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

Microsoft Visual C++ .NET Professional Projects - Premier Press

.pdf
Скачиваний:
180
Добавлен:
24.05.2014
Размер:
26 Мб
Скачать
☆
CREATING WEB SERVICES

710 Project 7

while(dataReader->Read())

{

i++;

}

dataReader->Close();

In the preceding code:

The set_CommandText method of the SqlCommand object is used to set

The Read method of the DataReader class moves to the next record.

the command text.

Y

 

 

L

 

F

Once the total number of the records is calculated, close the dataReader

 

A

object. It needs to be reopened since a DataReader is forward-only and

read-only.

 

The contents of the Product tableMwill be stored in an array and returned by the

 

T

Web service. Declare an array as shown here:

ArtArray list1=new ArtDataEgc[i];

All that remains to be done is to read from the database and fill the array with values. For accessing the content of each field from the DataReader object, you will use the get_Item method, which accepts either a string containing the name of the field or an integer that represents the index of the field:

dataReader=sCommand->ExecuteReader(); i=0;

while(dataReader->Read())

{

list1[i].ProdID=(dataReader->get_Item(“ProdID”))->ToString(); //Similarly for all the other fields

i++;

}

dataReader->Close(); return list1;

Once the array has been initialized, return the array to the calling application.

The following is the complete method:

Team-Fly®

CREATING A WEB SERVICE USING MANAGED EXTENSIONS Chapter 23 711

ArtArray Class1::getArtList()

{

int i=0;

SqlConnection *sConn=new SqlConnection();

sConn->set_ConnectionString(“Data Source=saik-d185;Initial

Catalog=ArtShop;Integrated Security=SSPI”);

sConn->Open();

SqlCommand *sCommand=new SqlCommand(NULL,sConn);

SqlDataReader *dataReader;

sCommand->set_CommandText(“select ProdID, ProdType, ProdName,ProdPrice,PictureFile from Product where ProdStatus=’unsold’”);

try{ dataReader=sCommand->ExecuteReader(); while(dataReader->Read())

{

i++;

}

dataReader->Close();

ArtArray list1=new ArtData __gc[i];

dataReader=sCommand->ExecuteReader(); i=0;

while(dataReader->Read())

{

list1[i].ProdID=(dataReader->get_Item(“ProdID”))->ToString(); list1[i].ProdType=(String *)dataReader->get_Item(“ProdType”); list1[i].ProdName=(String *)dataReader->get_Item(“ProdName”); list1[i].ProdPrice=(dataReader->get_Item(“ProdPrice”))->ToString(); list1[i].PictureFile=(String *)dataReader->get_Item(“PictureFile”); i++;

}

712 Project 7 CREATING WEB SERVICES

dataReader->Close(); return list1;

}

catch(Exception *e)

{

Console::WriteLine(e->Message);

}

}

Next, you will add a method that supports placing an order. This method will be called from any of the affiliated Web sites that are selling Art-Shop’s products. The method will simply insert a record into the Orders table. The structure of the table is as follows:

OrderID. Stores the order number. It is the primary key field of type

integer.

CustId. Stores the customer ID. It is of type integer and has a foreign key relationship with the Customer table.

ProdId. Stores the product ID. It is of type integer and has a foreign key relationship with the Product table.

OrderDate. Stores the date on which the order was placed. It is of type

Datetime.

OrderStatus. Stores the status of the order and stores either Pending or

Cleared.

SessionID. Stores the sessions ID of the visitor as received from the Web server.

Add the following code to the ProdService.h file, after the declaration of the

getArtList method:

[System::Web::Services::WebMethod(MessageName=”placeOrder”, Description=”Allows

affiliate partners to place an order at art-shop.com”)]

int placeOrder(String *,String *,String *);

In the WebMethod attribute, the name of the operation has been specified as placeOrder, and this is what will appear in the WSDL file.

Now, add the implementation of the preceding declaration to the ProdService.cpp file:

CREATING A WEB SERVICE USING MANAGED EXTENSIONS Chapter 23 713

int Class1::placeOrder(String *nProdID, String *nCustId,String *strDate)

