context and remoting module subtitle building distributed applications and implementing...

54
Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft .NET

Upload: juniper-austin

Post on 17-Dec-2015

225 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Context and Remoting

Module SubtitleBuilding distributed applications and

implementing attribute-driven behaviors with Microsoft .NET

Page 2: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Objectives

Introduction to the .NET Remoting core infrastructure

Explore the extensibility mechanisms Available on the transport level Available through the Remoting Context

Page 3: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Contents

Section 1: Overview

Section 2: Remoting Architecture

Section 3: Context and Interception

Section 4: Serving and Accessing Objects

Summary

Page 4: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Section 1: Overview

Looking back: Remoting in COM(+)

What's wrong with that?

.NET Remoting Core Concepts

Page 5: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Looking Back: Remoting in COM(+)

All Objects implement IUnknown interface Dynamic exploration of object features Lifecycle control with reference counting

DCOM: Object-RPC based on DCE Wire Format

Marshaling through MIDL generated Proxies/Stubs Automation: Dynamic binding through IDispatch

Servers locally advertised in Registry

Activation "on-demand" Servers launched at client request Objects created through class factories

Page 6: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

What’s wrong with that?

DCOM protocol is binary and complex

Reference counting difficult to master Common source of memory leaks for servers Distributed operation require "pinging" clients

Marshaling is non-extensible

Registry is difficult to manage; registration clumsy

Activation paradigm has component bias Difficult to locate and connect active servers

Connection oriented protocol Does not work well on the Internet

Page 7: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

WebServiceProviders

Trading Partners

.NETBuilding Block

Services (“Hailstorm“)

.NET Remoting Core ConceptsThe Federated Services Model

Financial

News

B2B

.NETEnterprise

Servers

BizTalkMessaging

SQL ServerXML

ExchangeWebStorage

Open Standards:

TCP/IPXML

HTTPSMTPSOAP

Enterprise Applications

Accounting Organisation

Sales Procurement

Knowledge Management

Website

XML

EDIFACT

X12

Page 8: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

MessageQueue

Messages – RPC is not all

Application

Application

Application

Application

bidirectionalmethod call

unidirectionalmethod call

queuedmessage exchange

bidirectionalmessage exchange

Page 9: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Application Domains

Isolated execution space for applications

Independent of OS concept of thread, process

Process Process

AppDomain AppDomainAppDomain

Object Object

ObjectObjectObject

Page 10: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

The Remoting Context Derived from COM+ context idea

But: Remoting Context != COM+ Context

Encloses objects with same functional context

Carries shared properties that describe behavior

RqTx Sync Thrd

remoting boundary

Object

ObjectObject

AppDomain

Context Context

Object Object

Object Object

Page 11: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

What is “Remote”, What is” Local”?

"Local" are all objects within the same AppDomain

All other objects are "Remote" Even objects in the same process!

Context-bound objects: "Local" if they share the same context "Remote" if they are in different contexts

"Local": Not marshaled, immediate object calls

"Remote": Marshaled, calls through proxies

Page 12: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Section 2: Remoting Architecture

What: Messages

Where: Channels

How: Formatters

Marshaling Concepts

Proxies

Page 13: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

What to communicate: Messages

Messages are objects that implement IMessage

IMessage: Simple dictionary of key/values pairs

.NET Message Types: Construction call messages, response messages Method call messages, response messages

Invocation Styles Synchronous: Request with immediate response Asynchronous: Request with delayed or no response

Page 14: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Server

Where to communicate: Channels Channels transport messages

Built-in channels: TCP, HTTP

Establish endpoint-to-endpoint communication

Channels can listen for and send messages Listen: IChannelReceiver, Send: IChannelSender

Makes no assumptions about endpoint architecture

Can implement channel sinks for logging, interception

Client

Channel"Proxy"

Dis-patcher

Page 15: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

How to communicate: Formatters Formatters serialize .NET objects into wire formats

Used dynamically by channel architecture Configuration-file based association with channels Formatters are implemented as channel sinks

Built-in: SOAP and Binary Formatters System.Runtime.Remoting.Serialization.Formatters

Channel

encode into wire format

decode from wire format

SOAP, Binary, Custom

Page 16: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Selecting Channels: TcpChannel

System.Runtime.Remoting.Channels.Tcp

Uses plain TCP sockets

Transmits compact, binary wire format By default, serialized by the BinaryFormatter .NET native wire-format Fast

Can use custom formatters for other wire-formats

