1. Trang chủ
  2. » Công Nghệ Thông Tin

Teach Yourself the C# Language in 21 Days phần 9 ppsx

81 347 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Tic Tac Toe
Trường học Standard University
Chuyên ngành Computer Science
Thể loại Bài tập
Năm xuất bản 2023
Thành phố Standard City
Định dạng
Số trang 81
Dung lượng 1,07 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The data provider is used to interact between the database and your program.. More specifically, four key classes areused as a part of the data provider: xxxConnection Used to connect to

Trang 1

184: new System.Drawing.Font(“Microsoft Sans Serif”,

185: 20.25F,

186: System.Drawing.FontStyle.Regular, 187: System.Drawing.GraphicsUnit.Point, 188: ((System.Byte)(0)));

189: this.btnBottomMiddle.Location = new System.Drawing.Point(96, 160); 190: this.btnBottomMiddle.Name = “btnBottomMiddle”;

191: this.btnBottomMiddle.Size = new System.Drawing.Size(64, 56); 192: this.btnBottomMiddle.TabIndex = 7;

204: this.btnBottomLeft.Location = new System.Drawing.Point(16, 160); 205: this.btnBottomLeft.Name = “btnBottomLeft”;

206: this.btnBottomLeft.Size = new System.Drawing.Size(64, 56);

Trang 2

255: this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

256: this.ClientSize = new System.Drawing.Size(256, 286);

281: public static void Main()

LISTING T&R 4.1 continued

Trang 3

288: string tmpText = origText;