{

String *strCmdTxt;

SqlConnection *sConn=new SqlConnection(); sConn->set_ConnectionString(“Data Source=Server1;Initial Catalog=ArtShop;Integrated Security=SSPI”); sConn->Open();

SqlCommand *sCommand=new SqlCommand(NULL,sConn);

SqlDataReader *dataReader;

Once you have connected to the database, create a command string to add a new record to the Orders table:

strCmdTxt=”insert into orders(ProdID,CustID,OrderDate) values(“; strCmdTxt=strCmdTxt->Concat(strCmdTxt,nProdID); strCmdTxt=strCmdTxt->Concat(strCmdTxt,”,”); strCmdTxt=strCmdTxt->Concat(strCmdTxt,nCustId); strCmdTxt=strCmdTxt->Concat(strCmdTxt,”,’”); strCmdTxt=strCmdTxt->Concat(strCmdTxt,strDate); strCmdTxt=strCmdTxt->Concat(strCmdTxt,”’)”); sCommand->set_CommandText(strCmdTxt);

try

{

dataReader=sCommand->ExecuteReader();

}

catch(Exception *e)

{

Console::WriteLine(e->Message); return 1;

}

return 0;

}

Once the Web service is built, it will be published to the ProdService virtual directory of your IIS installation.

714 Project 7 CREATING WEB SERVICES

Testing the Web Service

Access the published Web service by connecting to the URL http://localhost/ Prodservice/ProService.asmx/getArtList?, and compare the returned values to the values stored in the Product table of the ArtShop database.

Building a Web Service Consumer Using Managed C++

In this section, you will build a Managed C++ client to access the Web service. Remember that the steps you will follow are almost the same for building a client in any of the other .NET-compatible languages, such as C# and VB.NET.

Start Visual Studio .NET and create a new Visual C++ .NET project. Select Managed C++ Application from the Visual C++ Projects dialog shown in Figure 23-6.

FIGURE 23-6 Visual C++ Projects dialog box

Just as Visual Studio .NET simplifies the process of creating Web services, it makes it very easy to create Web clients, too. In this example, you will build a client that will access the data from the ProdService Web service, which you built earlier. The client can be built in any of the .NET languages and most often is an ASP.NET page.

CREATING A WEB SERVICE USING MANAGED EXTENSIONS Chapter 23 715

Here, you will build a Managed C++ client. You will add a list view to the client to display the items on sale at the art-shop.com site.

Next, right-click on the project name in the Solution Explorer window and select Add Web Reference. This will open the Add Web Reference dialog box, shown in Figure 23-7.

FIGURE 23-7 The Add Web Reference dialog box

This dialog box gives you the option of choosing a Web service from many locations:

Microsoft UDDI Directory. Allows you to select Web services from Microsoft’s production UDDI server.

Microsoft Test UDDI. Allows you to select Web services from Microsoft’s Test UDDI directory. This is used when you are developing Web service clients and want to use features like debugging.

Web reference on Local Web Server. Allows you to select Web services deployed on the local Web server installation.

In this project, you will select the Local Web Server option. Then, to the left of the dialog box, you see the root directory level DISCO XML document. At this point, you will take a small detour to see what this DISCO document is all about.

716 Project 7 CREATING WEB SERVICES

The process of investigating what Web services are available and how to use them is called Web service discovery, and DISCO files allow you to do it. DISCO files are actually XML Schemas that describe Web services. Visual Studio’s own version of the DISCO files are the VSDISCO files.

The default VSDISCO file is placed in the inetpub\wwwroot folder. It has the following structure:

<?xml version=”1.0” ?>

<dynamicDiscovery xmlns=”urn:schemas-dynamicdiscovery:disco.2000-03-17”>

<exclude path=”_vti_cnf” /> <exclude path=”_vti_pvt” /> <exclude path=”_vti_log” /> <exclude path=”_vti_script” /> <exclude path=”_vti_txt” />

</dynamicDiscovery>

The <exclude path=> tells the dynamic discovery process what folders to exclude from a search for Web services.

