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

Professional VB 2005 - 2006 phần 9 pot

110 122 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 đề Web Services
Trường học University of Information Technology
Chuyên ngành Computer Science
Thể loại bài tập
Năm xuất bản 2005-2006
Thành phố Ho Chi Minh City
Định dạng
Số trang 110
Dung lượng 6,33 MB

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

Nội dung

848 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com... Get operationfor retrievingdata fromEnterprisedatabase Simpo PDF Merge and Split Unregistered Version - ht

Trang 1

That’s pretty much all there is to Web Services from an implementation perspective in NET .NET dealswith all of the plumbing that was discussed in the first part of this chapter (SOAP, WSDL, and so on),which means that all there is to do is add properly decorated methods to the service.

To get the data from your site to the remote site, call a Web Service on the remote Web server from yourintranet Since the SOAP envelope is sent via HTTP, the firewall will allow it through, and ADO.NET onthe IIS server will handle the actual database manipulation The remote firewall will allow database callsonly from the IIS server, and the data will be updated safely because of the security

In real life, the class file GetCustomerswould be local to your intranet server, and the database filewould be an SQL server on a second PC Across the Internet, as shown in the diagram, the Web Servicewould be on an IIS server sitting outside the network firewall The DLL that actually provides the datafunctions would be on an application server inside the firewall, and the database would again be on aseparate machine

For this application, though, you will create a Web Service that will expose the Customers table from thesample Northwind database, across the intranet, that will then later be consumed by a Web application.Just remember that Web Services are not only about exposing simple values, but also about exposing aricher dataset of values such as entire tables from a data store (for example, SQL Server)

Start this example by first creating a new Web Service project in Visual Studio called MyWebService

Using Visual Studio 2005 to Build Web Services

The Visual Studio 2005 IDE shows a marked improvement from the add-ins provided for Visual Studio 6

in the SOAP Toolkit For instance, Web Services are shown as references on a project, rather than in aseparate dialog box The discovery process, discussed later, is used to its fullest, providing much moreinformation to the developer In short, it is nearly as easy to consume a Web Service with Visual Basic as

it is to use DLLs

848

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 2

Figure 23-6

7 Updateoperation forpublishingEnterprise data toremote server

Firewall

5 Call routed toISP via HTTPThe Internet

4 Web Service makescall to ISP for update

Local EnterpriseServer

3 DLL providesWeb servicewith data

2 SP ReturnsRecordset

0 Get operationfor retrievingdata fromEnterprisedatabase

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 3

Produce a Typed DataSet

For simplicity, you’ll use Visual Studio to first create a typed DataSet, which will be returned from theWebMethod that you will later produce This IDE enables you to quickly and easily create the neededdata access without having to dig through lots of ADO.NET code

To do this, right-click the MyWebServiceproject in the Solution Explorer and select Add ➪ Add New Item.One of the options is a new DataSet Change the name of this file to MyDataComponent.xsd This creates atyped DataSeton the fly, and it’s already strongly typed In addition to this, Visual Studio will request toplace this file in the App_Code directory of your solution Confirm this request, because having it in theApp_Code directory allows for programmatic access to the DataSet (shown in Figure 23-7)

Trang 4

The first step in the TableAdapter Configuration Wizard is to establish a data connection If there is not aconnection already in place, create a new connection by clicking on the New Connection button Usingthis dialog, make a new connection to the sample Northwind database in Microsoft’s SQL Server.Once the connection is in place, you will be able to see that the wizard will use the System.Data.SqlClientprovider Click the Next button, which calls up a dialog that enables you to pick the com-mand type that you are going to want to work with Typically, the options are working with either directSQL commands, existing stored procedures, or stored procedures that you can create directly in the wiz-ard For this example though, choose the first option: Use SQL Statements.

The next page in the wizard asks for the query that you want to use to load the table data Input the following:

SELECT dbo.Customers.* FROM dbo.Customers

Clicking the Next button s results in a page that will allow you to pick the methods that the wizard willcreate These are the methods used in your Web Service to load data into datasets for transmission Inthis case, just accept the default and click the Next button again

Now you will be at the last page of the wizard This final page just shows the results of all the actionstaken (shown in Figure 23-9)

Figure 23-9

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 5

Once you click the Finish button, notice that the design surface of the MyDataComponent.xsdfilechanges to reflect the data that comes from the Customers table of the Northwind database Theseresults are shown in Figure 23-10.

Figure 23-10

The typed dataset is now in place and ready to use by the Web Service Looking at the results on thedesign surface of the xsd file, you can see that indeed the typed Customersdataset is in place, but inaddition to this there is also a CustomersTableAdapterobject with Fill()and GetData()methods

in place

Build the Service

Right-click Service.asmxfrom within Solution Explorer in Visual Studio, and select View Code.Rename the HelloWorldfunction to GetCustomers From here, simply retrieve data from the

CustomersTableAdapterthat was created when you created the xsd file earlier

<%@ WebService Language=”VB” Class=”Service” %>

Trang 6

Dim ds As New MyDataComponent.CustomersDataTable()da.Fill(ds)

Return dsEnd FunctionEnd Class

Right-click the Service.asmxfile in Solution Explorer and select View in Browser If there are no errors, asimple screen listing GetCustomersas the sole method of the service appears Click the Service Descriptionline, and you’ll get a screen like that shown earlier in the “Web Services Description Language” section

Consuming the Service

For this consuming application, provide a Web application called WSCustomersby creating a newASP.NET Web site project with that name The first step is to create a Web reference to the remote XMLWeb Service

Adding a Web Reference

The only bit of magic here is the adding of a Web reference to the project with the Visual Studio IDE Asdiscussed later, you are really creating a proxy based upon the WSDL file of the service and referencingthe proxy in the project, but the IDE makes this all very easy

