presentation 23: .net remoting introduced

31
Presentation 23: .NET Remoting Introduced Objektorienteret Netværkskommunikation

Upload: amadeus-franks

Post on 03-Jan-2016

44 views

Category:

Documents


0 download

DESCRIPTION

Presentation 23: .NET Remoting Introduced. Objektorienteret Netværkskommunikation. Outline. .NET Framework introduced .NET Remoting Strategies Architecture Remoting object types Activation Lifetime Deployment Example application Windows Communication Foundation short intro. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Presentation 23: .NET Remoting Introduced

Presentation 23:.NET Remoting Introduced

Objektorienteret Netværkskommunikation

Page 2: Presentation 23: .NET Remoting Introduced

Outline

• .NET Framework introduced• .NET Remoting

• Strategies

• Architecture

• Remoting object types

• Activation

• Lifetime

• Deployment

• Example application

• Windows Communication Foundation short intro

Page 3: Presentation 23: .NET Remoting Introduced

Not a Windows .NET course

• You will NOT be required to be an expert on .NET• You will be required to be knowledgeable about it

• History:• Open source, Java, Linux the WWW threatened MS

• Especially Java was gaining widespread support amongst developers for its ease of use, productivity and heterogeneity

• The Empire Strikes back = the .NET Framework

Page 4: Presentation 23: .NET Remoting Introduced

Benefits of .NET

