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

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

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

520 Chapter 12 • Creating an ADO.NET Shopping Cart

Figure 12.14 Creating the Booksource Web Service

Creating the Data Connection

Data Connections can be created in several ways. Let’s look at how the VS.NET Wizard does this. For this example, we’ll create a connection to an Access database.The steps for MS SQL will be slightly different.

1.Open the Server Explorer, and select View | Server Explorer from the menu.

2.Right-click Data Connection, then select Add connection.

3.Select the Provider tab.

4.Select the appropriate provider. For access, select Jet 4.0 OLEDB Provider.

5.Click Next.

6.Select the database name by clicking the Browse… button and navigating to your database.

7.Click Test Connection.You should get a pop-up window that says

Connection succeeded.

8.Click OK.

9.Click OK.You now have a data connection.

www.syngress.com

Creating an ADO.NET Shopping Cart • Chapter 12

521

While in design mode, you can drag and drop this connection onto your

.asmx page.This will add the following to our code-behind page as the first line in the service public class:

private System.Data.OleDb.OleDbConnection oleDbConnection1;

Connection string information will also be added to the InitializeComponent() method. Alternatively, we can still create a connection string by creating a .udl file on the desktop, double-clicking it and following the dialogs.With this method, we will have to insert the code ourselves, as follows:

1.In C#, add Using System.Data.OleDb to the top “using” section.

2.Then add the following inside the service class:

private OleDbConnection myConnection = new OleDbConnection();

3.Add the following to a method (Page_onload, or a method of your own creation):

myConnection.ConnectionString =

[the string obtained from the udl file]

We will take a closer look at adding a connection when we create the “sellerAdmin” service in the next section.

Creating a Web Service

All of the code for the Web Services in this chapter can be found on the CD. (See adminCustomer.asmx.cs, sellerAdmin.asmx.cs, getBooks.asmx.cs, getCategories.asmx.cs, getCustomer.asmx.cs, loginCustomer.asmx.cs, orderBooks.asmx.cs, and sellerAdmin.asmx.cs.)

Let’s take a closer look at adding a connection by creating the “sellerAdmin” Service.To create this service follow these steps:

1.Create the connection object.

2.Set the connection string.

3.Create the Command object.

4.Create the Parameter objects and assign their values.

5.Execute the procedure.We will be using the AdminAddBook proc. It takes the following parameters: BK_ISBN, BK_Author, BK_Price,

BK_Title, BK_Description, CAT_ID, BK_ImagePath.

6.Return string indicating success or failure of the operation.

www.syngress.com

522 Chapter 12 • Creating an ADO.NET Shopping Cart

Now let’s get started.To accomplish Step 1 (creating the connection object), first create a new C# Web Service and name it sellerAdmin.asmx. Add this directive to the top “using” section:

Using System.Data.OleDb;

Scroll down to below the method named Dispose(bool disposing). Add the following:

protected OleDbConnection sellerAdminConn = new OleDbConnection();

This accomplishes the creation of the connection object. Now, for Step 2 (setting the connection string), add the following:

protected void init()

{

this.sellerAdminConn.ConnectionString =

@"Provider=SQLOLEDB.1;

Persist Security Info=False;

User ID=[user id]; password=[password]; Initial Catalog=[Database

Name];

Data Source=[Server Name]"

}

Note that the use of the “@” before the connection string is required.This accomplishes Step 2.

For Step 3, (creating the Command object), first create a new method called addItem. It should have parameters corresponding to the stored procedures parameters, and should return a string indicating success or failure of the operation:

public string addItem(string ISBN,string author,double price, string

title,string description,string imagePath, int CAT_ID)

Now create a Command object that references the AdminAddBook proc:

OleDbCommand addItem =

new OleDbCommand("AdminAddBook",this.sellerAdminConn);

addItem.CommandType = CommandType.StoredProcedure;

This accomplishes Step 3.

For Step 4 (creating the Parameter objects and assigning their value), we will create Parameter objects for ISBN, author, price, title, description, imagePath, and CAT_ID, then set their values. Here is the code for “isbn”:

www.syngress.com

Creating an ADO.NET Shopping Cart • Chapter 12

523

OleDbParameter addISBN =

addItem.Parameters.Add("@BK_ISBN",OleDbType.Char,15);

addISBN.Value = ISBN;

Note that “@BK_ISBN” is the name of the parameter we are assigning a value to;“OleDbType.Char” is its datatype (it should be compatible with the field in the database); and “15” refers to the character size as defined for the field in the database.

The code to create Parameter objects for each of the method parameters is nearly identical, and can be found on the CD (see: sellerAdmin.asmx.cs).This accomplishes Step 4.

Now, for Step 5 (executing the procedure), we will open the connection and execute the query. Since the stored procedure performs an insert operation it will return an “int” containing the number of rows affected.Therefore, we will use the command ExecuteNonQuery.

this.sellerAdminConn.Open();

int queryResult = QueryObject.ExecuteNonQuery();

This accomplishes Step 5. Now close the connection and return the result of executing the proc (this is Step 6). Note that our method returns the following string:“success” or the generated error message.

this.sellerAdminConn.Close(); if ( queryResult != 0)

{

return "Success";

}

else

{

return "error: QueryResult= " + queryResult;

}

