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

C# ПІДРУЧНИКИ / c# / MS Press - Msdn Training Programming Net Framework With C#

.pdf
Скачиваний:
194
Добавлен:
12.02.2016
Размер:
16.87 Mб
Скачать

Module 13: Remoting and XML Web Services

17

 

 

 

The only difference between GetObject and new is that GetObject allows you to specify a Uniform Resource Identifier as a parameter, while new obtains the Uniform Resource Identifier from the configuration file.

You can use CreateInstance or new for client-activated objects. Both CreateInstance and new allow you to instantiate an object by using constructors with parameters. The lifetime of client-activated objects is controlled by the leasing service that is provided by the remoting framework.

Using Activator.GetObject

The following example code shows how to obtain a server-activated object by using Activator.GetObject:

HelloServer obj = (HelloServer)Activator.GetObject( typeof(RemotingSamples.HelloServer), "tcp://localhost:8085/SayHello");

In the preceding example, "tcp://localhost:8085/SayHello" specifies that a connection should be made to the remote object at the SayHello endpoint by using TCP on port 8085.

Using the new Operator

To use the new operator, you must load a configuration file with the remote object’s information. For example, for a file called MyHello.exe.config, you load the configuration file as follows:

RemotingConfiguration.Configure("MyHello.exe.config");

After the configuration file has been loaded, the client can activate the object as follows:

HelloServer obj = new HelloServer();

18

Module 13: Remoting and XML Web Services

Client Compilation Techniques

Topic Objective

To explain how type information is provided to the compiler.

Lead-in

When compiling the client code, the compiler requires type information about the

HelloServer class.

!When the Client Is Compiled, the Compiler Needs Server Class Data

!Class Information Can Be Provided by:

#A reference to the assembly where the class is stored

#Splitting the remote object into an implementation class and an interface type

#Using Wsdl.exe to extract the required metadata directly from the endpoint

*****************************ILLEGAL FOR NON-TRAINER USE******************************

When compiling the client code, the compiler requires type information about the HelloServer class. This type information is discussed in the preceding topic.

You can provide type information in one of the following ways:

!Provide a reference to the assembly in which the HelloServer class is stored.

Providing a reference is useful when the client and server components are developed at the same site.

!Split the remote object into an implementation class and an interface type, and use the interface as a reference when compiling the client.

Splitting the remote object into an implementation class and an interface type is useful when the client and server components are not developed at the same site. The interface or interfaces can be compiled to a DLL and shipped to the client sites when necessary. According to COM guidelines, you should avoid changing the published interface.

!Use the Web Services Description Language tool (Wsdl.exe) to extract the required metadata directly from the endpoint.

The Web Services Description Language tool lets you connect to the endpoint that is provided, extract the metadata, and generate source code that can then be used to compile the client. The Web Services Description Language tool is useful when client and server components are developed at different sites and when no interface classes are available.

To use the Web Services Description Language tool, point the tool at a remote Uniform Resource Identifier and generate the required metadata.

Note The Web Service Utility extracts only metadata and does not generate the source for the remote object.

Module 13: Remoting and XML Web Services

19

 

 

 

Remoting Configuration Files

Topic Objective

To explain how to configure objects with configuration files for use in remoting.

Lead-in

Programmatic registration is a simple process, but it is not practical for use in reallife situations where large numbers of remote objects must be managed on a corporate network.

! Configure Method on RemotingConfiguration

RemotingConfiguration.Configure(foo.exe.config);

RemotingConfiguration.Configure(foo.exe.config);

!An Application Configuration File is an XML Document

#Configuration files are case-sensitive

#Can be specified on a machine or on an application level

Application level configuration takes priority over machine level configuration

#For more information see “Remoting Configuration File Format” in the .NET Framework SDK documentation

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Programmatic registration is a simple process, but it is not practical for use in real-life situations where large numbers of remote objects must be managed on a corporate network. Remoting configuration solves this problem by using a configuration file, a simple mechanism, to register an object.

To configure an object with a configuration file, call the Configure method on

RemotingConfiguration, as shown in the following example:

using System; using System.IO;

using System.Runtime.Remoting;

public class MyHost