• Changes EVERYTHING• Takes all that was nice in Java and enhances it• End of DLL incompatibilities, DLL Hell, COM registry hell • Enter world of VM’s and Java like code (C#) including

Garbage collection – BUT with easy support for legacy unmanaged code (e.g. C++ for speed) and COM

• Performs much better than Java, and almost equivalent with Win32 C++ applications

• Still only support Microsoft operating systems BUT• .NET and C# is ECMA standard: Mono (www.go-mono.org)

for Linux is being developed. • IIOP.NET (http://iiop-net.sourceforge.net/index.html) for CORBA interop

Page 5: Presentation 23: .NET Remoting Introduced

.NET Framework

Win32Win32

MessageMessageQueuingQueuing

COM+COM+(Transactions, Partitions, (Transactions, Partitions,

Object Pooling)Object Pooling)IISIIS WMIWMI

Common Language RuntimeCommon Language Runtime

.NET Framework Class Library.NET Framework Class Library

ADO.NET and XMLADO.NET and XML

XML Web ServicesXML Web Services User InterfaceUser Interface

VisualBasic C++ C# Perl JScript …

Application services. E.g. IIS, Message Queuing etc.

CLR:runtime execution environment. Equlas JVM of Java. Microsoft Intermediate Language (MSIL) equals Java ByteCode

A collection of class libraries (over 9000) wraps Win32 like Java API

ActiveX Data Objects

3 types of user interfaces: Web forms, Windows forms (Win32), Command Console

For inter-process communications

Any language conforming to the Common Language Specification (CLS) may be used.

Sourcecode

Sourcecode CompilerCompiler

IntermediateLanguage

IntermediateLanguage

.NETFramework

.NETFramework

Other ILlibrariesOther ILlibraries

LinkerLinkerLinked

ProgramLinked

Program JIT-compilerJIT-compilerExecutableProgram

ExecutableProgram

Here we find the .NET Remoting libraries

Page 6: Presentation 23: .NET Remoting Introduced

Strategies• Two .NET Remoting strategies (+ new strategy WCF) :

• Web services for inter-business purposes• Is heterogeneous across platforms and languages• Supported by the .NET compact framework• Relies primarily on HTTP/SOAP protocols, • May be adapted for any type of protocol • Heterogeneous • Is slow when used with HTTP/SOAP

• .NET Remoting for intra-business purposes • Is only heterogeneous across CLS languages• Not supported by the .NET compact framework• Relies on either HTTP/SOAP or TCP/Binary protocols,• May be adapted for any type of protocol • Is fast when used with TCP/Binary• Only heterogeneity within .NET runtime• In many ways very similar to Java RMI in Java 5

Page 7: Presentation 23: .NET Remoting Introduced

Simplified .NET Remoting Architecture

Using the classic Proxy patternUsing the classic Proxy pattern

The Remoting System wraps most of the marshalling/unmarshalling work for you – like CORBAThe Remoting System wraps most of the marshalling/unmarshalling work for you – like CORBA

Channel:

Takes a stream of data and transports it to another computer or process:

Default: TcpChannel & HttpChannel

Channel:

Takes a stream of data and transports it to another computer or process:

Default: TcpChannel & HttpChannel

Page 8: Presentation 23: .NET Remoting Introduced

The Remoting Architecture

Proxy created dynamically by the CLR. Creates a message to the server

Proxy created dynamically by the CLR. Creates a message to the server

Serializes the message into a stream (SOAP or binary)

Serializes the message into a stream (SOAP or binary)

Optional extra handlingOptional extra handling

Writes the stream to the wire, e.g. TCP or HTTP

Writes the stream to the wire, e.g. TCP or HTTP

Deserializes the messageDeserializes the message

Developers are free to implement new channels or replace sink elementsDevelopers are free to implement new channels or replace sink elements

All server objects must be of type MarshalByRefObject or an descendant hereof

All server objects must be of type MarshalByRefObject or an descendant hereof

Dispatch to server objectDispatch to server object

Page 9: Presentation 23: .NET Remoting Introduced

Remotable Objects in .NET Remoting

• Marshal-by-reference objects• By-reference – no state is transferred• MarshalByRefObject • Corresponds to CORBA Interface IDL and Java RMI Remote

objects (UnicastRemote objects)• Proxy created

• Marshal-by-value objects• By-value – complete object is serialized and transferred• Implements ISerializable or decorated with Serializable

Attribute [Serializable]• Very similar to Java RMI Serializable objects• Some similarity with CORBA valuetypes (Objects by Value)

Page 10: Presentation 23: .NET Remoting Introduced

Activation

• All server objects needs to be activated before a client proxy may access it

• Two types of activation• Server Activation (SAO)

• Activated when first client request arrives at server– Singleton: only one server instance for all clients– Single-call: a new server object pr. client request

• Lifetime is defined by server• Client Activation (CAO)

• Activated by the client with the CreateInstance method on the Activator object

• Server object only associated with creating client• Lifetime is controlled by client (using leases)

• Very different semantics than CORBA & RMI – closer to Web services (application, session, request scope) especially SAO

Page 11: Presentation 23: .NET Remoting Introduced

Lifetime management

• .NET Remoting uses leases for lifetime management• All server objects has a lifetime lease – a time-to-live• Lease manager

• controls the server object leases• If expired – check all sponsors (clients)• performs garbage collection on server objects

• In DCOM • reference counting & pinging

• In CORBA• ORB vendor specific• Often implemented as “time since last request”

• In Java RMI• uses leases (similar to .NET Remoting). Clients auto-update lease at

50%• Web services

• Toolkit specific (HTTP primitives: Application, Session, Request)• Application scope = runs for-ever / singleton

Page 12: Presentation 23: .NET Remoting Introduced

Configuration

• Configuration:• Need to inform runtime which servers are available and

at which address (URL)

• Two types of configuration• Programmatic (shown in example next)

• Configuration file

• Web.config (e.g. with IIS) or Machine.config

Page 13: Presentation 23: .NET Remoting Introduced

Deployment

• Server objects may be deployed as:• Windows Form application

• Windows Console application

• Windows Service

• Internet Information Server deployment

• no need for a server bootstrapping application

Page 14: Presentation 23: .NET Remoting Introduced

InterfaceDefinition

Design

Server StubGeneration

Client StubGeneration

ServerCoding

ClientCoding

ServerRegistration

Development Steps – Remoting vs. CORBA & Java RMI

Java RMI: rmicJava RMI: rmic

RMI: JAVARMI: JAVA

J2SE JDKJ2SE JDK

Start with Server Interface Coding: JAVA

Start with Server Interface Coding: JAVA

rmiregistryrmiregistry

CORBACORBA

CORBA: IDLCORBA: IDL

CORBA: IDLCORBA: IDL

ORBORB

RMI: JAVA interfaceRMI: JAVA interface

C++, Java …C++, Java …

C++, Java …C++, Java …

CLS InterfaceCLS Interface

Implicit stub gen.Implicit stub gen.

CLS (C# …)CLS (C# …)

CLS (C# …)CLS (C# …)

RemotingConfiguration

with CLR

RemotingConfiguration

with CLR

.NET Remoting

.NET Remoting

Page 15: Presentation 23: .NET Remoting Introduced

Making the HelloWorld App

• Using Microsoft Visual Studio .NET• may of course be done with .NET Framework alone

• Make Client & Server solutions• Server:

• IHelloWorld.cs interface• HelloWorld.cs class implementation• Server.cs class implementation for boot-strapping• Add Reference to assembly System.Runtime.Remoting

• Client• Must add IHelloWorld.cs• Client.cs class implementation• Add Reference to assembly System.Runtime.Remoting

Page 16: Presentation 23: .NET Remoting Introduced

The IHelloWorld Interface

using System;

namespace RemotingHelloServer{

// IHelloWorld is the interface for the HelloWorld server class.// It is the interface that is shared across the Internetpublic interface IHelloWorld{

string sayHello(string name); }

}

using System;

namespace RemotingHelloServer{

// IHelloWorld is the interface for the HelloWorld server class.// It is the interface that is shared across the Internetpublic interface IHelloWorld{

string sayHello(string name); }

}

The “IDL” of .NET Remoting – similar to Java RMI The “IDL” of .NET Remoting – similar to Java RMI

Page 17: Presentation 23: .NET Remoting Introduced

HelloWorld Implementation Code

using System;using System.Runtime.Remoting;

namespace RemotingHelloServer{

// HelloWorld is a server object that is available// "by-reference". It contains a constructor and a the// "sayHello" method taking a string parameter "name"public class HelloWorld : MarshalByRefObject, IHelloWorld{

private string greeting;

public HelloWorld(){

greeting = "OOMI Christsmas greetings from the server to: ";}

public string sayHello(string name) {

return (greeting + name);}

}}

using System;using System.Runtime.Remoting;

namespace RemotingHelloServer{

// HelloWorld is a server object that is available// "by-reference". It contains a constructor and a the// "sayHello" method taking a string parameter "name"public class HelloWorld : MarshalByRefObject, IHelloWorld{

private string greeting;

public HelloWorld(){

greeting = "OOMI Christsmas greetings from the server to: ";}

public string sayHello(string name) {

return (greeting + name);}

}}