289: if (origText == “X” || origText == “O” ) 290: {

291: // Already a character in section 292:

310: // Check to see if game is over

311: // val == character for turn.

312: private void checkEndGame(string val) 313: {

314: bool gameover = false;

315:

316: // First check for a winner

317: if( btnTopLeft.Text == val )

Trang 4

377: // Check to see if game over because of win

378: if( gameover == true)

379: {

LISTING T&R 4.1 continued

Trang 5

392: // game over do end game stuff

393: MessageBox.Show(“Game Over - No winner!”);

Trang 6

429:

430: // Set X or O text on grid button

431: private void btnTicTac_Click(object sender, System.EventArgs e)

432: {

433: // convert the sender object to a button:

434: Button tmpButton = (Button) sender;

435: // Set the text of this button:

This is a Windows application, so you will want to target the compiling as a winexe

With the Microsoft C# command-line compiler, this is done by using the /target:or/t:

flags Additionally, you may need to reference the windows forms classes in the

com-mand line:

csc /r:System.Windows.Forms.dll /t:winexe TicTac.cs

LISTING T&R 4.1 continued

Depending on your compiler, you may not need to include the reference to

System.Windows.Forms.dll in the command line.

Trang 7

The source code for this listing is available on the included CD Any updates

to the code will be available at www.TeachYourselfCSharp.com

Note

Trang 8

• Review key database terminology.

• Learn about ADO.NET

• Use ADO.NET to retrieve data from a database

• Discover how to use a DataReader

• Add data to a database

Trang 9

Understanding Key Database Concepts

On Day 15, “Using Existing Routines from the NET Base Classes,” you learned how toread and write simple text files using streams Using classes such as StreamWriter,

StreamReader,BinaryWriter, andFileStream, you were able to both read information fromdifferent files and write information

In real-world applications, you will often need a more robust set of classes and routines

to work with data and information Instead of storing everything as pure text or purebinary information, you will want to store items as different data types with differentcharacteristics You won’t want to store integers and strings; instead, you will want tostore information such as prices and titles Information such as this is best stored in adatabase

Data becomes more useful when it is stored in a grouping For example, if you create anapplication to track videos that are available for a rental, you might have a group ofinformation that describes the videos and a group of information that describes the cus-tomers For customers, this information may include their name, address, phone number,and membership number, along with the date they obtained rental privileges You mayalso keep information on the media in the store For example, you may keep track oftitle, rating, length, format, release date, and price to buy A third set of information thatyou might want to track is the videos that a customer rented and when he or she rentedthem Obviously, a lot more information can be tracked; however, most of this informa-tion can be grouped

If you started to write programs using the file classes you learned on Day 15, you wouldfind that it would take a lot of work to simply read in a date or a dollar number

Additionally, storing the information in a straight text or binary file would not be veryefficient Instead, information can be stored in databases such as Oracle, Microsoft SQLServer, mySQL, and Microsoft Access A database system such as these helps organize,store, and access the information

Understanding the Terminology

A single piece of information, such as a name or an address, is called a field.

Another name for a field is a column; you’ll understand why in a second A

Be aware that entire books have been written on the topic of data gramming with C# and NET In today’s lesson, you will learn quite a bit; however, this just scratches the surface of everything there is to learn about database programming with C#.

pro-Note

N EW T ERM

Trang 10

group of related fields is called a record Another name for a record is a column An

example of a record or column is the information traced on a video—this may be the

title, media, price, and other information A set of records, or information on a number of

titles, is kept as a fil A file is also known as a table A group of one or more related files

is considered a database.

You’ve just learned a lot of terms In general, the terms row, column, and table are used

within the context of NET These terms come from the fact that you can present data in

a table format, as shown in Figure 18.1

One other term worth mentioning here is dataset A dataset is one or more

tables that have been copied from a database into memory

Note

Introducing ADO.NET

Because most real-world applications use data stored in a database, it shouldn’t be a

sur-prise that strong database support is a part of the NET Framework Regardless of

whether your data is stored on your local machine, on a network, or somewhere across

the Internet, routines exist to help you access that information

FIGURE 18.1

Tables, rows, and

columns.

Rows/Records Columns/Fields

Table: Videos

Trang 11

The primary data access technology for tapping into a database from NET is ADO.NET.ADO.NET provides a way to connect to a database and to manipulate the data within it Accessing databases is a slow process in terms of how fast your application will execute.Keeping a database open and working with specific data while the database is beingaccessed is a resource-intensive process In general, you will want to access and connect

to a database for the shortest periods of time possible

In the past, people opened a database at the beginning of their application They viewed,added, updated, and deleted information in the application Finally, when the applicationwas ready to end, they closed the database This mode of operation is fine if you are theonly one using the database and if the database is on your local machine; however, if youare working with a database across the Internet, or if you are sharing the database withothers, this method of operation is very inefficient

One of the key features of ADO.NET is that it provides classes and methods for ing a database in a disconnected sort of way Instead of accessing the database the entiretime your application is running, you access it only when you really need to The waythis works is that, using ADO.NET classes, information is copied from the database intothe memory of your own computer You can then disconnect from the database Aftermanipulating the data in memory, you can again connect to the database and have thechanges made

access-Connecting to and Working with a Database

Connecting to the database, retrieving data from the database, updating or ing the data in the database, and performing other functions directly related to

delet-the database are all done with a data provider The data provider is used to interact

between the database and your program

A data provider is a set of classes that you use More specifically, four key classes areused as a part of the data provider:

xxxConnection Used to connect to the database

xxxCommand Used to execute a command against the database

xxxDataReader A special class used to get a set of data from the database

that you can view This can be viewed only sequentially,and the data can’t be changed

xxxDataAdapter Used to get a set of data from the database that you can

then manipulate You use this to make the changes to thedatabase as well

N EW T ERM

Trang 12

The actual names for the key data provider classes are dependent upon the data provider

you use Microsoft’s NET Framework contains two different data providers The

Microsoft SQL Server NET Data Provider is specifically tailored for Microsoft SQL

Server 7.0 or later The other, OleDb NET Data Provider, is a more generic provider that

connects to a number of different databases, including Microsoft Access and Oracle

The different data provider classes are accessed from different namespaces The SQL

Server data provider classes can be found in System.IO.Data.Sql The names of the

classes within this provider start with the prefix Sql For example, the connection class

mentioned previously (xxxConnection) would be SqlConnectionif the SQL Server provider

were used

The OleDb classes can be found in System.IO.Data.OleDB The prefix for these classes is

OleDb The connection class for this data provider would be OleDbConnection

In today’s lessons, the OleDb data provider is used If you are using a SQL

Server database, you should switch to the SQL Server data provider It is

optimized for Microsoft SQL Server, so it can provide for better

perfor-mance If you use the SQL Server provider, you should change the OleDb

pre-fix used in the examples to an Sql prefix.

Note

Making the Connection to the Database

When using a database, the first thing you must do is open it To open a database, you

must first connect to it

You create a connection by using the xxxConnectionclass mentioned earlier Using this

class, you instantiate a connection object:

OleDbConnection myConnection = new OleDbConnection(myConnectionString);

As you can see,myConnectionis created in the same way that other objects are created

The one unique thing is the myConnectionStringvalue that is passed to the constructor

This string contains information about connecting to a database The exact values placed

in this string vary depending on the database, access rights, and other information

spe-cific to the database you are opening For example, if you want to open a Microsoft

Access database that does not have any security included, you could set

myConnectionStringas follows:

string myConnectionString = @”Provider=Microsoft.Jet.OLEDB.4.0;User Id=;

Password=;Data Source=Videos.mdb”

Trang 13

You can see that the string is composed of four different areas that are separated by colons:

semi-Provider This defines the data provider that will be used In this case, it is

Microsoft Jet, which is the provider for Microsoft Access If youwere using a Microsoft Access database, you would most likely usethis same provider

User ID This is the ID of the account to use to access the database In the

case of the database used here, no ID is needed

Password This is the password associated with the User ID Again, because

there is no security being used on the example database, no value isset equal to the Password

Data Source This is the database name and location In the example provided

here, the data source is the Videos.mdb database that is in the rent directory

cur-If you were accessing a different database, your values would be different You may alsoneed to include additional values The values that you will provide are the ones needed

by your database If you are unsure of what is needed, check with your database istrator Examples of other connection strings are shown here:

admin-“Provider=MSDAORA; Data Source=ORACLE8i7;Persist Security Info=False;I

➥ntegrated Security=yes”

“Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\databases\Contacts.mdb”

“Provider=SQLOLEDB;Data Source=MySQLServer;Integrated Security=SSPI”

After you have created your connection object, you can use it to open the database Youopen the database by calling the Openmethod of the connection object:

MyConnection.Open();

AfterOpenis called, a connection to the database should be opened and ready to use Ofcourse, if the database doesn’t exist or if there is something wrong with the database, anexception will be thrown

You should always use exception handling when using database routines You want to control your application’s reaction to problems such as a miss- ing database In today’s examples, exception handling is left out to save space In the exercises, you will see an example of using exception handling with database access.

Note

Trang 14

Executing a Command

With a database opened, the next step is to issue one or more commands to the database

Commands are issued to the database by using a command object that is associated to

your connection object You will want to first create the command object You will then

apply a command to the command object Finally, you will execute the command

To create the command object, you use the xxxCommand class Because you are using the

OleDb provider in this chapter, you would use the following statement to create a

com-mand object named myCommand:

OleDbCommand myCommand = new OleDbCommand();

You can then associate the command object with the connection object by setting the

command’s Connectionproperty:

myCommand.Connection = myConnection;

You now have a command object that you can use When the command object is

exe-cuted, it will use the database associated with myConnection

Before you can execute the command, you need to associate a SQL query or a stored

procedure with the command To make this association, you assign the SQL query or

stored procedure to the CommandTextproperty:

myCommand.CommandText = “SELECT * FROM Titles ORDER BY Title”;

As you can see, this assigns a SQL query to the CommandTextof the myCommandobject With

this assignment, the command can now be executed

How you execute a command depends on the result you expect from the command You

will consider executing a command generally in three ways:

• ExecuteReader

• ExecuteNonQuery

• ExecuteScalar

You use ExecuteReaderif you plan to retrieve data from the database If you plan to make

changes to the database but don’t expect values to be returned, you can use

ExecuteNonQuery Finally, if you want to get just a single value from the database, you can

useExecuteScalar

Retrieving Data with a DataReader

Most likely, your first foray into a database will be to read information from the database

to display A special class has been created to enable you to easily and efficiently read

Trang 15

data from a database This is the DataReader The downsides to the DataReaderare that itcan only read data (it can’t write) and that it does only a forward read This means youcan go through the data only once With these downsides, it is worth saying again—thebenefit of the DataReaderis that it is easy and efficient.

When you initially create a DataReader, you don’t need to instantiate it Instead, whenyou execute a command against the database, it returns a DataReaderobject to you Thefollowing creates a DataReadernamedmyDataReaderand sets it to null:

OleDbDataReader myDataReader = null;

You can then execute your Commandobject, using the ExecuteReadermethod:

myDataReader = myCommand.ExecuteReader();

Remember,myCommandis associated with your connection, plus it contains the SQL ment or stored procedure that you assigned earlier After it is executed,myDataReaderwillcontain the results of the command that you assigned

state-This result will most likely be a set of records from the database You can now loopthrough these records by calling the Readmethod of the DataReader Each time you calltheReadmethod, the next record is read

You can access the values in each record by getting their values with a Getxxxmethod

To use most of these methods, you must know the data type of the information you areretrieving If you don’t know the type, you will want to use the GetValuemethod.Table 18.1 presents a list of the Getxxxmethods that you can use

TABLE 18.1 TheGetxxxMethods of the DataReader

Method Returns

GetBoolean A Boolean value (bool)

GetByte A byte value

GetBytes An array of bytes

GetChar A character value (char)

GetChars An array of characters

GetDataTypeName The name of the source’s data type

GetDateTime A DateTime object

GetDecimal A decimal value

GetDouble A double value

GetFieldType A Type value

GetFloat A float value

Trang 16

GetInt32 An integer value (int)

GetOrdinal The ordinal, when passed the column title

GetSchemaTable A DataTable object

GetTimeSpan A TimeSpan object

GetValues Gets all the attribute values in the current row

With the DataReaderexecuted, you can easily set up a command to loop through the

retrieved information For example, to print the value of the first item in each row or

record retrieved, you could use the following simple loop:

Closing the Database

Just as you should close the DataReaderwhen you are finished with it, you should close

the database connection You close the connection by calling its Closemethod:

myConnection.Close();

Pulling It All Together

You’ve covered a lot up to this point When you pull together all of the snippets, you can

create a simple application that can read through a set of records within a database

Listing 18.1 presents an application that uses the code snippets you’ve seen up to this

point This listing uses a Microsoft Access database named Videos This database can be

found on the CD included with this book

TABLE 18.1 continued

Trang 17

LISTING 18.1 ReadVids.cs—Using the DataReader

Listing 18.1 does not include exception handling, to keep the listing short It

is highly recommended that you never create a database application out including exception handling because too many things can go wrong For example, the database could be missing

with-Exercise 1 at the end of this chapter instructs you to add exception handling

to this listing The answer to that exercise is provided on the CD-ROM,

“Answers.”

Note

Trang 18

XBx - Blood Wake (Teen) - $49.99

DVD - Boys Don’t Cry (R) - $9.99

DVD - Family Man, The (PG-13) - $12.99

DVD - For Love of the Game (PG-13) - $9.99

XBx - Fuzion Frenzy (Everyone) - $49.99

LISTING 18.1 continued

OUTPUT

Trang 19

DVD - GalaxyQuest (PG) - $16.99 DVD - Gladiator (R) - $19.99 XBx - Halo Combat Evolved (Mature) - $49.99 DVD - Harry Potter and the Sorcerer’s Stone (PG) - $12.99 VHS - Hollow Man (R) - $9.99

DVD - Independence Day Collector’s Edition (PG-13) - $19.99

DVD - X-Men (PG-13) - $14.99 VHS - You Can Count On Me (R) - $9.99 DVD - You’ve Got Mail (PG) - $14.99 TOTAL: $1,727.36 AVG PRICE: $16.77Before running this listing, you need to make sure that the Videos.mdb file islocated at C:\ If you want this file to be somewhere else, change the path used inthe data source shown in Line 19

This listing uses everything you’ve read about in today’s lesson up to this point In Line 16, a connection string named myConnectionStringis created This includes informa-tion to use Microsoft Access database (see Line 17) as well as the previously mentionedlink to the data source

vari-Note

In Lines 20–21, two variables are set up to track totals These totals will be filled in asthe records are read In Line 22 a SQL query is created and also assigned to a string vari-able,mySelectQuery This query selects all the information from each row in the videostable It then orders (sorts) them by their titles

In Line 24, the connection object,myConnection, is created using the connection stringthat was created in Line 16 In Line 27, an OleDbCommandobject is created This is doneslightly differently than what you saw earlier As you can see, the query (mySelectQuery)

is passed as the first item along with the connection object

Line 30 uses the connection object that you created for the video database to actuallyopen the database using the Openmethod After this line is executed, you will have anopened, usable connection to the data

Trang 20

Line 32 creates the DataReaderthat will be used to read the data Line 33 calls the

ExecuteReadermethod using your command object This returns the data to your reader

object,myDataReader With the reader full of data, you are ready to loop through it This is

accomplished with the whileloop in Lines 35–47 Each time through, you call the Read

method to get the next record

With each loop, Lines 37–43 contain a call to WriteLine Although this looks

compli-cated, it isn’t Getxxxmethods are used to get data from the records In this case, the 10

element is the medium type Because the medium type is a string,myDataReaderuses the

GetStringmethod and passes the value 9, which gives the tenth element because of the

zero offset The PadLeftis a standard string function that enables you to pad a value with

a character—in this case, a string Line 40 works in the same way, getting the second

element, which is the title Line 43 uses the GetDecimalmethod to get the fourth value,

which is a currency value This is retrieved as a decimal value and then is displayed

using the currency formatter ({0:C})

In Line 45, the fourth value is used a second time In this line, the value is added to a

total accumulator In Line 46, a counter is being used to count the number of records that

are being counted

After the loop completes, Line 50 closes the DataReaderthat you were using You should

always close your DataReaders Line 53 closes the connection to the database Again, this

is something you should always do

This listing ends with the values of the counter variables being printed in Line 55 This

prints the total value of the videos along with the average value

I may sound like a broken record (or a CD with a skip), but this listing is missing

excep-tion handling In an exercise at the end of today, excepexcep-tion handling will be added You

should always include exception handling in your applications

Adding, Updating, and Deleting Data

Earlier, the Commandclass was mentioned In Listing 18.1, you used the ExecuteReader

method to read data from a database You can also use the command object to execute

other commands against the database This includes using it to do inserts, updates, and

deletes

Instead of using ExecuteReader, you use the ExecuteNonQuerymethod This method enables

you to execute a SQL query or a stored procedure against the database This method

returns the number of records impacted by the query Because it doesn’t return data, you

can’t use it for retrieving information However, this is perfect for inserts, updates, and

deletes

Trang 21

TheExecuteNonQuerycommand is used similarly to the ExecuteReadercommand You nect to and open the database, create a command object, and associate both the connec-tion and the query you want to execute with the Commandobject You then call

con-ExecuteNonQuery You should close the connection before exiting

The queries that you can assign are any valid SQL query or stored procedure This queryneeds to be valid for the specific database that you are using SQL is not exactly thesame across databases

In Listing 18.2, a simple insert query is created for Microsoft Access To make this ing simpler, a different table from within the Videos database is used When this listing isexecuted, two additional rows are added to the Names table

list-LISTING 18.2 Customers.cs—Updating with a SQL query

11: Customers myCustomer = new Customers();

12: myCustomer.Add(“Kyle”, “Rinni”, DateTime.Now.Date);

13: myCustomer.Add(“Kaylee”, “Rinni”, DateTime.Now.Date);

28: string myAddQuery = @”INSERT INTO [Names] “ +

29: @”(FirstName, LastName, JoinDate ) “ +

30: “VALUES ( \”” + FirstName + “\”,\”” +

31: LastName + “\”,\”” + Joined + “\”)”;

32:

33: try

Trang 22

Note that this listing also writes two additional rows into the Names table in the

Videos.mdb Microsoft Access Database located at C:\

The first thing you should notice is that a little bit of exception handling was

added to this listing The code for connecting and accessing the database is

con-tained within a trystatement starting in Line 33 If an error occurs with the database,

instead of having the application crash with an error, the exception is caught In Line 44,

a check is done to catch an OleDbException This is a general exception class for database

errors that may have occurred You can actually catch more specific errors if you want If

a database error is caught, it is simply printed to the console

Stepping back, you can see that much of the logic for connecting and opening the

data-base is the same as in the previous listing Where things start to truly differ is in Line 42

Instead of calling the ExecuteReadermethod, this line calls the ExecuteNonQuerymethod

This executes the myAddQuerythat was associated to myCommandin Lines 37–38 The call to

ExecuteNonQueryresults in the query being executed and a number being returned that is

equal to the number of rows affected In this case, a single line was added, so the value 1

should be returned

LISTING 18.2 continued

OUTPUT

A NALYSIS

Trang 23

After Line 42 completes, the exception-handling logic directs the program’s flow to the

finallyclause in Line 48 In Line 50, a check is made to see whether the connection tothe database was actually made If it was, it is closed in Line 51 If an exception hadbeen thrown before the connection had been made or opened, you wouldn’t have wanted

to close it because it wouldn’t have been opened

With the record updated and everything closed, the listing ends with Line 54 This ply prints the return value from having called ExecuteNonQuery This was done to showyou that the returned value did equal the number of records impacted: one

sim-This same logic can be used to do updates and deletes All you need to do is prepare theinformation that you want to update or delete and then associate it with the commandobject that you create

The SQL commands that you use must be appropriate for your database Although SQL for different databases looks similar, it often is not

Caution

Other Database Concepts

As mentioned at the beginning of today’s lesson, covering database topics and ADOcould fill several books I’ve provided you with a means of accessing and manipulatingdata in a database However, this is not the only means There are other ways, including

a more robust way to work with data from databases This includes the use ofDataSetsandDataAdapters There is also the capability to do data binding to controls Finally, youcan work with data in other formats, including XML This can be done in the same man-ner as working with databases

ADataSetis a copy of data from a database that is stored in the memory of yourcomputer Data is often manipulated by retrieving data and placing it into aDataSet This set may include multiple data tables as well as relationships between them.Unlike the DataReader, you are not locked into just reading data, nor are you forced toread the data only from beginning to end

AlthoughDataSets are on your local machine, they are not directly connected to a base Again, they are a copy of the data To pull this data from the database (and to putchanges back into the database), you use a DataAdapter

data-When working with DataSets, you often use a DataAdapter A DataAdapteris an objectthat contains a set of commands and a database connection You use a DataAdapteras anintermediary for working with the data and a database

N EW T ERM

Trang 24

Data binding is the process of associating a data to a control This is usually a control on

a form such as a DataGrid The binding of data makes it easy to present the data on the

control However, it doesn’t remove the need to do the adding, updating, and deleting

logic

Summary

In today’s lesson, you learned a little about working with ADO.NET and databases You

learned to use a number of key classes for manipulating data You learned an efficient

way to retrieve data using the DataReader You also learned a method for adding,

updat-ing, and deleting information from a database The lesson ended by exposing you to a

few of the terms that were not covered in regard to database programming

Q&A

Q What does ADO stand for?

A ADO stands for Active Data Objects

Q Isn’t ADO.NET a Microsoft standard? If so, will it be portable?

A ADO is a Microsoft standard; however, it is still being ported to other platforms.

For example, the mono project (www.go-mono.com) is including a port of ADO.NET

within its scope This should result in ADO.NET being supported on platforms

such as Red Hat Linux, FreeBSD, and the Mac

Q Is ADO.NET just a newer version of ADO?

A Yes and no ADO.NET continued what ADO started ADO.NET, however, is based

on the premise that the database may be disconnected from the application To

accomplish this, ADO.NET was written from the ground up

Q How comprehensive was today’s lessons in regard to databases and

ADO.NET?

A Today’s lessons barely scratched the surface of ADO.NET and database

develop-ment with NET Entire books focus on just ADO.NET

Workshop

The Workshop provides quiz questions to help you solidify your understanding of the

material covered and exercises to provide you with experience in using what you’ve

learned Try to understand the quiz and exercise answers before continuing to the next

day’s lesson Answers are provided on the CD

Trang 25

1 What is the difference between a column and a field?

2 Put the following in order from largest to smallest:

a Table

b Row/record

c Database

d Column/field

3 What four key classes are generally used by a data provider?

4 What is the difference between OleDbConnectionandSqlConnection?

5 In the following, what is the name of the database being used?

string myConnectionString = @”Provider=Microsoft.Jet.OLEDB.4.0;User Id=;

Password=;Data Source=Bobby.mdb”

6 What would the connection string be for accessing a Microsoft Access databasenamed Customers using the password secret and the user ID BradJ?

7 What method of OleDbCommandwould you use with a DataReader?

8 What method of OleDbCommandwould you use to delete a record from a table?

9 What method of the DataReaderwould you use to get an double value from arecord?

10 Why is exception handling important when working with databases?

Exercises

1 Add exception handling to Listing 18.1

2 Modify the listing in Exercise 1 so that the class contains a method that will accept

any valid connection string and still work Hint: From the Mainmethod, pass a nection string value to a new method

con-3 On Your Own: Using a database, create the tables for tracking data for a video

store Write the code for reading the information in the different tables

4 On Your Own: Create a windows form application that displays the information

from the DataReader

5 On Your Own: Create a windows form that allows the user to enter a first name

and a last name as well as a date Add the values to the Names table in theVideos.mdb database when the user clicks a button Make sure that the three valueshave been entered before actually adding the information

Trang 26

D AY 19

Creating Remote

Procedures: Web Services

Over the last couple of days, you have learned about creating applications thatuse windows forms If you are building applications for the Internet—or, morespecifically, the Web—you might not be able to use windows-based forms thatuse the System.Windows.Formsnamespace Instead, you might want to takeadvantage of the Web’s capability of working with numerous different systems

by using general standards, such as HTML and XML Today you begin the first of two days that dig into developing applications focused at the Web.Today you…

• Learn the basics about Web services

• Create a simple Web service using C#

• Understand how to generate a proxy file for using a Web service

• Use your Web service from a client program

Trang 27

Creating Web Applications

Two types of Web applications are covered: Web services and Web forms Each of thesehas its own use and its own applications Today you start with Web services

Examining the Concept of a Component

Before tackling the concept of a Web service, it is worth looking at the concept

of components A component is a piece of software that has a well-defined

inter-face, hidden internals, and the capability of being discovered By “discovered,” I meanthat you can determine what the component does without needing to see the code within

it In a lot of ways, a component is similar to a method It can be called with argumentsthat fit a set of parameters, and it has the capability of returning results

Web Services

The use of methods as components has been moved to the Web A Web

compo-nent can be referred to as a Web service A Web service is a compocompo-nent that

per-forms a function or service A Web service may also return information to the caller Thisservice resides somewhere on the Web and can be accessed from other locations on the

The topic of today’s lesson and tomorrow’s lesson—Web development— could fill entire books on its own To avoid adding a large number of pages

to these lessons, I make some assumptions If you don’t fit all these tions, don’t fret—you will still find lots of value in the concepts and code presented in today’s lessons

assump-My assumptions are as follows:

• You have access to a Web server or a Web service provider that can host Web services written to the NET runtime

• You are familiar with basic Web development concepts, including the use of HTML and basic client-side scripting

• You are using a computer that has a Web server running that ports Active Server Pages and ASP.NET (such as Microsoft Internet Information Server [IIS])

sup-• Your Web server is set up with the standard Inetpub/wwwroot tory Today’s lesson references this directory as the base directory or root directory of your Web server If you know how to set up virtual directories, you can use those as well

direc-Caution

N EW T ERM

N EW T ERM

Trang 28

Web For this service to be called, a number of elements must be in place First, the

caller must know how to call the service Second, the call must be made across the Web

(otherwise, it is just a service, not a Web service) Finally, the Web service must know

how to respond Figure 19.1 illustrates the Web service process

FIGURE 19.1

SOAP/HTTP The Internet

Calling Program

Web Service

In the figure, the Simple Object Access Protocol (SOAP) has been created to

communi-cate between a program and a Web service SOAP is a standardized way of formatting

information about method calls and data This formatting is based on the XML standard

Using SOAP, a program can communicate to a Web service, and the Web service can

communicate back

The calling program can be a C# program or a program written in any other

program-ming language Additionally, the calling program can be a browser or even another Web

service, and the Web service can be written in C# or any other language Because a

stan-dardized protocol—SOAP—is being used, the calling program can interact with the Web

service and vice versa

Although understanding SOAP is valuable, it is not critical for creating Web services.

Note

Three basic steps are involved in setting up and using a Web service:

1 Create the actual Web service

2 Create a program to use the service

3 Create a file that can help your program call the service This helper

program is called a Web proxy.

You’ll learn about creating each of these three parts in the following sections

Creating a Simple Component

Before creating a Web service, you create a simple class This class then is used as the

basis of your first Web service This class also is compiled as a routine within a library

Listing 19.1 contains the simple routine that will be used

N EW T ERM

Trang 29

LISTING 19.1 Calc.cs—A Basic Component

The result is a file named Calc.dll instead of Calc.exe

If you are using Visual Studio NET 2003, you can set the output type to get a library (Class Library) by selecting the properties of the project You can see the project properties in several ways One is to right-click the name

tar-of the project in the Solutions Explorer and select Properties from the

pop-up menu Alternatively, you can select the Properties option on the Project menu When you have the project’s Properties page displayed, change the Output Type to Class Library.

If you are using SharpDevelop, to set the project to create a library, select Project Options from the Project menus Within the Project Options dialog box, select the Configurations folder and then Code Generation In the Code Generation dialog box, you can change the compile target to Library Clicking OK applies this change.

If you are using another editor, consult your documentation or the help files In many Integrated Development Environments, including Visual Studio NET and SharpDevelop, you can select a library project type when initially creating the project.

Note

Trang 30

Looking at the listing, you see that the component will contain two methods in a

class named Calc.Addin Lines 8–11 add two numbers Subtractin Lines 12–15

returns the difference of two numbers Listing 19.2 presents a routine that can use these

If you compile this routine the normal way, you get an error saying that a type or

name-space could not be found:

csc myApp.cs

As you learned earlier in this book, you need to include a reference to the component

that you will be using—in this case,Calc Compile the main listing by including a

refer-ence to the file with the component that you created in Listing 19.1 This is done by

using the reference compile flag:

csc /r:Calc.dll myApp.cs

The/r:is the reference flag It tells the compiler to include the identified file, Calc.dll

The result is that myApp.cs will be capable of using the classes and methods in Calc.dll

If you are using an Integrated Development Environment, you can add a reference to

your library in the same manner as the other libraries you’ve referenced If your library is

in a different directory, you may need to browse to that directory

A NALYSIS

OUTPUT

Trang 31

Looking at the code in Listing 19.2, you can see that there is nothing differentfrom what you have done before The Mainroutine makes calls to the classes thatare available Because you included the Calc.dll in your compile command, theCalc

class and its AddandSubtractmethods are available

Creating a Web Service

TheCalcclass and its methods are nice, but the example in Listings 19.1 and 19.2 are for

a class located on a local machine A Web service uses a component across the Web Youwant to have the Calcmethods operate as Web services so that they will be accessibleacross the Web by any Web-based application This obviously adds complexity to the use

of the class

To create a Web service based on the Calcclass, you need to make some changes Listing 19.3 presents the Calcroutine as a Web service

LISTING 19.3 WebCalc.asmx—Making Calc a Web Service

1: <%@WebService Language=”C#” Class=”Calc”%>

In SharpDevelop, you can add a reference as well In the Project window, right-click References and then select Add Reference This displays the Add Reference dialog box Select the NET Assembly Browser Use the Browse button to find and select the library file that you created earlier The library will be added to your project.

Note

Trang 32

Several changes were made to this listing to make it a Web service As you can

see by glancing at the listing, none of the changes was major

The first change is in the name of the file Instead of ending with a cs extension, a Web

service always ends with an asmx extension This extension is a signal to the runtime

and to a browser that this is a Web service

The first coding change is in Line 1—a line with lots of stuff that may seem weird:

%@WebService Language=”C#” Class=”Calc”%

The<%@and%>are indicators to the Web server The Web server will see that this is a

Web service written in the language C# It will also know that the primary routine is

namedCalc Because the language is specified as C#, the server will know to read the

rest of the file as C# and not as some other language

When this service is first called, it is compiled You do not need to do the actual compile

yourself The Web server calls the correct compiler based on the language specified in

theLanguage=command

The next change that you can see is the inclusion of the System.Web.Servicenamespace in

Line 8 This is included so that the use of WebMethodandWebServicecan be done without

explicitly including the namespace name throughout the rest of the listing

In Line 10, the Calcclass is derived from WebService This gives your class the Web

ser-vice traits as defined within the NET Framework

The only remaining change is to identify each of the methods that you want to have

available to anyone accessing your service These are identified by including [WebMethod]

before the method, as has been done in Lines 12 and 18

That’s it: This Web service is ready to go

LISTING 19.3 continued

A NALYSIS

Trang 33

In the following sections, you learn how to create a proxy and how to call your Web vice You probably can’t wait to see your Web service in action—and you don’t have to.

ser-If you are running a Web server such as Microsoft’s Internet Information Server (IIS),you have a directory on your machine named Inetpub This directory has a subdirectorynamed wwwroot You can copy your Web service (WebCalc.asmx) to this directory When your new Web service is in that directory, you can call it by using your browser.You use the following address to call the WebCalc.asmx service:

http://localhost/WebCalc.asmx

When you use this address, you get a page similar to the page in Figure 19.2 If you have

an error in your Web service, you might get a different page, indicating the error

If you are using Visual Studio NET, you have the option to create a Web vice project This project provides you with the basic infrastructure for a Web service Like many other Visual Studio NET projects, it includes a lot of additional code

ser-SharpDevelop also includes a file template for creating Web services.

Selecting File, New, File takes you to the New File dialog box You can then select the category for Web services files This gives you several options for Web service files.

Other development environments may also include templates for creating Web services

Trang 34

Looking at this page, you can see that a lot of information is displayed regarding your

Web service Most important is that this page lists the two operations that can be

per-formed,AddandSubtract These are the two methods from your Web services class

If you click on either of these methods, you are taken to a second screen (see

Figure 19.3), which enables you to enter the parameters that your method expects

FIGURE 19.3

TheAddmethod within

the Web service.

In the case of the Addmethod, two parameters are expected:xandy This matches your

code in Listing 19.3 If you enter the values of 5and10, as you did in Listing 19.2, you

will see the result:

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

<int xmlns=”http://tempuri.org/”>15</int>

The result of 15is in there, but so is a bunch of other stuff The other stuff is the SOAP

information needed to send the information back to the calling routine

Creating a Proxy

The previous section showed you how to see your Web service in action by using your

browser on your local machine; however, it is more likely that you will want to use the

service from another program To do this, you need to set up a Web proxy

As mentioned earlier, this proxy helps your local program know where on the Web to

find the Web service It also contains the details for communicating to the Web service

(the SOAP stuff)

Trang 35

Writing a proxy can be a lot of work; however, there are utilities to help make this easier.One such utility is wsdl.exe, provided by Microsoft in its framework This command-linetool can be run using the following parameters:

wsdl WebService_file?wsdl /out:proxyfile

Here,wsdlis the name of the utility that you are executing and WebService_fileis thename and location of your Web service file The Web service name is followed by ?wsdl,which indicates that this is to generate a file using the wsdl standard For the Calcpro-gramming example, this is currently on your localhostserver; this could easily be on adifferent server, in which case this would be the URL to the service

The/out:flag is optional and is used to give your proxy a name If you don’t use the

/out:flag, your proxy will be named the same as your service I suggest adding proxytothe name of your proxy The following line creates the proxy file for the WebCalc.asmx

service and places it in the inetpub\wwwroot\directory with the name of CalcProxy.cs:wsdl http://localhost/WebCalc.asmx?wsdl /out:c:\inetpub\wwwroot\CalcProxy.csThe proxy file has a cs extension, which means that it is C# code that can be compiled.Listing 19.4 contains the code that was generated by wsdl using the WebCalc.asmx filethat you created earlier (no line numbers are provided)

LISTING 19.4 CalcProxy.cs—Generated Code from wsdl

// <autogenerated>

// -// This code was generated by a tool.

// -// This source code was auto-generated by wsdl, Version=1.1.4322.510.

Trang 36

public int Add(int x, int y) {

object[] results = this.Invoke(“Add”, new object[] {

x, y});

return ((int)(results[0]));

}

/// <remarks/>

public System.IAsyncResult BeginAdd(int x, int y, System.AsyncCallback

➥callback, object asyncState) {

return this.BeginInvoke(“Add”, new object[] {

x, y}, callback, asyncState);

}

/// <remarks/>

public int EndAdd(System.IAsyncResult asyncResult) {

object[] results = this.EndInvoke(asyncResult);

Trang 37

object[] results = this.Invoke(“Subtract”, new object[] {

x, y});

return ((int)(results[0]));

} /// <remarks/>

public System.IAsyncResult BeginSubtract(int x, int y, System.AsyncCallback callback, object asyncState) {

return this.BeginInvoke(“Subtract”, new object[] {

x, y}, callback, asyncState);

} /// <remarks/>

public int EndSubtract(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult);

return ((int)(results[0]));

} }

It is beyond the scope of this book to explain the code in this listing The important thing

to note is that it takes care of the SOAP stuff for you Before you can use it, however,you need to compile it As you’ve done before, you need to compile this listing as alibrary Remember, this is done using the target flag (/t:library):

csc /t:library CalcProxy.cs

The result is a file named CalcProxy.dll that you will use with the programs that callyour Web service

Calling a Web Service

The final step in using a Web service is to create the program that will call the service.Listing 19.5 presents a simple program that can use the WebCalcservice

LISTING 19.5 WebClient.cs—Client to Use WebCalc

Trang 38

When you compile this listing, you need to include a reference to the proxy file

that you previously compiled You do this the same way that you include any

library, with the /r:flag:

csc /r:CalcProxy.dll WebClient.cs

After it’s compiled, you have a program that can use the Web proxy (via the CalcProxy

program that you generated) to access the Web service that you created (WebCalc.cs)

You can see in Listing 19.5 that using the Web service is very easy In Line 11, you

cre-ate a Calcobject named cSrv This is then used to call the methods within the service In

reality, this is the same as if you were using a local library The difference is that you

created and used the Web proxy file that took care of connecting to the Calcroutines on

the Web server

Today’s lesson was broken into two parts You spent the first part setting up and using a

simple Web service You learned that a Web service is a piece of code residing

some-where on the Web that you can call from your program Because of communication

stan-dards that have been developed, calling and using such Web services has become

relatively easy

Trang 39

In tomorrow’s lesson, you will continue working with Web-based applications Ratherthan focusing on services, tomorrow you will focus on building Web applications thatuse forms

Q&A

Q The code in the Web service and in the client using the Web service is not very different from normal code Shouldn’t this be more complex?

A The code presented in today’s Web service and client was very simple A lot of

work has gone into creating standards for communicating across the Web Thecomplexity of Web services is in the communication The wsdl tool created thecomplex code for you By creating standards for communicating interaction, much

of the complexity has been removed from the applications Your applications canfocus on what they need to do rather than on communicating

Q Do I have to use wsdl.exe to generate the proxy code file?

A No You can write this code by hand, or you can use a development tool such as

Visual Studio NET that can help generate some of the code needed

Q Can windows forms, database routines, and other NET Framework classes be used with Web services?

A Because a Web service is accessed across the Web, and because a Web service

could be called from any platform, you should avoid using a graphical user face (GUI) within a Web service You can use database routines or NET

inter-Framework classes in your Web services Any routines can be used that are ported by the server running the Web service

sup-Workshop

The Workshop provides quiz questions to help you solidify your understanding of thematerial covered and exercises to provide you with experience in using what you’velearned Try to understand the quiz and exercise answers before continuing to the nextday’s lesson Answers are provided on the CD

Quiz

1 What is a Web service?

2 What is the file called that helps a client application communicate with a Web vice?

ser-3 What program can be used to create the code to communicate with a Web server?

Trang 40

4 How can you tell a Web service from an ASP.NET page?

5 How do you execute an ASP.NET page?

6 What is the SOAP returned from the WebCalc Web service if you enter 20for x

and10for y?

7 If you have a Web Service in a file named myService.asmx on a server named

www.myserver.com, what wsdl command would you use to create a proxy file named

myProxy in the wwwroot directory on your C: drive?

8 If you were using Microsoft’s command-line compiler, how would you compile the

proxy file generated in question 7?

9 How would you compile a program in a file named myClient.cs that uses the proxy

from question 8?

Exercises

1 What is the first line of a C# program that will be used as a Web service? Assume

that the Web service class name is DBInfoand that the first method is named

GetData

2 What changes need to be made to a method to use it in a Web service?

3 Add a Multiplymethod and a Subtractmethod to the WebCalc Web service

4 Create a new client that uses the MultiplyandDivideclasses created in Exercise 3

5 On Your Own: Amazon.com is one of many sites that have provided a Web

ser-vice At the time this book was written, you could access this Web service on the

Amazon.com Web site (www.Amazon.com) Incorporate this Web service into an

appli-cation Your application should allow you to see how well your favorite books are

doing at Amazon

Ngày đăng: 13/08/2014, 08:20

TỪ KHÓA LIÊN QUAN