Best choice for LAN communication Uses permanent socket connection

Not recommended for Internet communication

Page 17: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Selecting Channels: HttpChannel

System.Runtime.Remoting.Channels.Http

Uses HTTP 1.1 protocol

Transmits SOAP 1.1 XML format Serialized by SoapFormatter Open standard Basis for W3C SOAP/XMLP Protocol activity

Can use custom formatters for other wire-formats

Best choice for Internet communication Stateless protocol, scales well

Best choice for interoperability and integration

Page 18: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Selecting Channels: Custom

Bring your own Protocol (APPC,IPX,Pipes, ...)

Transmit any format that fits Can use SoapFormatter or BinaryFormatter Or bring your own formatter: IIOP, RMI, ORPC, ...

Applies to integration scenarios

Page 19: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

The Message Box: IMessageSink Message Sinks are the .NET message drop-off

Implemented by channels to accept messages

Implemented by context properties for interception

Allows building chains of sinks Simple linked list through NextSink property Messages can be intercepted, modified or

processed anywhere in the chain

Client

Channel

"Proxy" IMessageSink

SynchProcessMessage()or AsynchProcessMessage()

Page 20: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Objects To Go: Marshaling

Definition: Packaging Data for Transfer

For objects passed as arguments, return values

Marshal-By-Value Entire object is packaged as-is Copy is transferred to destination No link between copy and original

Marshal-By-Reference Just a reference to an object is packaged Reference is transferred to destination "Proxy" object links destination with original

Page 21: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Concepts: Agile and Contextful

Agile Objects Independent of Context Called directly from any AppDomain or Context Do not use channels Unbound Classes:

Travel between AppDomains, marshal-by-value

AppDomain-Bound Classes: Reside in a single AppDomain, marshal-by-reference

Contextful Objects Bound to AppDomain and Context Marshal-by-reference outside of context

Page 22: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Objects calling Objects: Proxies

"Proxy" Definition Object that acts locally on behalf of a remote object Looks like and accepts calls as if it were "real" Forwards them to the remote object

Real Proxies Inherit System.Runtime.Remoting.RealProxy Are the communication layer for transparent proxies

Transparent Proxies Built dynamically through RealProxy Exact pass-through mirror of the remote object

Page 23: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Client Server

Proxies illustrated

Channel

"Proxy" IMessageSink

Transparent Proxy

MethodA()

MethodB()

PropertyQ

PropertyP

FieldX

FieldY

RealProxy

builds

Invoke()

SyncProcessMessage()

Page 24: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

The Dispatcher

Simplified model: Located at the channel endpoint Receives messages Builds stack-frame from message content Invokes actual method on object Collects result and creates response message

Page 25: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Server

Dispatcher

The Dispatcher illustratedClient

Channel

Object

MethodA()

MethodB()

PropertyQ

PropertyP

FieldX

FieldY

StackBuilderSink

SyncDispatchMessage()

actual method calls

Page 26: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Channel Sinks

Formatter, dispatcher and transport are in sinks

All channel sinks are linked in chains

Client Server

StackBuilderSink

Server Object

Formatter Sink

Custom SinksCustom SinksCustom Sinks

Transport Sink

Proxy

Client Object

Formatter Sink

Custom SinksCustom SinksCustom Sinks

Transport Sink

Page 27: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Some Advanced Topics

Declaring Methods "One-Way" Use the "oneway" attribute:

[oneway] void FireAndForget();

The Call Context Property bag passed with every IMessage Dictionary entry "__CallContext", class CallContext Allows to pass processing information along

Page 28: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Section 3: Contexts and Interception

Context Rules and Concepts

Context Attributes and Properties

Context Characteristics

Interception: Context and Message Chains

Standard Context Attributes

Custom Context Attributes

Page 29: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Context Rules and Concepts

Contexts enclose "contextful" objects Classes derived from System.ContextBoundObject Behavior for class declared using context attributes

Common context boundary is shared when Objects have identical attributes or Context attributes actively agree to deviations

All objects in other contexts are "remote" Conceptually similar to AppDomain boundary

Messages crossing boundary may be intercepted Chains of IMessageSinks allows hooks at any stage

Page 30: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Context Attributes and Properties

Property

Object

Context-Bound Class

System.ContextBoundObject

Attribute

create object

IsContextOK() ?1

No! GetPropertiesForNewContext() !

23

newYes! Use existing context.

No! Create new context.

Page 31: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Interception: Message Chains Every message passes a four chains of sinks