{

public static void Main(String[] args)

{

if (args.Length == 0)

{

//Perform a default configuration, throw an exception

//or display usage information to the user

}

else

{

RemotingConfiguration.Configure (args[0]);

}

//The program should pause here till the

//registered objects are no longer required

}

}

20

Module 13: Remoting and XML Web Services

The Configure method loads the configuration file into memory, parses the contents, and calls the relevant methods to register the channels and objects that are described in the file.

You can also use configuration files to store such settings as binding policy and security. The name of the configuration file includes the full module name and the extension, with .config appended to that extension. For example, the configuration file name for Foo.exe is Foo.exe.config.

Although .NET Remoting does not mandate how you name a configuration file, you should use the naming convention that is described in the preceding paragraph to ensure that specific security and binding policies are picked up when an application is executed.

The Configure call on RemotingConfiguration only reads the relevant sections in the configuration file that apply to remoting, while the rest of the information is ignored.

Module 13: Remoting and XML Web Services

21

 

 

 

An application configuration file is an XML document that contains sections for various feature areas. The general format is a follows:

Note Configuration files are case-sensitive.

<configuration>

<system.runtime.remoting>

<application>

<lifetime>

<!--Default lifetime information for all --> <!--objects in the application. Individual --> <!--service objects can customize these -->

</lifetime>

<service>

<!--Specifies one or more remote objects provided by --> <!--this service. These can be client-activated --> <!--as well as server-activated -->

</service>

<client>

<!--Specifies a remote object this client used --> <!--One or more clients can be specified -->

</client>

<SOAPinterop>

<!--Specify type, assembly and XML information --> <!--to use deserializing data from SOAP endpoints -->

</SOAPinterop>

<channels>

<!--List all channels the client or service require.--> <!—-Individual clients or services can customize the --> <!—-machine level settings -->

</channels>

</application>

<channels>

<!--Provide a list of the channel and sink providers.--> <!--This data will normally be provided on a machine --> <!--level in the machine configuration file -->

</channels>

<channelSinkProviders>

<clientProviders>

<!--one or more client providers --> </clientProviders>

<serverProviders>

<!--one or more server providers --> </serverProviders>

</channelSinkProviders>

</system.runtime.remoting>

</configuration>

All configuration information can be specified on a machine or on an application level. Application level configuration takes priority over machine level configuration.

For more information about the .NET Remoting configuration file format, see “Remoting Configuration File Format” in the .NET Framework SDK documentation.

22

Module 13: Remoting and XML Web Services

Demonstration: Remoting

Topic Objective

To demonstrate how a client application uses .NET Remoting to make a method call on an object in a server application.

Lead-in

This demonstration shows how a client application uses .NET Remoting to make a method call on an object in a server application.

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Delivery Tip

Although this demonstration includes detailed instructions, this is not a guided practice. Present the demonstration and suggest that the students try the demonstration for themselves later.

This demonstration shows how a client application can use .NET Remoting to make a method call on an object in a server application.

Important Before running the application, ensure that all currently running server applications that may be using the same port number have been closed. Running more than one server that uses the same port number will generate an error.

Tip You can display your machine’s current TCP/IP network connections by running the program netstat in a command prompt window. The following example shows that port 7 is in use by a process with PID 1504:

C:\>netstat -o -n -a

Active Connections

Proto

Local Address

Foreign Address

State

PID

TCP

0.0.0.0:7

0.0.0.0:0

LISTENING

1504 …

 

 

 

 

 

Module 13: Remoting and XML Web Services

23

 

 

 

Server-Side

The following sample code is the server source code, which is named Server.cs:

using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using System.Runtime.Remoting.Channels.Http;

namespace RemotingSamples

{

public class HelloServer : MarshalByRefObject

{

public int callCounter = 0;

public static int Main(string [] args)

{

TcpChannel chan1 = new TcpChannel(8085);

HttpChannel chan2 = new HttpChannel(8086);

ChannelServices.RegisterChannel(chan1);

ChannelServices.RegisterChannel(chan2);

/*

RemotingConfiguration.RegisterWellKnownServiceType

(

typeof(HelloServer),

"SayHello",

WellKnownObjectMode.Singleton

);

*/

RemotingConfiguration.RegisterWellKnownServiceType(

typeof(HelloServer),

"SayHello",

WellKnownObjectMode.SingleCall

);

System.Console.WriteLine("Press Enter key to exit"); System.Console.ReadLine();

return 0;

}

(Code continued on the following page.)

24

Module 13: Remoting and XML Web Services

public HelloServer()

{

Console.WriteLine("HelloServer activated");

}

public String HelloMethod(String name, out int counter)

{

counter = ++callCounter; Console.WriteLine(

"Server Hello.HelloMethod : {0} Counter :{1}", name, callCounter);

return "Hi there " + name;

}

}

}