Like in Java RMI (& CORBA) – we need to have an implementation of the interfaceLike in Java RMI (& CORBA) – we need to have an implementation of the interface

A remote object“by-reference” that

implements the IHelloWorld interface

A remote object“by-reference” that

implements the IHelloWorld interface

Implementing thesayHello methodImplementing thesayHello method

Page 18: Presentation 23: .NET Remoting Introduced

Server Code – Console Bootstrapping

using System;using System.Runtime.Remoting;using System.Runtime.Remoting.Channels;using System.Runtime.Remoting.Channels.Tcp;namespace RemotingHelloServer{

public class Server{

[STAThread]static void Main(string[] args){

//Create a TCP channelTcpChannel theChannel = new TcpChannel(8085)/* Register the channel so that clients can * connect to the server */ChannelServices.RegisterChannel(theChannel);

//Register the service on the channelRemotingConfiguration.ApplicationName = "HelloWorld App";RemotingConfiguration.RegisterWellKnownServiceType(

typeof(HelloWorld),"HelloWorld App",WellKnownObjectMode.SingleCall);

/*Start the server and keep it running so that clients * can connect to it. May be aborted by keypress */System.Console.WriteLine("Press Enter to end this server process");System.Console.Read();

}}

}

using System;using System.Runtime.Remoting;using System.Runtime.Remoting.Channels;using System.Runtime.Remoting.Channels.Tcp;namespace RemotingHelloServer{

public class Server{

[STAThread]static void Main(string[] args){

//Create a TCP channelTcpChannel theChannel = new TcpChannel(8085)/* Register the channel so that clients can * connect to the server */ChannelServices.RegisterChannel(theChannel);

//Register the service on the channelRemotingConfiguration.ApplicationName = "HelloWorld App";RemotingConfiguration.RegisterWellKnownServiceType(

typeof(HelloWorld),"HelloWorld App",WellKnownObjectMode.SingleCall);

/*Start the server and keep it running so that clients * can connect to it. May be aborted by keypress */System.Console.WriteLine("Press Enter to end this server process");System.Console.Read();

}}

}

