Form 2 reappears after the user replies to the prom pt, the form shows the first two text boxes with their prior values as well as t he fourth text box for displaying a colum n value.. T
Trang 1Form 2 reappears after the user replies to the prom pt, the form
shows the first two text boxes with their prior values as well as t he fourth text box for displaying a colum n value The specific value in the bottom text box is t he one m atching row specified by the user’s reply to the prom pt
Figure 1 3 - 1 1 The client applicat ion form for t he Service1 W eb service in
the TableProcessor folder
The processing of the return values from the Colum nValues Web
m ethod illustrates a typical scenario A developer engineers an application so that it can accom m odate any of several scenarios For exam ple, a client application m akes a selection from the total set of colum n values to show the colum n value for just one row instead of the whole set of colum n values as in Figure 13-10 Figure 13- 12 tracks the process from designating database and table nam es to capturing the reply to the I nputBox prom pt to showing the specific colum n value t hat a user wants to view I n the top window, the user designates that they want results from the Custom ers table in t he Northwind database before clicking the button labeled Get Colum n Value The m iddle window shows the user indicated that t he
application should show the colum n value for the fift h row By the way, the prom pt adjusts autom atically to show the m axim um num ber of rows The application does this by running the RowCountWeb m ethod when processing a request to show a specific row value from the first colum n The bottom window in the figure reveals BERGS as t he colum n value for the fifth row in the first colum n You can easily confirm this out com e for yourself by exam ining the output in Figure 13- 10, which shows all the colum n values for the first colum n in t he Custom ers table from the
Northwind database
Trang 2Figure 1 3 - 1 2 The client applicat ion for t he Service1 W eb service in the TableProcessor folder dem onst rat ing how it handles a request t o show a particular colum n value from the first colum n of the Cust om ers table in
the Northw ind dat abase
The following listing shows the code behind Form 2 that m anages the behavior of the client application for the Web service in the TableProcessor folder The listing starts with the instantiation of a
Trang 3m odule- level variable, xws1, for the proxy Web service Notice how Visual Basic NET system atically nam es the second- level reference
in t he proxy object The proxy for the first Web service uses
localhost as its second nam e The proxy for the deployed version used localhost1 as its second nam e This proxy variable, which is the third one in the chapter, has localhost2 as it s second nam e I n all three cases, the first nam e for a proxy denotes the client
application’s project— nam ely, XMLWebServiceClients Also, the nam e for the proxy object in each case refers to the asm x file in the Web service, which has the nam e Service1 in all three
the form These event procedures invoke the RowCount and
Colum nValues Web m ethods as well as processing their return
values As you can see, the xws1 proxy variable appears in both
Click event procedures, which is why the listing starts by
instantiating the variable at the m odule level
The Button1_Click event procedure invokes the RowCount Web
m ethod and displays its result in TextBox3 This procedure actually starts by m aking sure TextBox4 and its m atching label are invisible These two controls are for displaying a colum n value and labeling the return value, but a click of the Row Count button (Button1) doesn’t show any colum n values Next t he procedure copies the
Text property values of TextBox1 and TextBox2 to m em ory
variables in the client application These variables store the nam e of the database and the table for the Web service to exam ine After saving the local m em ory variables, the procedure uses them as argum ents while invoking the RowCount Web m ethod The argum ents specify for which table in which database to return a row count The final group of lines in the event procedure m akes the text box and label (TextBox3 and Label3) for the row count value visible on the form The procedure’s final line passes the converted value type of the return value from the RowCount Web m ethod to the Text property of TextBox3
The Click event procedure for Button2 is slight ly m ore sophisticated than the one for Button1 There are three reasons for this First, the
Button2_Click event procedure invokes two Web m ethods instead of one Second, the Click event procedure for Button2 presents a prom pt to gather user feedback Third, the event procedure stores the return value from the Colum nValues Web m ethod as an array
and then uses the reply to the prom pt to pick a value from the array and display it on the form
Trang 4Like the event procedure for Button1, the Button2_Click event procedure starts by m aking a text box and label invisible I n this case, the text box and label are for the RowCount Web m ethod’s return value, which a click to But ton2 doesn’t show Just because
the procedure doesn’t directly show the return value from the
RowCount Web m ethod doesn’t m ean the Web m ethod is unused in the procedure On the contrary, the RowCount Web m ethod’s return value is used early and often throughout the procedure I n fact, the next three lines save argum ents for the Web m ethod, invoke it, and save the return value in a m em ory variable, m yRowCount Next the procedure prom pts the user for which row in the first colum n to show a colum n value The procedure uses an I nputBox function for this with the default value 1
After obtaining a reply to the I nputBox funct ion prom pt, the procedure concludes its data input phase from the user All the data
it needs is in m em ory or available via a Web m ethod call Next the procedure invokes the Colum nValues Web m ethod and saves its result as a string Then the procedure strips off the leading string (
"Values in column 1 are: " ) from the return value and saves the resulting string (str1) This leaves str1 with j ust the colum n values from the table nam ed in TextBox2
Perhaps the m ost interesting aspect of the procedure is the parsing
of str1 to extract individual colum n values that go into cells in the
m yVector array The array is dim ensioned based on the row count from the table nam ed in TextBox2 This value is available via a
m em ory variable (m yRowCount) from the invocation of the RowCount Web m ethod The procedure then opens a loop that iterates through the colum n values in st r1 On each pass through
the loop, the code reads the first colum n value in str1, which is a substring up to but not including the first com m a I t then saves this value in the first em pty cell in the m yVector array and rem oves the value, its trailing com m a, and t he blank space after the com m a from the str1 variable Therefore, successive passes always have a fresh value as the first colum n value in str1 The procedure
concludes by m aking TextBox4 with it s m atching label visible and
by selecting a cell from the m yVector array to show based on the user’s response to the I nputBox function prom pt
’Use cabinc_NthRoot Web Service
Dim xws1 As New XMLWebServiceClients.localhost2.Service1()
Private Sub Form2_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ’Hide RowCount text box and label
TextBox3.Visible = False Label3.Visible = False
Trang 5’Hide ColumnValue text box and label
TextBox4.Visible = False Label4.Visible = False End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click ’Hide ColumnValue text box and label
Label4.Visible = False TextBox4.Visible = False ’Pass database name and table name from text boxes on ’the form to the RowCount Web method
Dim adbname As String = TextBox1.Text Dim atablename As String = TextBox2.Text Dim myRowCount As Integer = _
xws1.RowCount(adbname, atablename) ’Make the RowCount label and text box visible ’before populating the text box with a value ’from the RowCount Web method
Label3.Visible = True TextBox3.Visible = True TextBox3.Text = myRowCount.ToString End Sub
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click ’Hide RowCount text box and label
Label3.Visible = False TextBox3.Visible = False ’Pass database name and table name from text boxes on ’the form to the RowCount Web method
Dim adbname As String = TextBox1.Text Dim atablename As String = TextBox2.Text Dim myRowCount As Integer = _
xws1.RowCount(adbname, atablename) ’Print out the maximum number of rows as part of a prompt
’for a selected row from a user
Dim strInputMsg = _ "What row to max of " & myRowCount.ToString & "?
"
Trang 6Dim intReturnedRow As Integer = _ CInt(InputBox(strInputMsg, "", "1")) ’Pass database name and table name memory values to t
he ’ColumnValues Web method and strip off leading string ’for column values
Dim myColumnValues As String = _ xws1.ColumnValues(adbname, atablename) Dim intToColon = InStr(myColumnValues, ":") Dim str1 = Mid(myColumnValues, intToColon + 2, _ Len(myColumnValues))
’Dimension array and integer variable for loop
Dim myVector(myRowCount - 1) As String Dim intRow As Integer
’Pass string of column values to an array
For intRow = 0 To myRowCount - 1 myVector(intRow) = _
str1.substring(0, InStr(str1, ",") - 1) str1 = Mid(str1, InStr(str1, ",") + 2, Len(str1)) Next
’Make ColumnValue label and text box visible before ’passing array value corresponding to user selection
in ’the text box
Label4.Visible = True TextBox4.Visible = True TextBox4.Text = myVector(intReturnedRow - 1) End Sub
The SQL Server 2 0 0 0 W eb Services Toolkit
The Web Services Toolkit sim plifies the creation of Web services based on SQL Server 2000 database objects and tem plates in I I S virtual directories Microsoft built on an earlier approach for delivering XML functionality from SQL Server with the Web Services Toolkit— nam ely, by extending the capability of the I I S virtual
directory so that it can host a Web service The Web service from
an I I S virtual directory exposes individual database objects and tem plates as Web m ethods
After the creation of a Web service based on an I I S virtual directory, you still use the sam e basic approach dem onstrated in the preceding two sections for developing a client application for your Web service This section starts by revealing how to design an
Trang 7I I S virtual directory to offer a Web service The design of the virtual directory specifies the Web service based on a stored procedure The review of a core client application and a sim ple extension of it equip you with the skills to build your own solut ions for capturing XML fragm ents returned from Web m ethods based on database objects and tem plates
Script ing a SQL Server User for a Virtual Direct ory
Although it isn’t essential to designate a SQL Server user when specifying an I I S virtual directory, it can be useful— especially when the virtual directory hosts a Web service Any Web service
em anating from an I I S virtual directory can have a potentially large num ber of users By using a special SQL Server user, you can set the perm issions for the special SQL Server user and be sure that anyone who connects to t he Web service will have perm ission to perform the tasks enabled through the exposed Web m ethods You can also lim it the ability to perform tasks through the Web service
by lim iting the perm ission for its special SQL Server user
Note
The NET Fram ework contains standard security conventions, including techniques for m anaging the use of encryption that your applications m ay require for protecting a user’s identity,
m anaging data during transm ission, and authenticating data from designated clients See the “Cryptography Overview”
topic in t he Visual Studio NET docum entation for m ore detail
on this topic This topic is a m ajor sect ion within t he
“Security Applications” topic, which you m ight also want to review
The following T- SQL script is m eant for you to run from Query Analyzer for the SQL Server 2000 instance that you use for the rem aining sam ples throughout this chapter The script is available
am ong the book’s sam ple files as ScriptsFor13.sql The sam ple is built around the notion that t his is t he local SQL Server 2000 instance I f this isn’t the case, you’ll need to adjust the sam ple accordingly The script drops any prior SQL Server login for the connected SQL Server instance and a prior user for the Northwind database nam ed vbdotnet1 I f you incur error m essages because the user doesn’t exist, sim ply ignore them because the purpose of the script is to rem ove a login or user only if it does exist After
m aking sure vbdotnet1 is free for assignm ent, the script adds a new user nam ed vbdotnet1 and grants access to the Northwind
database Recall that the Northwind database is one of the SQL Server sam ple databases The database’s public role grants any user access to m ost database objects that ship as part of t he database For exam ple, vbdotnet1 has autom at ic perm ission to run
Trang 8all stored procedures, such as t he Ten Most Expensive Products
stored procedure, which is one of the built- in user- defined stored procedures for the database
Notice that this script uses “/ * ” to m ark the beginning of the code com m ent that stretches over m ultiple lines, and “* / ” to end it
/*Run from member of sysadmin fixed server role
Ignore errors if user does not already exist
*/
USE Northwind EXEC sp_revokedbaccess ’vbdotnet1’
EXEC sp_droplogin @loginame = ’vbdotnet1’
GO Add vbdotnet1 user with known permissions
EXEC sp_addlogin @loginame = ’vbdotnet1’, @passwd = ’passvbdotnet1’, @defdb = ’Northwind’
EXEC sp_grantdbaccess ’vbdotnet1’
GO
Building a W eb Service in an I I S Virtual Directory
Now that we have a SQL Server user, we can proceed through the steps for creating an I I S virtual directory This directory will contain the contract for a Web service You can create a new I I S virtual directory by choosing Program s from the Windows Start m enu, then SQLXML 3.0, and then Configure I I S Support This opens the I I S Virtual Directory Managem ent utility for SQLXML 3.0 I n order to open the utility, you m ust, of course, have already installed Web Release 3 ( SQLXML 3.0) See the “Web Services from the Web Services Toolkit” section for a URL to download Web Release 3 along with the Web Services Toolkit
With the I I S Virtual Directory Managem ent ut ility open, expand the folder for the local Web server Then right- click Default Web Site within t he local Web server, choose New, and then choose Virtual Directory This opens a m ulti- tabbed dialog box that lets you set the properties of a new virtual directory You can use the New Virtual Directory Properties dialog box to create the virtual directory by following these instructions:
1 On the General tab, nam e the directory Chapter13, and give
the virtual directory the path c: \ inetpub\ wwwroot\ Chapter13 You can type the path or use the Browse button to navigate to the folder Although the utility allows you to create a new
Trang 9folder from within the utility, som e m ay find it easier to create the folder before opening the ut ility
2 On the Security tab, select the SQL Server radio button Then enter vbdotnet1 in t he User Nam e text box and
passvbdotnet1 in the Password text box Confirm t he
password before m oving off the tab
3 On the Data Source tab, accept the default settings of the local SQL Server and default database for the current login
4 On the Sett ings tab, leave Allow Tem plate Queries selected and also select Allow POST
5 On the Virtual Nam es tab, you set up the virtual directory through which you can deliver Web services With < New virtual nam e> highlighted in the Defined Virtual Nam es list box, enter SoapFor13 in the Nam e text box Then select soap from the Type list Next, in the Path text box, enter the path for your virtual directory, nam ely
c: \ inetput\ wwwroot\ Chapter13 Finally click Save to enable
the configuration of your Web service associated with the
SoapFor13 virtual nam e
Once you’ve clicked Save, the Configure button is enabled
6 While still in the Virtual Nam es tab, click Configure ( see Figure 13-13) to select SQL Server stored procedures and user-
defined functions to expose as Web m ethods You can also expose tem plates through the Web service Although your database objects and tem plates m ust exist before you can expose them , the Web Services Toolkit doesn’t expose them until you explicit ly configure it to m ake the Web service offer Web m ethods based on a stored procedure, user-defined function, or tem plat e
Figure 1 3 - 1 3 The Virt ual Nam e tab for t he New Virt ual Direct ory Propert ies dialog box for t he SoapFor1 3 W eb service in the
Chapter1 3 virt ual direct ory
Trang 107 After you click Configure, the Soap Virtual Nam e Configuration dialog box opens so that you can specify item s to expose as Web m ethods I f you are going to expose a stored procedure
or a user- defined function, designate SP as the Type;
otherwise, select Tem plate to designate a tem plate as the source for a Web m ethod You can designate an item by using the Browse button ( …) to browse sources for a Web m ethod in the Web service hosted by the virtual directory By clicking the Browse button with SP selected as the Type, I was able to pick Ten Most Expensive Products as the source for a Web
m ethod I accepted the default selection to return the result set from the stored procedure as XML objects With this selection, you can retrieve m ultiple results ( or just one) from
a stored procedure Figure 13-14 shows the dialog box just before I click Save to expose the stored procedure as a Web
m ethod
8 Click OK to save the configuration of the Web Service and close the Soap Virtual Nam e Configuration dialog box
Trang 11Figure 1 3 - 1 4 The Soap Virtual Nam e Configurat ion dialog box displaying t he set t ings for t he Ten_ Most_ Expensive_ Product s W eb
m et hod just before saving t hem
You can im prove your debugging process by disabling various caching options
9 Click the Advanced tab in the New Virtual Directory Properties dialog box Consider selecting all three options for disabling different types of caching These selections im prove the operation of your Web service, but the caching can be distracting in som e debugging and code updating operations
10 Click OK to save the settings you’ve chosen and close the New Virtual Directory Properties dialog box
Now you’re ready to test the Web service After you finish debugging and refining your Web service, restore the caching features because they speed up the operation of a Web
service in norm al operation
Trang 12Note
The book’s sam ple files include the Chapter13 virtual directory folder for reference’s sake I n order to create the virtual directory so that you can m anage it and use it, you’ll need to follow the instructions for its creation in this sect ion
When a subsequent section edits t he SoapFor13 Web service hosted by the Chapter13 virtual directory, you’ll need to follow the steps for that as well
Building a Client Application t o Show an XML Fragm ent
Web services created with the SQL Server 2000 Web Services Toolkit don’t have a built- in test interface I n addition, you connect them to a client application slightly differently than Web services, which you build directly with Visual Studio NET Nevertheless, the broad outline of the testing process with a client applicat ion is sim ilar I n both cases, a wsdl file form ally defines the Web service and specifies any input and outputs associated with individual Web
m ethods I n addition, you m ust create a Web reference in the client application that points at the Web service
Create a new form nam ed Form 3 in the XMLWebServiceClients
project Add two label controls Size the form and controls about as they appear in Figure 13- 15 later in t his section ( The form is also available in the XMLWebServiceClients project am ong the book’s sam ple files.) The arrangem ent and sizing of the form and its controls are intended to accom m odate the display of the entire XML fragm ent returned by the Ten_Most_Expensive_Products Web
m ethod Make Form 3 the startup object for the XMLWebServiceClients project so that t he form opens when you start t he project
I n the m odule behind Form 3, add a Web reference to the
SoapFor13 Web service by choosing Add Web Reference from the
Project m enu I n the address box of the Add Web Reference dialog box, type the following URL with its trailing param eter:
http: / / localhost/ Chapter13/ SoapFor13?wsdl
Then press Enter This populates the left pane of the Add Web Reference dialog box with a representation of the wsdl file for the
SoapFor13 Web service The right pane includes a single link with
the text View Contract Click the Add Reference button to create a Web reference for use with a proxy variable I f you have been creating the sam ples throughout the chapter, the nam e for this Web reference in the Web References folder of Solution Explorer is
localhost3 No m atter what its nam e, t he reference should include
an item nam ed SoapFor13.wsdl This wsdl file contains the form al description for the Web service Any proxy variable based on this Web reference will enable you to run t he
Trang 13Ten_Most_Expensive_Products Web m ethod and display the result
set returned as an XML fragm ent The result set from the stored procedure is available as an XML docum ent fragm ent because the exam ple selected this output form at in Figure 13- 14
The next listing shows the code behind the form in Figure 13- 15 As you can see, it consists of a single form Load event procedure When the form opens, t he procedure connects to t he SoapFor13 Web service and invokes the Ten_Most_Expensive_Products Web
m ethod I t collects t he XML fragm ent returned by the m ethod in an array of Response objects The Response object is the m ost basic kind of object in Visual Studio NET; this type of object can
accom m odate any other kind of object or type Since the Web service can present either an XML docum ent or a SqlMessage
object, the application needs Response objects to accom m odate
either outcom e The SqlMessage object can return SQL Server error
m essages and warnings to an applicat ion
Using an array of objects accom m odates the possibility of m ult iple result sets from a single stored procedure or tem plate file Although this sam ple has a single result set, t he sam ple’s design illustrates the For loop syntax for iterating through the m em bers of a
Response object array A Select…Case statem ent sends the Response object to the appropriate code for processing Because
this is a very sim ple application, the code just processes an object containing an XML fragm ent The processing consists of a pair of statem ents that copy the XML fragm ent in the Response object to the Text property of the second label on Form 3 Whenever you choose to output the result set or sets from a Web m ethod as XML objects, you’ll have to process the output in this style— that is, with
a Select…Case statem ent nested within a For loop that iterates through the objects returned from the Web m ethod
Private Sub Form3_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ’Declare Web service xws1 as type named soap in ’localhost4 Web reference
Dim xws1 As New XMLWebServiceClients.localhost3.SoapFor13()
’Declare object for return from Web service method Dim response As New Object()
Dim result As System.Xml.XmlElement ’Declare integer for iterating through multiple ’result sets that the Web service method can return Dim int1 As Integer
’Save return from Web service method as an object response = xws1.Ten_Most_Expensive_Products
Trang 14’Iterate through result sets
For int1 = 0 To UBound(response) Select Case response(int1).GetType().ToString() Case "System.Xml.XmlElement"
’Pass int1 result set to result and displ
ay ’in list box and Output window
result = response(int1) Label2.Text = result.OuterXml Case Else
’Handles end of result sets and other ’special returns
End Select Next
End Sub Figure 13- 15 shows Form 3 open from the XMLWebServiceClient project The form contains two labels The top label has a fixed Textproperty assignm ent I t always shows “XML fragm ent: ” The
contents of the bottom text box can change if the ten m ost expensive products change because of a price revision, the addition
of new products, or the dropping of existing products The product nam e and unit price values are delim ited by opening and closing tags Although this form at m ay be convenient for com puters to process and is readable by hum ans, it is verbose That’s because every value has a pair of tags, and there are additional tags to m ark the beginning and ending of each row (< row> and < / row>) as well
as the beginning and ending of the XML fragm ent (< SQLXML> and
< / SQLXML >)
Figure 1 3 - 1 5 Form 3 from t he XMLW ebServiceClient s project show ing t he out put from the Ten_ Most _ Expensive_ Products W eb m et hod in t he
SoapFor1 3 W eb service
Trang 15Populat ing a ListBox Cont rol w ith an XML Service
Figure 13- 15 is interesting, but it’s unlikely that you’ll want to show
m any clients of your Web services an XML fragm ent I t’s m ore likely that they will want t o view the tag values in a control t han a
verbose XML fragm ent including tags I n the case of the display in Figure 13- 15, they m ight prefer to see a ListBox control with 10 item s, showing product nam e and price in descending order The sam ple in t his section extends the preceding one to achieve this goal
You can im plem ent this sam ple by creating a new form , Form 4, in the XMLWebServiceClients project Add a list box control and the code listing in this section Make Form 4 the start up object for the project I f you have the Web reference defined as in the preceding sam ple, pressing F5 will cause the form to open and show the ten
m ost expensive products in a list box (See Figure 13- 16.) By adding custom code, such as we will show later in t his chapter, you can enable interactivity with data returned by a Web service from within a Windows form control
Once you understand that your applications can capture the result set from a stored procedure as a Response object containing an XML fragm ent, it’s easy to craft a solution like the one in Figure 13-
16 All your application has to do is parse the XML fragm ent to extract the tag values, com bine the product nam e and price in a form suitable for the List Box control, and then add the com bined item to the control