To create the proxy that is needed by the consuming application, right-click the WSCustomersproject inSolution Explorer and select Add Web Reference from the list of options In this form, enter in the WSDLfile of the Web Service that you are wishing to make a reference to If the Web Service is a NET WebService (with an asmx file extension), simply input the URL of the asmx file and nothing more becausethe wizard will know to put ?wsdlat the end of the input If you are referencing a Java Web Service, thenplace the URL for the wsdl file in this wizard Enter the URL of your service in the address bar (Thiswould be at the ISP in your real-life scenario, but if you’ve been following along it’ll be http://localhost/mywebservice/service.asmx If you are using IIS, click on the Web Services in this solution link).The dialog box should appear as displayed in Figure 23-11

Figure 23-11

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 7

The service description page you’ve just seen when you built your service appears in the left pane ofthe wizard, with NET specific information in the right Click the Add Reference button at the bottom

of the window to add this to the project The service appears in a new folder in Solution Explorer, WebReferences, as illustrated in Figure 23-12

Figure 23-12

Building the Consumer

The COM architecture continually promised “one line of code” to generate great results Web Serviceslive up to the promise, minus the declarations Now the only thing left to do is call the referenced WebService and pass the generated DataSet Compared to the scores of lines of XML needed to pass the

DataSetin the existing Microsoft technologies, this is a breeze

The first step of your consuming an aspx page is simply to make a reference to the proxy that VisualStudio created and then call the GetCustomers WebMethodthrough this instantiated object The resultspulled from the GetCustomersmethod will then be displayed in a GridViewcontrol, which should beplaced on the Web form

There are a couple of ways to achieve this The first method is to use an ObjectDataSourcecontrol,which does the work of invoking the GetCustomers WebMethodand then displaying the results in the

GridViewcontrol (The second method, discussed a bit later, is to manually write the required code.)

To work through this example, drop a GridViewand an ObjectDataSourceserver control onto thedesign surface of the Web Form Open the smart tag of the ObjectDataSource control and select theoption to Configure Data Source You will then be presented with the Configure Data Source Wizard

In the first page of this wizard, uncheck the Show Only Data Components check box and select

localhost.Servicefrom the drop-down list Click the Next button to choose the Selectmethod that for ObjectDataSourcecontrol to use (shown in Figure 23-13)

From the drop-down list on this page of the wizard, select GetData(), returns CustomerDataTable.Once this is selected, click the Finish button to progress to the next step of binding the GridViewcontrol tothe returned dataset from this ObjectDataSourcecontrol

854

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 8

Figure 23-13

Now, focus on the GridViewcontrol In configuring this control, open the control’s smart tag and select

ObjectDataSource1as the data source control for this control from the drop-down list Notice thatonce you do this, the GridViewcontrol expands to include all the appropriate columns from theCustomers table of the Northwind database

Then in the same smart tag, enable paging and sorting by selecting the appropriate check boxes The endcode that is generated by Visual Studio is shown here:

<asp:BoundField HeaderText=”ContactName” DataField=”ContactName”

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 9

Once it is complete, just build and run the page That’s it, there is a table in the Web form with all the

data from a remote SQL server that can be paged and sorted — and you didn’t have to write any code to

achieve this functionality! The end page results are shown in Figure 23-14

Now look at doing the same thing, but instead spend a little time writing some code This is a goodmove because it offers more control over the situation (if desired), and it teaches you more about what isgoing on

Start by creating a page that only includes a GridViewcontrol From here, you get at the data that comesfrom the Web Service in the Page_Loadevent This is illustrated in the following example:

Trang 10

GetCustomers() WebMethodcall Finally, close everything by calling the DataBind()method of the

GridViewcontrol By compiling and running the XML Web Service, you are able to pull out of thedatabase the entire Customers table from the Northwind database A returned dataset contains a wealth

of information, including:

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 11

❑ An XSD definition of the XML that is contained in the DataSet

❑ All the customer information from the Customers table of the Northwind database

Then on the consumption side, consumers of this XML Web Service can easily use the XSD definitionand the XML that is contained within the DataSetwithin their own applications If consumers are thenconsuming this DataSetinto NET applications, they can easily bind this data to a DataGridand use itwithin their applications with minimal lines of code

V isual Basic and System.Web.Ser vices

The SOAP Toolkit provided a number of wizards to navigate most of the obstacle course required to set

up a Web Service, but the NET Framework class library provides the abstract classes The System.Web.Servicesnamespace provides four classes and three other namespaces that allow programmaticexposure of methods to the Web

<%@ WebService Language=”VB” Class=”Util” %>

858

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 12

End If

HitCounter = Application(“HitCounter”)End Function

End Class

WebServiceis an optional base class, used only if access to ASP.NET objects is desired The

WebMethodAttributeclass, however, is a necessity if the class needs to be available over the Web.The WebServiceAttributeclass is similar to the WebMethodAttributeclass in that it enables theaddition of the description string to an entire class, rather than method by method We recommendadding it before the previous class declaration:

<WebService(Description=”Common Server Variables”)> _Public Class ServerVariables

Inherits System.Web.Services.WebService

Instead of using WSDL in the contract to describe these services, the System.Web.Servicesnamespaceprovides programmatic access to these properties IIS Service Discovery will use these descriptionswhen queried This way, we have removed the necessity to struggle with myriad protocols surroundingService Contract Language and SOAP

System.Web.Services.Description Namespace

The System.Web.Services.Descriptionnamespace provides a host of classes that provide totalmanagement of the WSDL Descriptions for your Web Service This object manages every element in theWSDL schema as a class property

Take this example In the preceding discussion on the benefits of WSDL description, we mentioned the benefits of being able to query a Web Service about its methods and parameters The System.Web.Services.Descriptionnamespace provides methods for the discovery of methods and parameters, gathering the information from the service contract and providing it to the object model inVisual Basic code

If working on the HTTP GET protocol (as opposed to SOAP, for instance), simply pass in the required

sEmailparameter through the use of a querystring There are details of this in the Web Service’sWSDL description In the successive <wsdl:message>sections, you find all parameter info for all threeprotocols, including HTTP GET

Trang 13

It is important to note that HTTP GET is disabled by default because it is deemed a security risk If youwish to enable HTTP GET for your XML Web Services, then configure it for this in the web.configfile

of your Web Service solution This is illustrated here:

Imports System.Web.Services.Discovery

ReadOnly Property DiscoveryDocument(strURL As String) As DiscoveryDocument

GetDiscoveryDocument = DiscoveryClientProtocol.Discover(strURL)End Get

End Property

Like the System.Web.Services.Descriptionnamespace, the System.Web.Services.Discovery

namespace provides many tools to build a disco document on the fly

System.Web.Services.Protocols Namespace

All of the wire service problems solved with HTTP and SOAP are handled here in the System.Web.Services.Protocolsnamespace When handling references to classes also referenced in other WebServices namespaces, the System.Web.Services.Protocolsnamespace proves to be a handy tool.The objects referenced by the System.Web.Services.Protocolsnamespace include (among others):

Trang 14

❑ URIs and URLs

<%@ WebService Language=”VB” Class=”Util” %>

Imports System.WebImports System.Web.ServicesImports System.Web.Services.Protocols

<WebService(Namespace:=”http://localhost/util”)> _

<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _Public Class Util

Inherits System.Web.Services.WebService

<SoapDocumentMethod(Action=”http://MySoapMethod.org/Sample”, _RequestNamespace=”http://MyNameSpace.org/Request”, _

RequestElementName=”GetUserNameRequest”, _ResponseNamespace=”http://MyNameSpace.org/Response”, _ResponseElementName=”GetUserNameResponse”) _

WebMethod(Description=”Obtains the User Name”)> _Public Function GetUserName()

End FunctionEnd Class

Architecting with Web Ser vicesWeb Services impart two remarkable benefits to users — one more obvious, another less so First, they willreplace common binary RPC formats, such as DCOM, CORBA, and RMI Since these use a proprietarycommunication protocol, they are significantly less architecturally flexible than Web Services With appli-ances utilizing more and more of the Internet, platform-neutrality will be a great advantage Less obvi-ously but more importantly, Web Services will be used to transfer structured business communications in

a secure manner, potentially ending the hold that Sterling has on the Electronic Data Interchange (EDI)market HTTPS with 128-bit SSL can provide the security necessary for intracompany information trans-fer In addition to this, Microsoft has recently (as of this writing) released Web Services Enhancements 2.0(WSE), which allows you to easily use WS-Security and other advanced protocols to apply credentials,encryption, and digital signing to your SOAP messages in an easy and straightforward manner

Why Web Services?

So, why Web Services? First, they are remarkably easy to deploy with Visual Basic The key to remotingwith Web Services is the SDL contract — written in the dense WSDL protocol you saw earlier

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 15

IIS 5.0 and 6.0 does that in conjunction with the NET Framework, analyzing the VB code and cally generating the WSDL code for the contract.

dynami-Also, Web Services are inherently cross-platform, even if created with Microsoft products Yes, you’veheard this before, but so far this seems to be true Since the standard XML schemas are centrally man-aged, and IBM mostly built the WSDL specification, Microsoft seems to have toed the line on this one.Finally, they best represent where the Internet is going — toward an architecturally neutral collection ofappliances, rather than millions of PCs surfing the World Wide Web Encapsulating code so that you cansimply and easily allow cellphones to use your logic is a major boon to developers, even if they don’tknow it yet

How This All Fits Together

It is important to note that Web Services are not a feature of the NET Framework per se In fact, WebServices run fine on Windows NT4 SP6, with the SOAP Toolkit installed You can do most anything youare doing here with VB6 and IIS 4.0

However, the NET Framework encapsulates the Web Services protocol into objects It is now an grated part of the strategy, rather than an add-on If you are currently working in a VB6 environment,take a look at the SOAP Toolkit (downloadable from MSDN at http://msdn.microsoft.com/webservices), and understand that the services you build are available not only to different flavors ofWindows, but also to IBM and Sun platforms

inte-The goal of Web Services is to provide a loosely coupled, ubiquitous, universal information exchangeformat Toward that end, SOAP is not the only mechanism for communicating with Web Services —the HTTP GET and HTTP POST protocols are also supported by NET Response is via HTTP, just likenormal RPCs with SOAP This allows legacy Web applications to make use of Web Services without thebenefit of the NET Framework

State Management for XML Web Services

The Internet is stateless by nature Many of the techniques used for managing state in ASP.NET Web

applications are the same techniques you can use within the XML Web Services built on the NET form Remember that XML Web Services are part of the ASP.NET model and both application types havethe same objects at their disposal

plat-These sessions can also be run in the same process as the XML Web Service application itself — out ofprocess, using the NET StateServer, or by storing all the sessions within SQL Server

To use sessions within XML Web Services built on the NET platform, you actually have to turn on thiscapability within the WebMethodattribute by using the EnableSessionproperty By default, the

EnableSessionproperty is set to False, so to use the HTTPSessionStateobject, you have to setthis property to True,as shown here:

<%@ WebService Language=”VB” Class=”Service” %>

Imports System.Web

862

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 16

Imports System.Web.ServicesImports System.Web.Services.Protocols

<WebService(Namespace:=”http://localhost/util”)> _

<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1> _

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _Public Class Service

Inherits System.Web.Services.WebService

<WebMethod(EnableSession:=True)> _Public Function SessionCounter() As Integer

If Session(“Counter”) Is Nothing ThenSession(“Counter”) = 1

ElseSession(“Counter”) = CInt(Session(“Counter”)) + 1End If

Return CInt(Session(“Counter”))End Function

End Class

The EnableSessionproperty goes directly in the parentheses of the WebMethoddeclaration This erty takes a Boolean value and needs to be set to Truein order to work with the Sessionobject

prop-Using DNS As a Model

How does any computer know where to find a Web page? Every machine doesn’t know every location

of every page Rather, there is a big catalog called DNS that is replicated by most Internet service

providers, which translates domain names (like yahoo.com) into IP numbers (like 204.71.200.74).The benefit of the DNS system is that it offers a further level of abstraction between the marketing andthe wires It’s a lot easier to remember yahoo.comthan 204.71.200.74 With Web Services, it becomeseven more important, because there is not only a function name but also the parameters to remember

Three things make up the Web Service Repository: a standard format, a language, and a database You

have already seen the language, WSDL This can be used to lay out the discovery information you need

to publicize your Web Service The format of choice is called DISCO (short for DISCOvery of all things) Finally, and most exciting, is the Web Services answer to DNS — UDDI (Universal Description, Discovery,

and Integration) Let’s talk about DISCO first.

DISCO

One way to enable a repository is to have applications that look for services To implement this, youdrop a DISCO document into the Web Service directory — a file that an application can look for thatenables the discovery of the Web Services present in that directory, or on that machine Alternatively,you can mark each particular service you would like to enable

Web Service discovery is the process of locating and interrogating Web Service descriptions, which is apreliminary step for accessing a Web Service It is through the discovery process that Web Service clientslearn that a Web Service exists, what its capabilities are, and how to properly interact with it

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 17

Dynamic Discovery with IIS

Admittedly not as fun as it sounds, dynamic discovery is Web Services’ answer to the robots.txtfile.Dynamic discovery automatically exposes Web Services beneath a given URL on a Web site By placingthis document at the root of your service’s directories, you give a prospective consumer the opportunity

to obtain information about all services contained in that directory or subdirectories

To enable dynamic discovery for your Web Services, create a <filename>.discodocument at the root

of the Web Services directory

This XML file contains the excluded directories within the hierarchy, so that the dynamic discovery

pro-cess knows where not to go to gather information about Web Services:

Or, if you have an XML page as your default:

<?xml-stylesheet type=”text/xml” alternate=”yes” href=”default.disco” ?>

Dynamic discovery is the way to go with IIS; the discovery process is very well tuned If you work withanother Web server, though, or are a hands-on sort, you can roll your own discovery documents for eachWeb Service

A discovery document is just an XML file with references listed in the discoveryhierarchy Within thehierarchy, you can add as many service contracts as you have services and references to other DISCOdocuments throughout the server:

Trang 18

This is essentially what IIS will do, using dynamic discovery.

The DISCO concept depends on the client knowing where to start If you don’t know that a businessoffers a particular Web Service, you won’t know where to look for a DISCO document UDDI is all aboutchanging that

The UDDI Project

The DISCO format allows crawlers to index Web Services just as they index Web sites The robots.txt

approach, however, is dependent on the ability of a crawler to locate each Web site and find the location

of the service description file on that Web site The current system relies upon the interlocking nature ofWeb sites to crawl from site to site — there is no such visible connection between Web Services Thisleaves the programmer having to know where to begin looking for a Web Service before he starts

UDDI (Universal Description, Discovery, and Integration) takes an approach that relies upon a distributed

registry of businesses and their service descriptions implemented in a common XML format There is allsorts of helpful information about UDDI at www.uddi.org, but we’ll give you an introduction to it hereand talk about how it relates to Microsoft in general and Visual Basic in particular

UDDI can be thought of as the Yellow Pages for Web Services UDDI is a means of defining a standardway to publish and discover information about Web Services, so businesses can provide descriptions oftheir Web Services in terms of an XML file with white, yellow, and green pages:

The white pages include how and where to find the service.

The yellow pages include ontological classifications and binding information.

The green pages include the technical specification of the service.

In the XML schema for UDDI, this breaks into four elements: businessEntity, businessService,

bindingElements, and metadata, or tModels The tModelsprovide additional important technicalinformation that falls outside the bindingElementselement, but that is necessary for the consumption

of the service once it is bound

You can find the XML schema for this at www.uddi.org/schema/uddi_1.xsd, but you don’t have tounderstand it because UDDI provided an API that is built into the NET Framework, as discussed in thenext section Generally, though, each API function represents a publicly accessible SOAP message used

to get or place information about a registry entry For instance, the findServiceSOAP message listsavailable services based on the conditions specified in the arguments:

<find_service businessKey=”uuid_key” generic=”1.0” [ maxRows=”nn” ]

xmlns=”urn:uddi-org:api” >

[<findQualifiers/>]

<name/> | <categoryBag/> | <tModelBag/>

</find_service>

The parameters it accepts include maxRows, businessKey, findQualifiers, name, categoryBag, and

tModelBag On success, it returns a serviceListas a SOAP response object On the whole, it’s not thatmuch different from the COM world, except that SOAP is entirely an open standard

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 19

Using UDDI

The best thing about UDDI is how easy it is to use Many of us who started early in the Internet fieldremember filling out the InterNIC’s domain add/change forms, and having our own representative atthe NIC to help us when we were stuck Now, though, the Web handles registration of services — youonly need to really have a grasp of the discovery schema if you are going to build a registration site

In fact, Microsoft has a UDDI mirror if its own at http://uddi.microsoft.comwhere you can registeryour Web Services, just like adding them to DNS or a search engine Of course, you’ll have to have aMicrosoft Passport (another UDDI registered Web Service) to do it, but it is a rather simple task Afterregistering against your Passport, you enter business and contact information that is stored in yourUDDI registry Then you can add your Web Services

Where UDDI Is Headed

UDDI is the invisible fourth layer in the stack of protocols that represent Web Services Like DNS andHTTP, UDDI provides a needed interface between the SOAP messaging and the ubiquity of the servicethat is so important, but difficult to achieve

Going forward, UDDI as an organization sees itself being a global provider of discovery services for thebusiness-to-business (B2B) Web Services market, hosted throughout the world For instance, softwarecompanies can build applications that customize themselves based on services information in the UDDIregistry on installation Online marketplaces can back their market sites with UDDI technology to betterserve the growing needs of B2B value-added services

Future services planned by UDDI include the extension of the technology far beyond the specifications inthe Open Draft Eventually, regional and hierarchical searches will be accomplished through simple, effec-tive conventions The industry’s goal is much farther reaching than InterNICs was at the beginning —truly using the lessons learned in the past to shape the future

Microsoft’s commitment to UDDI is apparent from its use within Windows Server 2003 If you haveWindows Server 2003 Enterprise Edition, you can enable your server to be a UDDI server, and there is aUDDI database built right in as well

Security in Web Ser vices

Opening up a procedure call to remoting makes applications vulnerable to accidents, poor end-userimplementation, and crackers Any application design needs to include some level of security WebServices demand the inclusion of security

Security problems with Web Services fall into two categories — that of interception and that of rized use SOAP messages intercepted by crackers potentially expose private information such asaccount numbers and passwords to the public Unauthorized use at best costs money and at worstwreaks havoc within a system

unautho-Very few of the concepts discussed here are things we would like to see in the hands of those wearingthe black hats Even the simple validation service handles email addresses — a valuable commodity in

866

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 20

this world of “opt in” spamming If you add Social Security or account numbers to the service, then thisbecomes even more of a concern Fortunately, the wire transport of choice — HTTPS — provides a 128-bitsolution to these problems.

Also, as mentioned earlier, now by using Microsoft’s Web Services Enhancements (WSE) capabilities,you can easily apply security standards such as WS-Security to your SOAP messages

The Secure Sockets Layer

The Secure Sockets Layer, or SSL, is a protocol consumed by HTTP in the transfer of Internet data fromthe Web server to browser On the Web, the process works like this:

1. The user calls a secure Web document, and a unique public key is generated for the clientbrowser, using the server’s root certificate

2. A message, encrypted with the server’s public key, is sent from the browser

3. The server can decrypt the message using its private key

The protocol in the URI represents how HTTP would appear if it was changed to HTTPS:

<address uri=”https://aspx.securedomains.com/evjen/Validate.asmx” />

Then the service would make an SSL call to the server Remember that SSL is significantly slower thanHTTP, so you will suffer a performance hit Given the sensitivity of much of the information passingover Web Services, it is probably worth the slowdown

You can use NTFS permissions for individual directories within an application and require users to vide a valid username and password combination if they wish to access the service

pro-Web Service security is a large area to cover For more information, you should refer to the tion included with the NET Framework SDK.

documenta-The best approach to security is to use SSL and directory-level security together It is slow, and at timesinconvenient, but this is a small price to pay for the heightened level of security Though this is differentfrom the traditional role-based COM+ security, it is still very effective for running information acrossthe wire

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 21

Other Types of Security

The Windows platform also provides for other forms of security For instance, the Windows CryptoAPIsupplies access to most of the commonly used encryption algorithms — aside from the protocols used inSecure Sockets Layer Digital certificates (sort of a personal form of SSLServerCertificates) are nowrapidly becoming a powerful force in security

The Downside

There is a downside to any distributed architecture We’ve covered most of them in this chapter and gested workarounds — security, state, speed, and connectivity Let’s go over them once more to helpmake sure that Web Services are the way to go

sug-Security

The key to the issue and solution of security problems is the management of client expectations If WebServices are built securely to begin with, there will be no instances to draw concern or scrutiny Considerthe security of everything you write It’s fairly easy, and the payoff is great

State

State is less of a problem in a distributed architecture because in Windows DNA, Microsoft has been

say-ing for years that n-tier statefulness has to go Most developers are used to the idea, and if you aren’t,

then you need to get on the boat with the rest of us Architect your solutions to be loosely coupled.That’s what Web Services are made to do

Transactions

Web Services are not made for transactional systems If the Web server at MyCompany.comwas to access

a database at UPS for example, and the connection dropped in the middle, the lock on the databasewould remain without giving the network system at UPS a chance to solve the problem Web Servicesare by nature loosely coupled They are not designed for tight transactional integration

A common use of Web Services, communication between differing systems, prompted a number of nology architects to design a number of XML transaction protocols such as 2PC These packages providefor an understanding between two systems that the network link will remain stable

tech-Speed and Connectivity

Speed and connectivity are going to be a continuing problem until we have the ubiquitous bandwidth

of which George Gilder talks about in his book Telecosm (Free Press, 2000) Right now, the majority of

Internet devices that could really benefit from Web Services — cellphones, PDAs, and the like — arestuck at the paltry 14,000-bits per second currently supported by most wireless providers

868

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 22

For application development, this is a concern because when the router goes down, the application goesdown Right now, intranets continue to function when the ISP drops the ISDN With Web Services run-ning the links to customers and suppliers, that ISDN line becomes the company lifeline Redundancy ofconnections and a firm partnership with your service provider are the only solution.

Where We Go from HereThe cellphone is a listening device It listens for a call to its network address from the cell network.When it receives one, it follows some logic to handle the call Sound familiar? This works just like theRPC architecture and will be the format for a new host of devices that listen for Web Service calls overthe G3 wireless network

The first lines of the W3C XML group’s charter say:

New business communication will be via XML and Web Services, rather than EDI and VANs Micropaymentmay actually become a reality There are scores of promises that the Internet made since its inception that can

be fulfilled with Web Services and XML It won’t stop there, though The power of listening devices willbring Web Services development into user-to-user markets from business-to-business ones

It sounds far-fetched, but the hope is that you can see how the power of Web Services on NET couldmake this possible SOAP isn’t just about replacing the RPC architecture already out there It is a funda-mentally different way to think about the network as the platform

Summar yThis chapter looked at the need for an architecturally neutral, ubiquitous, easy-to-use, and interoperablesystem to replace DCOM, RMI, and CORBA It discussed how Web Services fill the gaps successfullybecause HTTP is used as the language-independent protocol, XML is its language (in WSDL) and trans-port mechanism, and SOAP allows you to package messages for sending over HTTP

Then, the chapter moved on to look at how to create and consume Web Services programmatically usingVisual Basic It discussed the abstract classes provided by the NET Framework class library to set upand work with Web Services In particular, it looked at the WebService, WebServiceAttribute,

WebMethodAttribute, and WebServiceBindingAttributecomponent classes of the System.Web.Servicesnamespace, in addition to the System.Web.Services.Description, System.Web.Services.Discovery, and System.Web.Services.Protocolsnamespaces

“Today, the principal use of the World Wide Web is for interactive access to ments and applications In almost all cases, such access is by human users, typically working through Web browsers, audio players, or other interactive front-end sys- tems The Web can grow significantly in power and scope if it is extended to support communication between applications, from one program to another.”

docu-Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 23

Next, it took a high-level look at some of the technologies supporting Web Services — namely DISCOand UDDI — before briefly covering security in Web Services.

Finally, it talked about some of the downsides to using any distributed architecture (Web Servicesincluded), but it finished with an optimistic note on where Web Services might take us in the future

870

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 24

Remoting is the NET technology that allows code in one application domain (AppDomain) to callinto the methods and properties of objects running in another application domain A major use ofremoting is in the classic n-tier desktop approach, where presentation code on the desktop needs

to access objects running on a server somewhere on the network Another primary use for ing is when code in ASP.NET Web forms or Web Services needs to call objects running on an appli-cation server somewhere on the network In short, remoting is the technology to use when your

remot-n-tier code needs to talk to the business or data tier that is running on an application server.

Remoting is conceptually somewhat similar to Web Services Both remoting and Web Services areTCP/IP-based technologies that allow communication between different machines over an IP net-work This means that they both pass through firewalls, and they both provide stateless and con-nectionless communication between machines These two technologies share a lot of the sameprinciples

SOAP’s biggest problem is that it is not lightweight It’s designed with maximum platform operability in mind, and this puts certain limits on how data can be transferred For example,imagine that Platform A stores Integer variables as a 4-byte block of memory, with the lowest-value byte appearing first Now imagine that Platform B also uses a 4-byte block of memory, butthis time the highest-value byte appears first Without some form of conversion, if you copy thatblock of bytes from Platform A to Platform B, because the encoding of the value is different, theplatforms won’t be able to agree on what the number actually is In this scenario, one platformthinks it’s got the number 4, whereas the other thinks that the number is actually 536870912

inter-It is important to recognize that Microsoft intends to merge the functionality of remoting, Web Services, Enterprise Services, and MSMQ (Microsoft Message Queue) into Indigo — the next generation of the technologies.

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 25

SOAP gets around this problem by representing numbers (and everything else) as strings of ASCII acters — as ASCII is a text-encoding standard that most platforms can understand However, this meansthat the native binary representations of the numbers have to be converted to text each time the SOAPdocument has to be constructed In addition, the values themselves have to be packaged in somethingthat you can read (with a little bit of effort) This leads to two problems: massive bloat (a 4-byte valuestarts taking hundreds of bytes to store) and wasted CPU cycles used in converting from native encod-ing to text encoding and back again.

char-You can live with all these problems if you only want to run your Web Service on, say, Windows 2000,and have it accessed through a client running on a cellphone SOAP is designed to do this kind of thing However, if you have a Windows XP desktop application that wants to use objects hosted on a Windows

2000 server (using the same platform), the bloated network traffic and wastage in terms of conversion issuboptimal at best and ridiculous at worst

Remoting lets you enjoy the same power of Web Services but without the downside If you want, youcan connect directly to the server over TCP and send binary data without having to do any conversions

If one Windows computer has a 4-byte block of memory holding a 32-bit integer value, you can safelycopy the bit pattern to another Windows computer and both will agree on what the number is In effect,network traffic sanity is restored and processor time isn’t wasted doing conversions

Now that you know what remoting is, you’re ready to understand its architecture

Remoting Over view

It’s important to understand several basics about remoting, including the basic terms and related objects,which are covered in the following sections

Basic Terminology

A normal object is not accessible via remoting By default, NET objects are only accessible to other coderunning within the same NET AppDomain

A remote object is an object that’s been made available over remoting by inheriting from System

.MarshalByRefObject These objects are often also called MBROs Remote objects are the same kinds ofobjects that you build normally, with the single condition that they inherit from MarshalByRefObject

and that you register them with the Remotingsubsystem to make them available to clients Remoteobjects are anchored to the machine and AppDomainwhere they were created, and you communicatewith them over the network

A serializable object is an object that’s been made available over remoting by marking the class with the

<Serializable()>attribute These objects will move from machine to machine or AppDomainto

AppDomain They are not anchored to any particular location, so they are unanchored objects A commonexample of a serializable object is the DataSet, which can be returned from a server to a client across thenetwork The DataSetphysically moves from server to client via the serialization technology in the.NET Framework

872

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 26

A remoting host is a server application that configures remoting to listen for client requests Remoting

runs within the host process, using the memory and threads of the host process to handle any clientrequests The most common remoting host is IIS You can create custom remoting hosts, which are typi-cally created as a Windows Service, so they can run even when no user is logged in to the server It isalso possible to have any NET application be a remoting host, which can allow you to emulate ActiveXEXE behaviors to some degree This last technique is most commonly used when creating peer-to-peer-style applications

A channel is a way of communicating between two machines Out-of-the-box, NET comes with two

channels: TCP and HTTP The TCP channel is a lightweight channel designed for transporting binarydata between two computers (You need to think of the TCP channel as being different from the TCPprotocol that HTTP also uses.) It works using sockets, something discussed in much more detail inChapter 26 HTTP, as you already know, is the protocol that Web servers use The HTTP channel hosted

in IIS is recommended by Microsoft

A formatter object is used to serialize or marshal an object’s data into a format in which it can be

trans-ferred down the channel Out of the box, you have two formatter objects: BinaryFormatterand

SoapFormatter The BinaryFormatteris more efficient and is recommended The SoapFormatter

is not recommended and may be discontinued in future versions of the NET framework

A message is a communication between the client and server It holds the information about the remote

object and the method or property that’s being invoked, as well as any parameters

A proxy is used on the client side to call into the remote object To use remoting, you don’t typically have

to worry about creating the proxy — NET can do it all for you However, there’s a slightly confusing

split between something called a transparent proxy and a real proxy A transparent proxy is so called

because “you can’t see it.” When you request a remote object, a transparent proxy is what you get Itlooks like the remote object (that is, it has the same properties and methods as the original), whichmeans that your client code can use the remote object or a local copy of the would-be-remote objectwithout your having to make any changes and without your knowing that there is any difference Thetransparent proxy defers the calls to the real proxy The real proxy is what actually constructs the mes-sage, sends it to the server, and waits for the response You can think of the transparent proxy as a “fake”object that contains the same methods and properties that the real object contains

The real proxy is effectively a set of helper functions that manages the communications You don’t usethe real proxy directly, instead, the transparent proxy calls into the real proxy on your behalf

A message sink is an “interceptor object.” Before messages go into the channel, these are used to do some

further processing on them, perhaps to attach more data, reformat data before it is sent, route debugginginformation, or perform security checking On the client side, you have an “envoy sink.” On the serverside, you have a “server context sink” and an “object context sink.” In typical use, you can ignore these Message sinks are a pretty advanced topic and allow for some powerful extensions to the remotingmodel It is not recommended that you create custom sinks, channels, or formatters, so they are not cov-ered in this book Creating them is not recommended because they will not transfer directly to Indigo,the next generation of the technology from Microsoft If you do opt to create your own custom sink, for-matter, or channel, you must expect to rewrite it from scratch when you upgrade to Indigo

Figures 24-1 and 24-2 show how these concepts fit together

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 27

Figure 24-1

Figure 24-1 shows how a client calls the Hellomethod of a transparent proxy object The transparentproxy looks just like the real object, so the client doesn’t even realize that remoting is involved Thetransparent proxy then invokes the real proxy, which converts the method call into a generic remotingmessage

This message is sent through any messaging sinks configured on the client These messaging sinks maytransform the message in various ways, including adding encryption or compressing the data

The message is then serialized by the formatter object The result is a byte stream that is sent to theserver by using the channel configured for use on the client

Figure 24-2 shows how the server handles the message The message comes into the server via a channel.The message is then deserialized by the formatter object and run through any messaging sinks configured

on the server These messaging sinks typically mirror those on the client, unencrypting or decompressingthe data as appropriate

Finally, the message is decoded by the object context sink, which uses the information in the message toinvoke the method on the actual object The object itself has no idea that it was invoked via remoting,since the method call was merely relayed from the client

Trang 28

Figure 24-2

SingleCall, Singleton, and Activated Objects

The next step is to look at the way that remoting treats objects In remoting, objects are divided into threecamps: wellknownobjects, client-activated objects, and serializable objects.

❑ wellknownobjects run on the server and perform a service for the remote application, such as

give me a list of all the customers or create an invoice They can be configured to act similarly to a

Web Service or use what’s called a singleton pattern (which is discussed shortly)

❑ Client-activated (Activated) objects are created for each client and maintain state on the serverover time In many ways, these objects act similar to COM objects you accessed via DCOM inthe past

❑ Serializable objects can move from machine to machine as needed For instance, a serializableobject can be created on the server (by a wellknownor Activatedobject), and then returned to

a client When the object is returned to the client, it is physically copied to the client machine,

where it can be used by client code

The following table summarizes the types of object

SingleCall(wellknown) An object is created for each client Stateless, per-method life

method call made to the server time, atomic methods,

no-threading issues, anchored to

AppDomainwhere created

Singleton(wellknown) One object exists on the server and Stateful, long-lived, shared

is used to handle all method calls instance, thread from all clients nization required, anchored

synchro-to AppDomainwhere created

Table continued on following page

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 29

Type Calling Semantics Key Attributes

Activated The client creates Activatedobjects Stateful, long-lived,

per-on the server The client can create client instances, threading many such objects Activatedobjects issues only if client is multi-are available only to the client that threaded, anchored to

Serializable The object is automatically copied Stateful, long-lived, no

from machine to machine when it is threading issues, passed as a parameter or returned anchored (moves across

non-as the result of a function network automatically)

The following sections discuss each in a bit more detail

SingleCall Objects

SingleCallobjects act much like typical Web Service objects Each time a client calls a method on a

SingleCallobject, an object is created specifically to handle that method call Once the method call iscomplete, the object is not reused and is garbage collected by the NET runtime

SingleCallobjects also work the way a JIT (just-in-time) Activatedobject does in COM+, andmatches the way most people use MTS or COM+ objects In those environments, good developers typi-cally create a server-side object, make a method call, and then release the object

These objects must inherit from System.MarshalByRefObject, so they are MBROs This means thatthey always run in the AppDomainand Windows process where they are created If they are created on aserver in a host process, that is where they live and run Clients interact with them across the network.The most commonly used type of service object in remoting is the SingleCallobject Not only do theseobjects provide semantics similar to Web Services, MTS, and COM+, but they also provide the simplestprogramming model

Since an object is created for each method call, these objects are inherently stateless Even if an objecttried to keep state between calls, it would fail because the object is destroyed after each method is com-plete This helps ensure that no method call can be affected by previous method calls or can contaminatesubsequent method calls

Each method call runs on its own thread (from the NET thread pool, as discussed in Chapter 22).However, since each method call also gets its very own object, there’s typically no contention betweenthreads This means that you don’t need to worry about writing synchronization or locking code in your

SingleCallcode

Technically, it is possible to encounter synchronization issues if there are shared stateful objects on the

server This requires substantial work to create and access such shared objects and is outside the scope of this book Typically, this type of model is not used, so threading is a nonissue with SingleCallobjects.

Because of their automatic isolation, statelessness, and threading simplicity, SingleCallobjects are thepreferred technology for creation of server code in remoting

876

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 30

As with the SingleCallscenario, all method calls are run on threads from the NET thread pool Thismeans that multiple simultaneous method calls can be running on different threads at the same time.

As discussed in Chapter 22, this can be complex since you have to write multithreaded synchronizationcode to ensure that these threads don’t collide as they interact with your Singletonobject

Singletonobjects have a potentially unpredictable lifespan When the first client makes the firstmethod call to the object, it is created From that point forward, it remains in memory for an indetermi-nate period of time As long as it remains in memory, all method calls from all the clients will be handled

by this one object However, if the object is idle for a long time, remoting may release it to conserveresources Also, some remoting hosts may recycle their AppDomainobjects, which will automaticallycause the destruction of all your objects

Because of this, you can never be certain that the data stored in memory in the object will remain able over time This means that any long-term state data must be written to a persistent store like adatabase

avail-Due to the complexity of shared memory, thread synchronization, and dealing with object lifetimeissues, Singletonobjects are more complex to design and code than SingleCallobjects While theycan be useful in specialized scenarios, they aren’t as widely used as SingleCallobjects

Activated Objects

Client-activated (or Activated) objects are different from both SingleCalland Singletonobjects

Activatedobjects are created by a client application, and they remain in memory on the server overtime They are associated with just that one client, so they are not shared between clients Also, they arestateful objects, meaning that they can maintain data in memory during their lifetime

These objects must inherit from System.MarshalByRefObject, so they are MBROs This means thatthey always run in the AppDomainand Windows process where they are created If they are created on aserver in a host process, that is where they live and run Clients interact with them across the network

A client can create multiple Activatedobjects on the server The objects will remain on the server untilthe client releases the objects or the server Appdomainis reset (which can happen with some types ofremoting host) Also, if the client doesn’t contact the server for several minutes, the server will assumethe client abandoned the objects and it will release them

Activatedobjects typically don’t have any threading issues The only way multiple threads will be ning in the same Activated object is if the client is multithreaded and multiple client threads simultane-ously make method calls to the same server-side Activated object If this is the case in your application,then you’ll have to deal with shared data and synchronization issues as discussed in Chapter 22

run-Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 31

While long-lived, stateful, per-client objects can be useful in some specialized scenarios, they are not

commonly used in most client/server or n-tier application environments By storing per-client state in

an object on the server, this type of design reduces the scalability and fault tolerance of a system

Serializable Objects

While SingleCall, Singleton, and Activatedobjects are always anchored to the Appdomain,Windows process, and machine where they are created, this is not the case with serializable objects.Serializable objects can move from machine to machine as needed The classic example of this is theADO.NET DataSet, which can be returned as a result of a function on a server The DataSetphysicallymoves to the client machine, where it can be used by client code When the client wants to update the

DataSet, it simply passes the object to the server as a parameter, causing the DataSetto physicallymove to the server machine

These objects do not inherit from System.MarshalByRefObject Instead, they are decorated with the

<Serializable()>attribute and may optionally implement the ISerializableinterface The ing is a very basic implementation of a <Serializable()>object:

follow-<Serializable()> _

Public Class Customer

Private mName As String = “”

Public Property Name() As StringGet

Return mNameEnd GetSet(ByVal value As String)mName = value

End Set

Public Sub Load()

‘ Load data here

End SubEnd Class

<Serializable()>objects are not anchored to the Appdomainor Windows process where they werecreated The remoting subsystem will automatically serialize these objects’ data and transfer it across thenetwork to another machine On that other machine, a new instance of the objects will be created andloaded with the data, effectively cloning the objects across the network

When working with serializable objects, it’s typically a good idea to use a SingleCallobject on theserver to create the serializable object and call any server-side methods (such as ones to load the objectwith data from a database) The SingleCallobject will then return the serializable object to the client as

a function result, so the client can then interact with the object The SingleCallobject’s method mightlook like the following:

Public Function GetCustomer(ByVal ID As Integer) As Customer

Dim cust As New Customer()cust.Load(ID)

Trang 32

The client code might look like this:

Dim cust As Customer

cust = myService.GetCustomer(123)TextBox1.Text = cust.Name()

Note that both server and client code have direct, local access to the Customerobject, because it is matically copied from the server to the client as a result of the GetCustomermethod call

auto-Serializable objects can be very useful in many client/server scenarios, especially if the application iscreated using object-oriented application design principles

Implementing RemotingWhen you implement an application using remoting, there are three key components to the application.Client The application calling the server

Server Library The DLL containing the objects to be called by the client Host The application running on the server that hosts remoting and the Server Library

Basically, you create your server-side objects in a Visual Basic NET class library project Then, youexpose the classes in that DLL from your server-side remoting host application With the objects exposed

on the server, you can then create client applications that call the objects in the Server Library DLL.You might also have some other optional components to support various scenarios

Interface A DLL containing interfaces that are implemented by the objects in the Server

LibraryProxy A DLL containing generated proxy code based on the objects in the Server LibraryShared Library A DLL containing serializable objects that must be available to both the Server

Library and the client

Each of these is discussed in detail as it is used later in the chapter For now, it’s time to get into somecode and see how remoting works

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 33

The host needs the information because it will be exposing the library DLL to clients via remoting.However, the client needs the information in order to know which objects to create and what methodsare available on those objects.

Since you know that the library DLL will be on the server, it is easy enough for the host application tojust reference the DLL to get the type information The client is a bit trickier though, since the libraryDLL won’t necessarily be on the client machine There are three options for getting the type information

to the client

Reference the library DLL This is the simplest approach, since the client just references the

DLL directly and, thus, has all the type information The drawback isthat the DLL must be installed on the client along with the clientapplication

Use an interface DLL This approach is more complex The classes in the library DLL must

implement formal interfaces as defined in this interface DLL Theclient can then reference just the interface DLL, so the library DLLdoesn’t need to be installed on the client machine The way the clientinvokes the server is different when using interfaces

Generate a proxy DLL This approach is of moderate complexity The server must expose the

objects via HTTP, so you can run the soapsuds.exe command-lineutility The utility creates an assembly containing the type informa-tion for the library DLL classes exposed by the server The client thenreferences this proxy assembly rather than the library DLL

You’ll implement all three options in this chapter, starting with the simplest — referencing the libraryDLL directly from the client application

Library DLL

To begin, create the library DLL This is just a regular Class Libraryproject, so open Visual Studio.NET (VS.NET) and create a new class library named SimpleLibrary Remove Class1.vband add anew class named Calculator Since you’re creating a well-known remoting object, it must inherit from

Singleton, or Activated For SingleCallyou know that an instance of Calculatorwill be created

for each method call, so there’s absolutely no point in using any class-level variables After all, they’ll be

destroyed along with the object when each method call is complete

880

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 34

It also means that you can’t have the client call a sequence of methods on your object Since each methodcall gets its own object, each method call is entirely isolated from any previous or subsequent methodcalls In short, each method must stand alone.

For illustration purposes, you need to prove that the server-side code is running in a different processfrom the client code The easiest way to prove this is to return the thread IDwhere the code is running.You can compare this thread IDto the thread IDof the client process If they are different, then you aresure that the server-side code really is running on the server (or at least in another process on yourmachine)

Add the following method:

Public Function GetThreadID() As Integer

Return Threading.Thread.CurrentThread.ManagedThreadId

End Function

You can add other Publicmethods as well if you’d like, for instance:

Public Function Add(ByVal a As Integer, ByVal b As Integer) As Integer

Return a + b

End Function

Since this is a calculator class, it only seems appropriate that it should do some calculations

At this point, you have a simple but functional Calculatorclass Build the solution to create the DLL.Your remoting host application will use this DLL to provide the calculator functionality to clients

Host Application

With the server-side library complete, you can create a remoting host It is recommended that you useIIS as a remoting host, but it is quite possible to create a custom host as well You’ll use IIS later in thechapter, but for now let’s see how you can create a custom host in a ConsoleApplication for testing

Most custom hosts are created as a Windows Service so the host can run on the server even when no user is logged into the machine However, for testing purposes, a console application is easier to create and run.

The advantage to a custom host is that you can host a remoting server on any machine that supports the.NET Framework This includes Windows 98 and up If you use IIS as a host, you can only host onWindows 2000 and up, which is a bit more restrictive

The drawback to a custom host is that it isn’t as robust and capable as IIS, at least, not without a lot ofwork For this chapter’s example, you’re not going to attempt to make your host as powerful as IIS.You’ll just stick with the basic process of creating a custom host

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 35

Setting up the Project

Create a new solution in VS.NET, with a console application named SimpleServer

Since the remoting host will be interacting with remoting, you need to reference the appropriate work DLL Use the Add Referencedialog box to add a reference to System.Runtime.Remoting, asshown in Figure 24-3

Referencing the Library DLL

There are two ways to configure remoting, via a configuration file or via code If you opt for the ration file approach, then the only requirement is that SimpleLibrary.dllbe in the same directory asyour host application You don’t even need to reference SimpleLibrary.dllfrom the host However, ifyou opt to configure remoting via code, then your host must reference SimpleLibrary.dll

configu-Even if you go with the configuration file approach, referencing SimpleLibrary.dllfrom the host ject allows VS.NET to automatically keep the DLL updated in your project directory, and it means thatany setup project you might create will automatically include SimpleLibrary.dll In general, it is agood idea to reference the library DLL from the host and that’s what you’ll do here

pro-Add a reference to SimpleLibrary.dllby clicking the Browse button in the Add References dialogbox and navigating to the SimpleLibrary\bin\releasedirectory, as shown in Figure 24-4

882

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 36

Figure 24-4

All that remains now is to configure remoting

Configuring Remoting

The typical way to do this is with a configuration file Open the app.configfile in the SimpleServer

project In this configfile, you’ll add a section to configure remoting Remember that XML is sensitive, so the slightest typo here will prevent remoting from being properly configured:

Notice that all configuration is within the <system.runtime.remoting> element, and then within an

<application>element The real work happens first inside the <service>element The <service>

element tells remoting that you’re configuring server-side components Within this block is where you

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 37

define the classes you want to make available to clients You can define both wellknownand Activated

classes here In this case you’re defining a wellknownclass:

<wellknown mode=”SingleCall”

objectUri=”Calculator.rem”

type=”SimpleLibrary.Calculator, SimpleLibrary” />

The mode will be either SingleCallor Singletonas discussed earlier in the chapter

The objectUriis the “end part” of the URL that clients will use to reach your server You’ll revisit this in amoment, but this is basically how it fits (depending on whether you’re using the TCP or HTTP protocol):

han-Finally, the type defines the full type name and assembly where the actual class can be found Remotinguses this information to dynamically load the assembly and create the object when requested by a client.You can have many <wellknown>blocks here to expose all the server-side classes you want to makeavailable to clients

The other key configuration block is where you specify which remoting channel (protocol) you want touse You can choose between the TCP and HTTP channels

TCP Slightly faster than HTTP, but less stable and not recommended

HTTP Slightly slower than TCP, but more stable and is recommended

Since you’ll look at the HTTP channel later, you’re using the TCP channel now Either way, you need tospecify the IP port number on which you’ll be listening for client requests When choosing a port for aserver, you should keep the following port ranges in mind:

0–1023— Well-known ports reserved for specific applications such as Web servers, mail servers,and so on

1024–49151— Registered ports that are reserved for various widely used protocols such asDirectPlay

49152–65535— Intended for dynamic or private use, such as for applications that might be forming remoting with NET

per-884

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 38

You’re setting remoting to use a TCP channel, listening on port 49341:

Console.Read()End Sub

The Console.Writeand Console.Readstatements are there to ensure that the application stays ning until you are ready for it to terminate The line that actually configures remoting is:

run-RemotingConfiguration.Configure( _AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)

You are calling the Configuremethod, which tells remoting to read a configfile and to process the

<system.runtime.remoting>element in that file You want it to use your application configurationfile, so you pass that path as a parameter Fortunately, you can get the path from your AppDomainobject

so you don’t have to worry about hard-coding the file name

Configuring Remoting via Code

Your other option is to configure the remoting host via code To do this you’d write different code in

Sub Main:

Sub Main()

RemotingConfiguration.RegisterWellKnownServiceType( _GetType(SimpleLibrary.Calculator), _

“Calculator.rem”, _WellKnownObjectMode.SingleCall)

System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel( _New System.Runtime.Remoting.Channels.Tcp.TcpServerChannel(49341))

Console.Write(“Press <enter> to exit”)Console.Read()

End Sub

You can see that you’re providing the exact same information here as you did in the configfile, onlyvia code You call RegisterWellKnownServiceType, passing the mode, objectUri, and type datajust as you did in the configfile Then, you call RegisterChannel, passing a new instance of the

TcpServerChannelconfigured to use the port you chose earlier

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 39

The end result is the same as using the configfile Most server applications use a configfile to ure remoting because it allows you to change things like the channel and port without having to recom-pile the host application.

config-Build the solution At this point your host is ready to run Open a Command Prompt window, navigate

to the bindirectory, and run SimpleServer.exe

Client Application

The final piece of the puzzle is to create a client application that calls the server

Setting Up the Project

Here’s how to create a new VS.NET solution with a Windows Application named SimpleClient Asdiscussed earlier, the client needs access to the type information for the classes it wants to call on theserver The easiest way to get this type information is to have it reference SimpleLibrary.dll Sinceyou’ll be configuring remoting, you also need to reference the remoting DLL Then import the remotingnamespace in Form1:

Imports System.Runtime.Remoting

Now, you can write code to interact with the Calculatorclass Add controls to the form as shown inFigure 24-5

Figure 24-5

Name the controls (in order): ConfigureButton, CodeConfigureButton, LocalThreadButton,

LocalThread, RemoteThreadButton, RemoteThread First, let’s write the code to get the thread ID

values for each object:

Private Sub LocalThreadButton_Click( _

ByVal sender As System.Object, ByVal e As System.EventArgs) _Handles LocalThreadButton.Click

LocalThread.Text = CStr(Threading.Thread.CurrentThread.ManagedThreadId)

End Sub

Private Sub RemoteThreadButton_Click( _

ByVal sender As System.Object, ByVal e As System.EventArgs) _Handles RemoteThreadButton.Click

886

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 40

Dim calc As New SimpleLibrary.Calculator

RemoteThread.Text = CStr(calc.GetThreadID)

End Sub

Displaying the thread ID of the local process is easily accomplished More interesting though, is thatyour code to interact with the Calculatorclass doesn’t look special in any way Where’s the remotingcode?

It turns out that there’s this idea of location transparency, where it is possible to write “normal” code that

interacts with an object whether it is running locally or remotely This is an important and desirable traitfor distributed technologies, and remoting supports the concept Looking at the code you’ve written,you can’t tell if the Calculatorobject is local or remoting; its location is transparent

All that remains is to configure remoting so that it knows that the Calculatorobject should, in fact, becreated remotely As with the server, you can configure clients either via a configfile or through code.Before you configure remoting, you need to realize something important If remoting is not configuredbefore the first usage of SimpleLibrary.Calculator, then the Calculatorobject will be createdlocally If that happens, configuring remoting won’t help, and you’ll never create remote Calculator

objects

To prevent this from happening, you need to make sure that you can’t interact with the class until afterremoting is configured Typically, this is done by configuring remoting as the application starts up,either in Sub Mainor in the first form’s Loadevent In this case, however, you’re going to configureremoting behind some buttons, so a different approach is required

In Form_Load, add the following code:

Private Sub Form1_Load( _ByVal sender As System.Object, ByVal e As System.EventArgs) _Handles MyBase.Load

Ngày đăng: 12/08/2014, 23:23