The RemotingSamples.HelloServer class is derived from

MarshalByRefObject, so HelloServer is remotable. When the server is started, you create and register a TCP channel that listens for clients to connect on port 8085 and an HTTP channel that listens for clients to connect on port 8086. You also register the remote object with the remoting framework by calling RegisterWellKnownServiceType.

The parameters for this call include the following:

!The full type of the object that is being registered, such as

RemotingSamples.HelloServer in the preceding example

!The name of the endpoint where the object will be published

To connect to the object, clients must know the name of the endpoint. Any string can be used. In the preceding example, you use SayHello.

You can also connect to remote objects through ASP.NET. In the preceding example, if you were connecting to remote objects through ASP.NET, the endpoint would be RemotingSamples/HelloServer.soap.

!The object mode, which can be SingleCall or Singleton

In the preceding example, you initially specify SingleCall. The object mode specifies the lifetime of the object when it is activated on the server. In the case of SingleCall objects, a new instance of the class is created for each call that is made from a client, even if the same client calls the same method more than once.

Singleton objects, on the other hand, are created only once, and all clients communicate with the same object.

Module 13: Remoting and XML Web Services

25

 

 

 

Client-Side

The following sample code is the client source code, which is named Client.cs:

using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using System.Runtime.Remoting.Channels.Http; using System.IO;

namespace RemotingSamples

{

public class Client

{

public static int Main(string [] args)

{

int counter;

TcpChannel chan1 = new TcpChannel(); ChannelServices.RegisterChannel(chan1);

HelloServer obj1 = (HelloServer)Activator.GetObject( typeof(RemotingSamples.HelloServer), "tcp://localhost:8085/SayHello");

if (obj1 == null)

{

System.Console.WriteLine(

"Could not locate TCP server"); return 1;

}

HttpChannel chan2 = new HttpChannel(); ChannelServices.RegisterChannel(chan2);

HelloServer obj2 =(HelloServer)Activator.GetObject( typeof(RemotingSamples.HelloServer), "http://localhost:8086/SayHello");

if (obj2 == null)

{

System.Console.WriteLine(

"Could not locate HTTP server"); return 1;

}

(Code continued on the following page.)

26

Module 13: Remoting and XML Web Services

try

{

Console.WriteLine(

"Client1 TCP HelloMethod {0} Counter {1}", obj1.HelloMethod("Caveman", out counter), counter);

Console.WriteLine(

"Client2 HTTP HelloMethod {0} Counter {1}", obj2.HelloMethod("Caveman", out counter), counter);

}

catch (IOException ioExcep)

{

Console.WriteLine("Remote IO Error" + "\nException:\n" + ioExcep.ToString());

return 1;

}

return 0;

}

}

}

When the client starts up, it registers a TCP channel and an HTTP channel and proceeds to activate an object on each channel by calling the GetObject method on the Activator class.

The parameters for this call are the type of the name of the class that you need to activate, RemotingSamples.HelloServer, and the endpoint Uniform Resource Identifier.

For the client’s TCP connection, the Uniform Resource Identifier is tcp://localhost:8085/SayHello.

For the client’s HTTP connection, the Uniform Resource Identifier is

http://localhost:8086/SayHello.

Important The Uniform Resource Identifier includes the protocol, computer name, and port number, as well as the endpoint. If the server is deployed on a host that is named Sunshine, clients can connect to the server that is using TCP by specifying tcp://sunshine:8085/SayHello.

When you run the client, it locates and connects to the server, retrieves a proxy for the remote objects, and calls the HelloMethod on the remote objects, passing the string Caveman as a parameter and the counter as an out parameter. The server returns Hi there Caveman and the count of the number of times that the server object’s method has been called.

Соседние файлы в папке c#