This accomplishes Step 6. Since all of the Web methods have similar logic, we can combine some of this code into a method that each Web method calls:

protected string ExecuteQuery( OleDbCommand QueryObject)

{

this.sellerAdminConn.Open();

int queryResult = QueryObject.ExecuteNonQuery();

www.syngress.com

524 Chapter 12 • Creating an ADO.NET Shopping Cart

if ( queryResult != 0)

{

this.sellerAdminConn.Close(); return "Success";

}

else

{

return "error: QueryResult= " + queryResult;

}

}

We need to add one more thing to our method to make it accessible as a Web method:

[ WebMethod(Description="Adds a new book to the books table",

EnableSession=false)]

Putting it all together, we get the following:

using

System;

using

System.Collections;

using

System.ComponentModel;

using

System.Data;

using

System.Diagnostics;

using

System.Web;

using

System.Web.Services;

using

System.Data.OleDb;

namespace bookSource

{

public class sellerAdmin : System.Web.Services.WebService

{

public sellerAdmin()

{

InitializeComponent();

}

protected override void Dispose( bool disposing )

www.syngress.com

Creating an ADO.NET Shopping Cart • Chapter 12

525

{

protected OleDbConnection sellerAdminConn = new OleDbConnection();

}

protected void init()

{

this.sellerAdminConn.ConnectionString = @"Provider=SQLOLEDB.1; Persist Security Info=False; User ID=[user id]; password=[password];

Initial Catalog=[Database Name];

Data Source=[Server Name]";

}

protected string ExecuteQuery( OleDbCommand QueryObject)

{

this.sellerAdminConn.Open();

int queryResult = QueryObject.ExecuteNonQuery(); if ( queryResult != 0)

{

this.sellerAdminConn.Close(); return "Success";

}

else

{

return "error: QueryResult= " + queryResult;

}

}

[ WebMethod(Description="Adds a new book to the books table", EnableSession=false)]

public string addItem(string ISBN,string author,

double price, string title,string description,

www.syngress.com

526 Chapter 12 • Creating an ADO.NET Shopping Cart

string imagePath, int CAT_ID)

{

try

{

this.init(); OleDbCommand addItem =

new OleDbCommand( "AdminAddBook",

this.sellerAdminConn);

addItem.CommandType = CommandType.StoredProcedure;

OleDbParameter addISBN = addItem.Parameters.Add(

"@BK_ISBN",OleDbType.Char,15); addISBN.Value = ISBN;

OleDbParameter addAuthor = addItem.Parameters.Add( "@BK_Author",OleDbType.Char,80);

addAuthor.Value = author;

OleDbParameter addPrice = addItem.Parameters.Add(

"@BK_Price",OleDbType.Currency,8); addPrice.Value = price;

OleDbParameter addTitle = addItem.Parameters.Add(

"@BK_Title",OleDbType.Char,75); addTitle.Value = title;

OleDbParameter addDescription =addItem.Parameters.Add(

www.syngress.com

Creating an ADO.NET Shopping Cart • Chapter 12

527

"@BK_Description",OleDbType.Char,255); addDescription.Value = description;

OleDbParameter addImage = addItem.Parameters.Add(

"@BK_ImagePath",OleDbType.Char,50); addImage.Value = imagePath;

OleDbParameter addCatId = addItem.Parameters.Add(

"@CAT_ID",OleDbType.Integer,4); addCatId.Value = CAT_ID;

return this.ExecuteQuery( addItem );

}

catch(Exception e)

{

return e.ToString();

}

}

.

.

.

In this section, we created the sellerAdmin Web Service and the additem Web Service method. In the next section, we will look at how to test the Web Service and its methods.

Testing a Web Service

We can test our service by performing the following steps:

1.In VS.NET right-click the .asmx file (sellerAdmin.asmx), and select Set as start page.

2.Press F5 to run it.This will take a few seconds to compile and run.

3.When the browser loads, you should see something like Figure 12.15.

www.syngress.com

528 Chapter 12 • Creating an ADO.NET Shopping Cart

Figure 12.15 Web Service Listing

4.To test the service addItem, click its link. An input form will be displayed, prompting you for values for its parameters. See Figure 12.16.

5.Fill in the appropriate textboxes and click Invoke.

6.Since this service returns a datatype string, we should see something like Figure 12.17.

This shows that the method has completed successfully and returned the corresponding output.These steps can be repeated for each of the remaining methods: removeItem, updateItem, addCat, removeCat, and updateCat. Each of these methods is coupled with a corresponding stored procedure (MSSQL) or parameterized query (MS Access).

The following is a function prototype overview of the process-flow or steps involved in creating each of these Web methods. See if you can create and test these Web methods on your own, then compare them to the source on the CD. The sellerAdmin Web service and all of its methods can be found on the CD (see sellerAdmin.asmx.cs).

www.syngress.com

Creating an ADO.NET Shopping Cart • Chapter 12

529

Figure 12.16 Testing a Web Service

Figure 12.17 Results of invoking the addItem Web Service

removeItem (int isbn) Removes a book item from the database.

1.Call init().

2.Create Command object accessing the AdminRemoveBook proc.

3.Create the Parameter object and assign its value.

4.Execute the procedure. Call ExecuteQuery(commandObj).

www.syngress.com