Register the channelon port 8085

Register the channelon port 8085

Register theobject

Register theobject

Like in Java RMI (& CORBA) – we need some bootstrapping code – a server process Like in Java RMI (& CORBA) – we need some bootstrapping code – a server process

This may become a Windows NT service or a simple application, e.g. a console or Windows Form applicationThis may become a Windows NT service or a simple application, e.g. a console or Windows Form application

Page 19: Presentation 23: .NET Remoting Introduced

Client Code – Console Bootstrapping

… include all the Remoting stuffnamespace RemotingHelloClient{

public class Client{

[STAThread]static void Main(string[] args){

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

/* Activate the server object. Activation will bring * the server object to life, and create a proxy * stub class of the HelloWorld. In fact, as this is a * server-activated application, the call to the * server is NOT performed now, but instead waits until the * first request. It is thus the server who performs the * activation. This is the "Lazy-activation pattern" known * from e.g. CORBA */IHelloWorld helloWorld = (IHelloWorld) Activator.GetObject(

typeof(RemotingHelloServer.IHelloWorld),"tcp://localhost:8085/HelloWorld App");

System.Console.WriteLine("Please enter your name and press Enter");string name = System.Console.ReadLine();//Make the callstring greeting = helloWorld.sayHello(name);System.Console.WriteLine("We recieved from server: "+greeting);System.Console.WriteLine("Press Enter to end");System.Console.Read();

}}

}

… include all the Remoting stuffnamespace RemotingHelloClient{

public class Client{

[STAThread]static void Main(string[] args){

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

/* Activate the server object. Activation will bring * the server object to life, and create a proxy * stub class of the HelloWorld. In fact, as this is a * server-activated application, the call to the * server is NOT performed now, but instead waits until the * first request. It is thus the server who performs the * activation. This is the "Lazy-activation pattern" known * from e.g. CORBA */IHelloWorld helloWorld = (IHelloWorld) Activator.GetObject(

typeof(RemotingHelloServer.IHelloWorld),"tcp://localhost:8085/HelloWorld App");

System.Console.WriteLine("Please enter your name and press Enter");string name = System.Console.ReadLine();//Make the callstring greeting = helloWorld.sayHello(name);System.Console.WriteLine("We recieved from server: "+greeting);System.Console.WriteLine("Press Enter to end");System.Console.Read();

}}

}

Create ProxyCreate Proxy

Call via Proxy objectCall via Proxy object

Optional (may be done implicitly)Optional (may be done implicitly)

Page 20: Presentation 23: .NET Remoting Introduced

Configuration Strategi

• Alternative to Programmatic strategi:• Use a Server Configuration file (Listener.exe.config)

configuration> <system.runtime.remoting> <application> <service> <wellknown mode="Singleton" type="RemotableType, RemotableType" objectUri="RemotableType.rem" /> </service> <channels> <channel ref="http" port="8989"/> </channels> </application> </system.runtime.remoting></configuration>

Page 21: Presentation 23: .NET Remoting Introduced

Server Side Config Bootstrap

• Still need to implement: interface, MarshalByRef• But boostrapping is much simpler

using System;using System.Runtime.Remoting;

public class Listener{ public static void Main() { RemotingConfiguration.Configure("Listener.exe.config", false); Console.WriteLine("Listening for requests. Press enter to exit..."); Console.ReadLine(); } }

