Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 30 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
30
Dung lượng
682,05 KB
Nội dung
Form 2 reappears after the user replies to the prompt, the form
shows the first two text boxes with their prior values as well as the
fourth text box for displaying a column value. The specific value in
the bottom text box is the one matching row specified by the user’s
reply to the prompt.
Figu re 1 3 - 1 1 . The client applicat ion form for the Service1 W eb service in
the Tab leProcessor folde r.
The processing of the return values from the ColumnValues Web
method illustrates a typical scenario. A developer engineers an
application so that it can accommodate any of several scenarios. For
example, a client application makes a selection from the total set of
column values to show the column value for just one row instead of
the whole set of column values as in Figure 13-10. Figure 13-12
tracks the process from designating database and table names to
capturing the reply to the I nputBox prompt to showing the specific
column value that a user wants to view. I n the top window, the user
designates that they want results from the Custom ers table in the
Northwind database before clicking the button labeled Get Column
Value. The m iddle window shows the user indicated that the
application should show the column value for the fifth row. By the
way, the prompt adjusts automatically to show the maximum
number of rows. The application does this by running the RowCount
Web method when processing a request to show a specific row
value from the first column. The bottom window in the figure
reveals BERGS as the column value for the fifth row in the first
column. You can easily confirm this outcome for yourself by
examining the output in Figure 13-10, which shows all the column
values for the first column in the Custom ers table from the
Northwind database.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figu re 1 3 - 1 2 . The client applicat ion for t he Se rvice1 W eb service in the
TablePr ocessor folder dem on stra t ing h ow it handles a request t o show a
par t icular colum n va lu e from the first colum n of the Cu stom ers t able in
the Northw ind dat aba se.
The following listing shows the code behind Form 2 that manages
the behavior of the client application for the Web service in the
TableProcessor folder. The listing starts with the instantiation of a
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
module-level variable, x ws1, for the proxy Web service. Notice how
Visual Basic.NET systematically names the second-level reference
in the proxy object. The proxy for the first Web service uses
localhost as its second name. The proxy for the deployed version
used localhost1 as its second name. This proxy variable, which is
the third one in the chapter, has localhost2 as its second name. In
all three cases, the first name for a proxy denotes the client
application’s project— namely, XMLWebServiceClients. Also, the
name for the proxy object in each case refers to the .asmx file in
the Web service, which has the name Service1 in all three
instances.
The body of the listing includes three event procedures. One is a
form Load event procedure. This event procedure merely readies
the initial look of the form. In particular, it makes the third and
fourth text boxes, along with their matching labels, invisible. The
application also includes a Click event procedure for each button on
the form. These event procedures invoke the RowCount and
Colum nValues Web methods 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 module level.
The But ton1_Click event procedure invokes the RowCount Web
method and displays its result in TextBox3. This procedure actually
starts by m aking sure Text Box4 and its matching label are invisible.
These two controls are for displaying a column value and labeling
the return value, but a click of the Row Count button (Butt on1)
doesn’t show any column values. Next the procedure copies the
Text property values of TextBox1 and TextBox2 to memory
variables in the client application. These variables store the name of
the database and the table for the Web service to examine. After
saving the local m emory variables, the procedure uses them as
arguments while invoking the RowCount Web method. The
arguments specify for which table in which database to return a row
count. The final group of lines in the event procedure makes 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 method to
the Text property of TextBox3.
The Click event procedure for Butt on2 is slightly more sophisticated
than the one for Button1. There are three reasons for this. First, the
Button2_Click event procedure invokes two Web methods instead of
one. Second, the Click event procedure for Button2 presents a
prompt to gather user feedback. Third, the event procedure stores
the return value from the Colum nValues Web method as an array
and then uses the reply to the prompt to pick a value from the
array and display it on the form.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Like the event procedure for Butt on1, the Butt on2_Click event
procedure starts by making a text box and label invisible. I n this
case, the text box and label are for the RowCount Web method’s
return value, which a click to Button2 doesn’t show. Just because
the procedure doesn’t directly show the return value from the
RowCount Web method doesn’t mean the Web method is unused in
the procedure. On the contrary, the RowCount Web method’s return
value is used early and often throughout the procedure. In fact, the
next three lines save arguments for the Web method, invoke it, and
save the return value in a memory variable, m yRowCount. Next the
procedure prom pts the user for which row in the first column to
show a column value. The procedure uses an I nput Box function for
this with the default value 1.
After obtaining a reply to the I nput Box function prompt, the
procedure concludes its data input phase from the user. All the data
it needs is in memory or available via a Web method call. Next the
procedure invokes the Colum nValues Web method 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 (st r1). This leaves str1 with just the column
values from the table named in TextBox2.
Perhaps the most interesting aspect of the procedure is the parsing
of str1 to extract individual column values that go into cells in the
m yVect or array. The array is dimensioned based on the row count
from the table named in Text Box2. This value is available via a
memory variable (m yRowCount) from the invocation of the
RowCount Web method. The procedure then opens a loop that
iterates through the column values in str1. On each pass through
the loop, the code reads the first column value in str1, which is a
substring up to but not including the first comm a. It then saves this
value in the first em pty cell in the myVector array and removes the
value, its trailing comma, and the blank space after the comma
from the str1 variable. Therefore, successive passes always have a
fresh value as the first column value in str1. The procedure
concludes by m aking TextBox4 with its matching label visible and
by selecting a cell from the m yVect or array to show based on the
user’s response to the I nputBox function prompt.
’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
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
’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 pr
ompt
’for a selected row from a user.
Dim strInputMsg = _
"What row to max. of " & myRowCount.ToString & "?
"
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Dim 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 Se rver 2 0 0 0 W eb Ser vices Toolk it
The Web Services Toolkit simplifies the creation of Web services
based on SQLServer2000 database objects and templates in IIS
virtual directories. Microsoft built on an earlier approach for
delivering XML functionality from SQLServerwith the Web Services
Toolkit— namely, by extending the capability of the IIS virtual
directory so that it can host a Web service. The Web service from
an IIS virtual directory exposes individual database objects and
templates as Web m ethods.
After the creation of a Web service based on an IIS virtual
directory, you still use the same basic approach demonstrated in
the preceding two sections for developing a client application for
your Web service. This section starts by revealing how to design an
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
IIS 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 simple extension of it
equip you with the skills to build your own solutions for capturing
XML fragm ents returned from Web methods based on database
objects and templates.
Scripting a SQL Se r ver User for a Virt ual Direct ory
Although it isn’t essential to designate a SQLServer user when
specifying an II S virtual directory, it can be useful— especially when
the virtual directory hosts a Web service. Any Web service
emanating from an IIS virtual directory can have a potentially large
number of users. By using a special SQLServer user, you can set
the permissions for the special SQLServer user and be sure that
anyone who connects to the Web service will have permission to
perform the tasks enabled through the exposed Web methods. You
can also limit the ability to perform tasks through the Web service
by lim iting the permission for its special SQLServer user.
N ote
The .NET Framework contains standard security conventions,
including techniques for managing the use of encryption that
your applications m ay require for protecting a user’s identity,
managing data during transm ission, and authenticating data
from designated clients. See the “Cryptography Overview”
topic in the Visual Studio .NET documentation for more detail
on this topic. This topic is a major section within the
“Security Applications” topic, which you might also want to
review.
The following T-SQL script is meant for you to run from Query
Analyzer for the SQLServer2000 instance that you use for the
remaining samples throughout this chapter. The script is available
among the book’s sample files as ScriptsFor13.sql. The sample is
built around the notion that this is the local SQLServer2000
instance. If this isn’t the case, you’ll need to adjust the sample
accordingly. The script drops any prior SQLServer login for the
connected SQLServer instance and a prior user for the Northwind
database named vbdotnet1. If you incur error messages because
the user doesn’t exist, simply ignore them because the purpose of
the script is to remove a login or user only if it does exist. After
making sure vbdotnet1 is free for assignment, the script adds a new
user named vbdotnet1 and grants access to the Northwind
database. Recall that the Northwind database is one of the SQL
Server sample databases. The database’s public role grants any
user access to m ost database objects that ship as part of the
database. For exam ple, vbdotnet1 has automatic permission to run
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
all stored procedures, such as the 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 mark the beginning of the code
com m ent that stretches over multiple 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 Virt ua l D irectory
Now that we have a SQLServer user, we can proceed through the
steps for creating an IIS virtual directory. This directory will contain
the contract for a Web service. You can create a new IIS virtual
directory by choosing Programs from the Windows Start menu, then
SQLXML 3.0, and then Configure IIS Support. This opens the IIS
Virtual Directory Management utility for SQLXML 3.0. In order to
open the utility, you must, 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 IIS Virtual Directory Management utility open, expand the
folder for the local Web server. Then right-click Default Web Site
within the local Web server, choose New, and then choose Virtual
Directory. This opens a multi-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, name 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
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
folder from within the utility, som e may find it easier to create
the folder before opening the utility.
2. On the Security tab, select the SQLServer radio button. Then
enter vbdotnet1 in the User Name text box and
passvbdotnet1 in the Password text box. Confirm the
password before moving off the tab.
3. On the Data Source tab, accept the default settings of the
local SQLServer and default database for the current login.
4. On the Settings tab, leave Allow Template Queries selected
and also select Allow POST.
5. On the Virtual Names tab, you set up the virtual directory
through which you can deliver Web services. With < New
virtual name> highlighted in the Defined Virtual Names list
box, enter SoapFor13 in the Name text box. Then select soap
from the Type list. Next, in the Path text box, enter the path
for your virtual directory, namely
c: \ inetput\ wwwroot\ Chapter13. Finally click Save to enable
the configuration of your Web service associated with the
SoapFor13 virtual name.
Once you’ve clicked Save, the Configure button is enabled.
6. While still in the Virtual Names tab, click Configure (see Figure
13-13) to select SQLServer stored procedures and user-
defined functions to expose as Web methods. You can also
expose templates through the Web service. Although your
database objects and templates m ust exist before you can
expose them, the Web Services Toolkit doesn’t expose them
until you explicitly configure it to make the Web service offer
Web methods based on a stored procedure, user-defined
function, or template.
Figu re 1 3 - 1 3 . The V irt ual Nam e t ab for t he New Virtual Dire ctory
Proper t ie s dialog box for the SoapFor 1 3 W eb service in the
Chapt er1 3 virt ual dir ect ory.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
7. After you click Configure, the Soap Virtual Name Configuration
dialog box opens so that you can specify items to expose as
Web methods. If you are going to expose a stored procedure
or a user-defined function, designate SP as the Type;
otherwise, select Template to designate a template as the
source for a Web method. 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
method. 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
method.
8. Click OK to save the configuration of the Web Service and
close the Soap Virtual Name Configuration dialog box.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
[...]... purchase PDF Split-Merge on www.verypdf.com to remove this watermark Appe ndix About t he Aut hor Rick Dobson, Ph.D., is an aut hor and t r ainer specializing in MicrosoftSQL Server, Micr osoft Access, and Web t echnologies He is a big fan of program m at ic solut ions, part icular ly t hose t hat involv e Visual Basic NET, ADO.NET, ASP.NET, XML Web ser vices, and T- SQL t echnologies he feat ures prom... you’ll discov er t hat he also program s in VBA, ADO, Jet SQL, and SQL- DMO This is Rick ’s four t h book in four y ear s Bot h t his book and a form er one t it led Pr ofessional SQL Serv er Developm ent wit h Access 2000 ( Wrox Pr ess I nc., 2000) focus heavily on t he developm ent of SQLServer solut ions While his ot her t wo books are on Microsoft Access, t hey dem onst rat e his com m it m ent... through column values in XML string ’within Web service method output Do While InStr(str1, "") > 0 str2 = MyTagValue("TenMostExpensiveProduc ts", str1) str2 = str2 & ", " & MyTagValue("UnitPric e", str1) ListBox1.Items.Add(str2) str1 = Microsoft. VisualBasic.Right(str1, _ Len(str1) (InStr(str1, "")) - _ Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Len("")... Vir ginia j oint ly run t heir pract ice, CAB, I nc ( ht t p: / / www cabinc.net ) Rick aim s his cont ent pr oduct ion at int er m ediat e and advanced SQLServer , Access, and Web dev eloper s Rick also writ es for leading com put er r esources, such as SQL Server Magazine, MSDN Online Libr ar y, Microsoft TechNet , VisualBasic Pr ogr am m er’s Jour nal, and Micr osoft I nt er act iv e Developer... ’strXML is string with XML to parse ’int1 is start position ’int2 - int1 calculates number of characters Dim TagValue As String = Mid(strXML, _ int1, int2 - int1) Return TagValue End Function Mor e on Popu la t in g Con t r ols w it h W eb Se r vices This sect ion drills deeper int o building Web serv ices wit h t he SQL Server2000 Web Services Toolkit and client applicat ions w it h Visual St udio NET... ent ( < SQLXML> and < / SQLXML > ) Figu r e 1 3 - 1 5 Form 3 from t h e X M LW eb Se rvice Clie n t s p roj e ct sh ow in g t h e ou t pu t from t h e Ten _ M ost _ Exp e n sive _ Produ ct s W eb m e t h od in t h e Soap For 1 3 W e b ser vice Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Popu la t ing a List Box Cont r ol w it h a n X M L Se r vice Figure 1 3- 15 is... necessary with a SQL Server function procedur e Dim das1 As System.Data.DataSet das1 = _ xws1.udfProductsInACategoryAsDataset(CInt(TextBox 1.Text)) ’Populate second list box with product names ’for products in currently selected category in the ’first list box ListBox2.DataSource = das1.Tables(0) ListBox2.DisplayMember = _ das1.Tables(0).Columns(0).ColumnName End Sub Please purchase PDF Split-Merge on... window of Figur e 1 3- 21 The form aut om at ically select s t he first cat egory nam e in t he fir st List Box cont rol, display s t he Cat egor yI D value for t he first cat egory Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark nam e, and displays t he pr oduct s wit hin t he cat egory in t he second list box ( See t he t op form window in Figur e 1 3- 21.) Aft er t he... g a Clie n t Applica t ion t o Show a n XM L Fr a gm e n t Web services creat ed wit h t he SQL Server2000 Web Serv ices Toolkit don’t have a built - in t est int er face I n addit ion, you connect t hem t o a client applicat ion slight ly differ ent ly t han Web serv ices, which y ou build direct ly wit h Visual St udio NET Nev er t heless, t he broad out line of t he t est ing pr ocess wit h a client... purchase PDF Split-Merge on www.verypdf.com to remove this watermark Ten_Most _Expensive_Product s Web m et hod and display t he result set r et urned as an XML fr agm ent The r esult set from t he st ored procedure is available as an XML docum ent fr agm ent because t he exam ple select ed t his out put for m at in Figure 1 3- 14 The next list ing shows t he code behind t he for m in Figur e 1 3- 15 As . = Microsoft. VisualBasic.Right(str1,
_
Len(str1) -
(InStr(str1, "</UnitPrice>")) - _
Please purchase PDF Split-Merge on www.verypdf.com. deeper into building Web services with the SQL
Server 2000 Web Services Toolkit and client applications with Visual
Studio .NET. I n particular, the emphasis