Context properties contribute these sinks

Custom attributes allow intercepting all traffic

ServerClient

Server Envoy Chain

Client Context Chain

Server Context Chain

ServerObject Chain

Channel

Page 32: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Chain Hooks: Message Sinks

Server Object Sink Installed to intercept messages per-object Allows to modify object behavior on message level

Server Context Sink, Client Context Sink Installed to intercept messages per-context Allows to see, modify and possibly block all traffic

Server Envoy Sink Installed by the server on the client side (!) Allows to pre-scan messages before transmission

e.g. parameter validation

e.g. queuing of multiple calls for optimization

Page 33: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Attribute Driven Behaviour

Sample Context Attribute: CallTraceAttribute Intercepts all calls crossing the context boundary Writes methods and arguments to log file

How to establish interception? Property implements IContributeServerContextSink GetObjectSink() returns new IMessageSink

ServerServer

Context Chain

Context Property

Property contributes sink for server context

chain

Page 34: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Standard Context Attributes

[Synchronization()] Attribute Synchronized (serial) calls into context only Calls are queued at context boundary Allows to mimic the COM+ Apartment Model

COM+ Context Relationship COM+ Context is a different boundary May or may not overlap with remoting context No relationship whatsoever Belongs to COM/Interop Services domain

Page 35: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Context Characteristics

Context Local Store Allows any data to be associated with the context Context.SetData(), Context.GetData()

Context Statics [ContextStatic] static int q = 4;

Static (class) member with per-context scope

Access to the current context via Thread class Thread.GetCurrentContext()

Page 36: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Section 4: Serving & Accessing Objects

Remoting Services

Exposing Well-Known Objects

Exposing Classes for Client-Side Activation

Configuring Remoting and Registering Channels

Activation and Access

Page 37: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Remoting Services

System.Runtime.Remoting.RemotingServices class Provides fundamental remoting infrastructure

Connecting to remote object instances Object marshaling

System.Runtime.Remoting.RemotingConfiguration Provides infrastructure for Remoting configuration

System.Runtime.Remoting.ChannelServices Channel registration and management

System.Runtime.Remoting.LifetimeServices Lease-based lifecycle management for objects

System.Runtime.Remoting.TrackingServices Universal hooks for tracking remoting activities

Page 38: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Exposing Well-Known Objects

.NET's activation model is very unlike COM's .NET rather resembles CORBA model (!)

If there is no actively listening endpoint: no connection

No surrogates, no registry, no location transparency

EXE servers are not remotely activated

Simplifies Remoting greatly

Expose well-known object for clients to connect. Bound to known channels with known name Does not use static registration, prog-ids or class-id

Can expose "single call" or "singleton" objects

Page 39: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Single Call and Singletons

"Single Call" Objects Object instance is created for each call on channel Implements the stateless model of the web

"Singleton" Objects One shared instance provided for all clients Serves as "gateway" into stateful application Object is created at registration time

RemotingConfiguration. RegisterWellKnownServiceType

WellKnownObjectMode.SingleCall WellKnownObjectMode.Singleton

Page 40: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Server Setup Example

Channels and Objects are AppDomain-Global

Registers the single-call endpoint:http://myserver:8080/MyEndpointURI

Channel registration

Object registration

...

HttpChannel chan = new HttpChannel(8080);ChannelServices.RegisterChannel(chan);

RemotingConfiguration. RegisterWellKnownServiceType( typeof(ServerClass), "MyEndpointURI", WellKnownObjectMode.SingleCall);

Page 41: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Client-Side Activation

Client-Side Activation similar to COM Client requests creation of remote object Core difference: Server must be running

Server Side Implementation: Class registered with RemotingConfiguration class

RemotingConfiguration.RegisterActivatedServiceType()

Runtime creates objects on client request

Client Side Implementation: Object created through Activator class Alternatively: Configuration and language binding

Allows creating remote objects using "new"

Page 42: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Object Activation and Connection

The Activator (System.Activator) Creates or connects local and remote objects Activator.CreateInstance()

Creates client activated objects

Activator.GetObject Connects to well-known objects

RemotingServices Connect – lower level connect to remote object

Relationship: Activator uses RemotingServices

Page 43: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

o = Activator.GetObject("http://...")o.methodCall();

Activation illustrated

AppDomain

Context

Object Object

Object Object

TCP8501

HTTP8080

Identity Table

uriA uriB uriC uriD

tcp://server:8501/uriDhttp://server:8080/uriB