Page 22: Presentation 23: .NET Remoting Introduced

Client Configuration Strategi

• A Client Configuration file (Client.exe.config)

<configuration> <system.runtime.remoting> <application> <client> <wellknown type="RemotableType, RemotableType" url="http://localhost:8989/RemotableType.rem" /> </client> </application> </system.runtime.remoting></configuration>

Page 23: Presentation 23: .NET Remoting Introduced

Client Side Config Load + Proxy

• Still need to implement: interface, MarshalByRef• Generating dynamic proxy stub is simpler (VB.NET)

Imports SystemImports System.Runtime.Remoting

Public Shared Sub Main()

RemotingConfiguration.Configure(“Client.exe.config") Dim remoteObject As New RemotableType() Console.WriteLine(remoteObject.SayHello()) End Sub 'Main

Page 24: Presentation 23: .NET Remoting Introduced

Windows Communication Foundation (Kursorisk)

• Windows Vista => .NET Framework 3.0• Also for Windows XP and 2003 Server

• Unified Service-Oriented Programming Model

• Replaces / Suplements • .NET Remoting• DCOM• ASP.NET Web services• MSMQ (Queued Messaging) • .NET Enterprise Services

• Protocol Neutrality and Flexibility

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnlong/html/wcfroadmap.asp http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnlong/html/wcfarch.asp http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnlong/html/wcfroadmap.asp http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnlong/html/wcfarch.asp

Page 25: Presentation 23: .NET Remoting Introduced

Defining the Contract

using System.ServiceModel;

//a WCF contract defined using an interface[ServiceContract]public interface IMath{ [OperationContract] int Add(int x, int y);}

using System.ServiceModel;

//a WCF contract defined using an interface[ServiceContract]public interface IMath{ [OperationContract] int Add(int x, int y);}

//the service class implements the interfacepublic class MathService : IMath{ public int Add(int x, int y) { return x + y; }}

//the service class implements the interfacepublic class MathService : IMath{ public int Add(int x, int y) { return x + y; }}

Page 26: Presentation 23: .NET Remoting Introduced

Implementing the Servicepublic class WCFServiceApp{ public void DefineEndpointProgrammable() { //create a service host for MathService ServiceHost sh = new ServiceHost(typeof(MathService));

//use the AddEndpoint helper method to //create the ServiceEndpoint and add it //to the ServiceDescription sh.AddServiceEndpoint( typeof(IMath), //contract type new WSHttpBinding(), //one of the built-in bindings "http://localhost/MathService/Ep1"); //the endpoint's address

//create and open the service runtime sh.Open();

}

public void DefineEndpointInConfig() { //create a service host for MathService ServiceHost sh = new ServiceHost (typeof(MathService));

//create and open the service runtime sh.Open();

}}

public class WCFServiceApp{ public void DefineEndpointProgrammable() { //create a service host for MathService ServiceHost sh = new ServiceHost(typeof(MathService));

//use the AddEndpoint helper method to //create the ServiceEndpoint and add it //to the ServiceDescription sh.AddServiceEndpoint( typeof(IMath), //contract type new WSHttpBinding(), //one of the built-in bindings "http://localhost/MathService/Ep1"); //the endpoint's address

//create and open the service runtime sh.Open();

}

public void DefineEndpointInConfig() { //create a service host for MathService ServiceHost sh = new ServiceHost (typeof(MathService));

//create and open the service runtime sh.Open();

}}

Create the Service EndpointProgrammatically

Create the Service EndpointProgrammatically

Create the Service Endpoint

Using a ConfigurationFile (see next slide)

Create the Service Endpoint

Using a ConfigurationFile (see next slide)

Page 27: Presentation 23: .NET Remoting Introduced

Configuration File

<!-- configuration file used by above code --><configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <system.serviceModel> <services> <!-- service element references the service type --> <service type="MathService"> <!-- endpoint element defines the ABC's of the endpoint --> <endpoint address="http://localhost/MathService/Ep1" binding="wsHttpBinding" contract="IMath"/> </service> </services> </system.serviceModel></configuration>

<!-- configuration file used by above code --><configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <system.serviceModel> <services> <!-- service element references the service type --> <service type="MathService"> <!-- endpoint element defines the ABC's of the endpoint --> <endpoint address="http://localhost/MathService/Ep1" binding="wsHttpBinding" contract="IMath"/> </service> </services> </system.serviceModel></configuration>

Page 28: Presentation 23: .NET Remoting Introduced

Implementing the Client Using Static Proxy

//this class is generated by svcutil.exe//from the service's metadata//generated config is not shown herepublic class MathProxy : IMath{ ...}

public class WCFClientApp{ public void SendMessageToEndpoint() { //this uses a proxy class that was //created by svcutil.exe from the service's metadata MathProxy proxy = new MathProxy();

int result = proxy.Add(35, 7); }

//this class is generated by svcutil.exe//from the service's metadata//generated config is not shown herepublic class MathProxy : IMath{ ...}

public class WCFClientApp{ public void SendMessageToEndpoint() { //this uses a proxy class that was //created by svcutil.exe from the service's metadata MathProxy proxy = new MathProxy();

int result = proxy.Add(35, 7); }

Page 29: Presentation 23: .NET Remoting Introduced

Implementing the Client Using Dynamic Proxy

public class WCFClientApp{

public void SendMessageToEndpointUsingChannel() { //this uses ChannelFactory to create the channel //you must specify the address, the binding and //the contract type (IMath) ChannelFactory<IMath> factory=new ChannelFactory<IMath>( new WSHttpBinding(), new EndpointAddress("http://localhost/MathService/Ep1")); IMath channel=factory.CreateChannel(); int result=channel.Add(35,7); factory.Close();

}

public class WCFClientApp{

public void SendMessageToEndpointUsingChannel() { //this uses ChannelFactory to create the channel //you must specify the address, the binding and //the contract type (IMath) ChannelFactory<IMath> factory=new ChannelFactory<IMath>( new WSHttpBinding(), new EndpointAddress("http://localhost/MathService/Ep1")); IMath channel=factory.CreateChannel(); int result=channel.Add(35,7); factory.Close();

}

Page 30: Presentation 23: .NET Remoting Introduced

Plenum Discussion

• Use 5 minutes in your groups:• Differences with Web services / Java RMI / CORBA?

• Strength over Web services / Java RMI / CORBA?

• Weaknesses compared to –”-?

• Plenum: 5 minutes discussion of findings

Page 31: Presentation 23: .NET Remoting Introduced

Alignment med læringsmål

Når kurset er færdigt forventes den studerende at kunne:• redegøre for de grundlæggende principper og teknikker omkring

interproceskommunikation over såvel lokalnetværk som Internettet• redegøre for teknikker for distribuerede objektorienterede løsninger,

herunder serialisering, marshalling, stub/skeleton, proxy, brug af forskellige Interface Definition Language sprog som udviklingskontrakt

• redegøre for principperne omkring transparens og heterogenitet (platforms og programmeringssprogs uafhængighed)

• redegøre for anvendelsen af Java RMI, XML/SOAP (Webservices), herunder forskelle/ligheder, fordele/ulemper teknologierne imellem. Samt på overordnet niveau have kendskab til forskelle og ligheder med CORBA og .NET Remoting teknologierne

• anvende socket programmering til at lave et mindre distribueret system baseret på objektorienterede principper

• anvende objektorienterede teknikker og arkitekturer til at designe og programmere netværksforbindelser ved brug af middleware, og bevise dette ved at konstruere og dokumentere to distribuerede systemer der gør brug af ovenstående teknologier

Hvornår vælgehvilken teknolog,der skal vælges

Forstå at .NET Remotingkan bruges binært+SOAP, ingen IDL, er semi-heterogenthar en ”pæn” objekt struktur. Også bruger stubs.Kunne genkende på koden at det er .NET Remoting. Men ikke forstå koden i detaljer