If you navigate to a VSDISCO file from a browser, a search is performed for all Web services in all the folders lying one level below the folder containing the VSDISCO file. The folders listed in the VSDISCO file are excluded from the search. An XML document containing information about all the Web services found is returned.

On the right of the Add Web Reference dialog box you will see a list of the available Web services, as shown in Figure 23-8.

Select the link for the ProdService Web service. This will display the VSDISCO file for the Web service, as shown in Figure 23-9. Also on the right side of the dialog box you will see two links:

View Contract. Displays the WSDL file for the Web service.

View Documentation. Displays a list of operations supported by the Web service. Here, you should see the description that you added to the

Description parameter of the WebMethod attribute. This helps a developer creating a client application to decide if a particular Web service has an operation that is required by a client application.

CREATING A WEB SERVICE USING MANAGED EXTENSIONS Chapter 23 717

FIGURE 23-8 Add Web Reference dialog box with a listing of available Web services

FIGURE 23-9 Add Web Reference dialog box with details of the selected Web services

Information about the operations supported by a Web service is obtained from the WSDL file. Take a quick look at the WSDL file:

<definitions xmlns:http=”http://schemas.xmlsoap.org/wsdl/http/”

xmlns:soap=”http://schemas.xmlsoap.org/wsdl/soap/”

www.art-

718 Project 7 CREATING WEB SERVICES

xmlns:s=”http://www.w3.org/2001/XMLSchema” xmlns:s0=”http://www.art-shop.com”

xmlns:soapenc=”http://schemas.xmlsoap.org/soap/encoding/”

xmlns:tm=”http://microsoft.com/wsdl/mime/textMatching/”

xmlns:mime=”http://schemas.xmlsoap.org/wsdl/mime/”

targetNamespace=”http://www.art-shop.com”

xmlns=”http://schemas.xmlsoap.org/wsdl/”>

The preceding code shows the <definition> root element of the WSDL document. As you can see, the default namespace has been changed to

shop.com.

Next is the <types> element that is used to contain schemas that describe the data types used in the Web service. The following is the declaration for the ArtData structure that you have used in the Web service:

<s:sequence>

<s:element minOccurs=”0” maxOccurs=”unbounded” name=”ArtData”

type=”s0:ArtData” />

</s:sequence>

Next, you will take a look at the <message> elements. These elements describe the SOAP message sent to and from the Web service. For example, your Web service has the following message declarations:

- <message name=”getArtListSoapIn”>

<part name=”parameters” element=”s0:getArtList” /> </message>

- <message name=”getArtListSoapOut”>

<part name=”parameters” element=”s0:getArtListResponse” /> </message>

<message name=”getArtListHttpGetIn” />

- <message name=”getArtListHttpGetOut”>

<part name=”Body” element=”s0:ArrayOfArtData” /> </message>

<message name=”getArtListHttpPostIn” /> - <message name=”getArtListHttpPostOut”>

CREATING A WEB SERVICE USING MANAGED EXTENSIONS Chapter 23 719

<part name=”Body” element=”s0:ArrayOfArtData” />

</message>

Each operation can be accessed using GET, POST, and SOAP methods. Each of these methods has a pair of In/Out messages. For example, in the preceding sam-

ple, getArtListHttpPostIn and getArtListHttpPostOut are the messages for

accessing the Web service using the HTTP POST method.

Next, you will take a look at the <port> elements:

<portType name=”Class1Soap”>

- <operation name=”getArtList”>

<documentation>This method returns a list of products available at artshop.com</documentation>

<input message=”s0:getArtListSoapIn” /> <output message=”s0:getArtListSoapOut” />

</operation>

</portType>

<port> types are a collection of a named set of operations. The port type also binds the collection of operations to the protocol used, such as HTTP POST and HTTP GET. The Operations node lists one or more methods that a Web service will expose.

The last element that you need to be aware of is the <binding> element:

<binding name=”Class1HttpGet” type=”s0:Class1HttpGet”> <http:binding verb=”GET” />

- <operation name=”getArtList”> <http:operation location=”/getArtList” />

- <input> <http:urlEncoded />

</input>

- <output>

<mime:mimeXml part=”Body” /> </output>

</operation>

</binding>