RemotingServices.Connect()

Activator.GetObject()

Languagebinding

o = new myClass();o.methodCall();

Page 44: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Configuring Remoting

Remoting Configuration Architecture enables: Definition of endpoints at installation time Well-known ports, full control for administrators Application component distribution by configuration

Configuration can define which classes are remote or local

Configuration is file-based Integrated with .NET configuration infrastructure However: Must explicitly load

RemotingConfiguration.Configure(“filename“)

Hides most details of Remoting shown here

Page 45: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Server System Configuration

<configuration> <system.runtime.remoting> <channels> <channel id="http“ type="System.Runtime.Remoting.Channels.Http.HttpChannel, System.Runtime.Remoting" /> </channels> <channelSinkProviders> <serverProviders> <formatter id="soap“ type="System.Runtime.Remoting.Channels. SoapServerFormatterSinkProvider, System.Runtime.Remoting" /> </serverProviders> </channelSinkProviders> </system.runtime.remoting></configuration>

Declare channel

Specify formatter

Page 46: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Server Application Configuration<configuration> <system.runtime.remoting> <application name="MyFoo"> <service> <wellknown type="Foo, common“ objectUri="Foo.soap“ mode="Singleton" /> </service> <channels> <channel ref="http“ name="MyHttpChannel" port="9000"> <serverProviders> <formatter ref="soap" /> </serverProviders> </channel> </channels> </application> </system.runtime.remoting></configuration>

Associate channel with application

Declare singleton service endpoint

Associate formatter with channel

Page 47: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Section 5: Putting It Together

Variations of Objects

Context Attributes and Interception

Page 48: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Variations of Objects 1/2

Agile (never marshaled)public class MySimpleObject{ public MySimpleObject() { }}

Agile (marshal-by-value)[serializable]public class MySimpleObject{ public MySimpleObject() { }}

Page 49: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Variations of Objects 2/2

Agile (marshal-by-ref, AppDomain-bound) public class MySimpleObject : MarshalByRefObject{ public MySimpleObject() { }}

Context-bound (marshal-by-ref) [CallTrace()]public class MySimpleObject : ContextBoundObject{ public MySimpleObject() { }}

Page 50: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Context Attributes & Interception 1/3

A Simple Context Attribute

false forces new

context

install property

public class CallTraceAttribute : ContextAttribute{ public CallTraceAttribute(): base("CallTraceAttribute") { } public override bool IsContextOK( Context ctx, IConstructionCallMessage ctorMsg) { return false; } public override void GetPropertiesForNewContext( IConstructionCallMessage ctorMsg) { CallTraceProperty prop = new CallTraceProperty(); ctorMsg.ContextProperties.Add(prop); } }

Page 51: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Installs sink on runtime request.

Context Attributes & Interception 2/3

A Simple Context Property

public class CallTraceProperty : IContextProperty, IContributeServerContextSink { public String Name { get { return "CallTraceProperty"; } }

public virtual bool IsNewContextOK(Context newCtx) { return true; } public virtual void Freeze(Context newContext) { }

public IMessageSink GetServerContextSink(IMessageSink next) { return new CallTraceObjectSink(this, next); } }

Installed props check

context

Page 52: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Context Attributes & Interception 3/3

A Simple Message Sinkpublic class CallTraceObjectSink : IMessageSink{ private IMessageSink _nextSink; public CallTraceObjectSink(CallTraceProperty prop, IMessageSink nextSink) { _nextSink = nextSink; }

public IMessage SyncProcessMessage(IMessage reqMsg){ foreach( object o in reqMsg.Properties) { Console.WriteLine(o); } return _nextSink.SyncProcessMessage(reqMsg);

}

public IMessageCtrl AsyncProcessMessage(IMessage reqMsg, IMessageSink reply){ foreach( object o in reqMsg.Properties){ Console.WriteLine(o); } return _nextSink.AsyncProcessMessage(reqMsg, reply); }

public IMessageSink NextSink { get {return _nextSink; } }}

Dumps content of IMessage for each

call

Next sink receives control

thereafter

Page 53: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Summary

.NET Remoting is open-standards based ... supporting SOAP, XML and HTTP

The infrastructure is extensible at every level ... and useable on every level

.NET Remoting Contexts build on the COM+ idea ... but make contexts available for your extensions

Attribute driven behaviors can be built on Contexts ... to separate plumbing from business code

.NET Remoting is configurable at installation time ... and on an application level

Page 54: Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET

Questions?