.NET Framework Advanced Topics Name Title Department Company.

Slides:



Advertisements
Similar presentations
Web Service Ahmed Gamal Ahmed Nile University Bioinformatics Group
Advertisements

SOAP.
SOAP Quang Vinh Pham Simon De Baets Université Libre de Bruxelles1.
.NET Remoting in Delphi and C# Alain “Lino” Tadros President & CEO Falafel Software Inc. ComponentScience Inc. BORCON 2004.
.Net Remoting Pooja Panjala 06/17/10. Agenda What is.net Remoting? Explanation of terms Architecture Implementation of Remoting Sample example.net Security.
C# and Windows Programming Application Domains and Remoting.
.NET REMOTING CertSIG Tom Perkins. FUNDAMENTALS Distributed Applications Process A Process B Process C Objects can communicate across process boundaries.
.NET Remoting. .Net Remoting Replaces DCOM (Distributed Component Object Model – a proprietary Microsoft technology for communication among software components.
CORBA - Common Object Request Broker Architecture.
Windows Communication Foundation and Web Services.
Notes to the presenter. I would like to thank Jim Waldo, Jon Bostrom, and Dennis Govoni. They helped me put this presentation together for the field.
1 Advanced Programming Topics - II Objectives:  Background  Remoting  Types of remoting  Marshalling  Farmatters  Channels.
Remote Method Invocation Chin-Chih Chang. Java Remote Object Invocation In Java, the object is serialized before being passed as a parameter to an RMI.
Distributed Systems Tutorial 2 -.NET Remoting. 2 What is Remoting?  Remoting allows you to pass objects or values across servers in different domains.
Communication in Distributed Systems –Part 2
ASP.NET Programming with C# and SQL Server First Edition
Chapter 11 ASP.NET JavaScript, Third Edition. 2 Objectives Learn about client/server architecture Study server-side scripting Create ASP.NET applications.
Distributed Systems Tutorial 3 -.NET Remoting – Crossing Application Boundaries.
Intro to dot Net Dr. John Abraham UTPA – Fall 09 CSCI 3327.
Windows Programming Using C# Windows Services, Serialization, and Isolated Storage.
.NET, and Service Gateways Group members: Andre Tran, Priyanka Gangishetty, Irena Mao, Wileen Chiu.
A Free sample background from © 2001 By Default!Slide 1.NET Overview BY: Pinkesh Desai.
Programming Languages and Paradigms Object-Oriented Programming.
.NET Remoting Architecture. Slide 2 CITE 4420.NET Remoting Topics Remoting Boundaries Crossing the Boundaries Distributed Applications Marshalling Channels.
1 3. Implementing Web Services 1.Create SOAP proxy interfaces and WSDL based service descriptions 2.Register/publish services 3.Stores service descriptions.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Kalpesh Padia Reflection in.Net. OVERVIEW 9/19/
Reflection in.Net Siun-Wai Seow. Objective Explain.NET Reflection When to use it? How to use it? Topic is in the final exam.
EJB Framework.  As we know, EJB is the center of the J2EE architecture that provides a sturdy framework for building enterprise applications. The major.
Distributed Communication via ASP.Net Web Services and.Net Remoting By Richard King.
Serialization  What is Serialization?  System.Serialization  Scenarios in Serialization  Basic Serialization  Custom Serialization.
CS 390- Unix Programming Environment CS 390 Unix Programming Environment Topics to be covered: Distributed Computing Fundamentals.
Lecture 15 Introduction to Web Services Web Service Applications.
11 Web Services. 22 Objectives You will be able to Say what a web service is. Write and deploy a simple web service. Test a simple web service. Write.
Information Management NTU Interprocess Communication and Middleware.
All types in the CLR are self-describing – CLR provides a reader and writer for type definitions System.Reflection & System.Reflection.emit – You can ‘read’
Reflection Leveraging the Power of Metadata. Objectives Provide an introduction to.NET Reflection Explain how applications can use Reflection to explore.
ABHISHEK BISWAS.NET Reflection Dynamically Create, Find and Invoke Types.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 RMI.
Copyright © 2003, developerLabs Extending.NET Distributed Applications Stephen Fulcher developerLabs.
Serialization What is Serialization Serialization is the process of converting an object, or a connected graph of objects, stored within computer memory,
Java Remote Method Invocation RMI. Idea If objects communicate with each other on one JVM why not do the same on several JVM’s? If objects communicate.
RMI Remote Method Invocation Distributed Object-based System and RPC Together 2-Jun-16.
 Remote Method Invocation  A true distributed computing application interface for Java, written to provide easy access to objects existing on remote.
Enterprise Integration Patterns CS3300 Fall 2015.
Hwajung Lee.  Interprocess Communication (IPC) is at the heart of distributed computing.  Processes and Threads  Process is the execution of a program.
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
Context and Remoting Module Subtitle Building distributed applications and implementing attribute-driven behaviors with Microsoft.NET.
ASP.NET Web Services.  A unit of managed code installed under IIS that can be remotely invoked using HTTP.
Object Oriented Software Development 4. C# data types, objects and references.
Lecture 4 Mechanisms & Kernel for NOSs. Mechanisms for Network Operating Systems  Network operating systems provide three basic mechanisms that support.
.NET Mobile Application Development XML Web Services.
.Net Reflection Taipan Tamsare. Overview Reflection core concepts Exploring metadata Detail information Attributes Building Types at runtime.
Exploring Networked Data and Data Stores Lesson 3.
METADATA IN.NET Presented By Sukumar Manduva. INTRODUCTION  What is Metadata ? Metadata is a binary information which contains the complete description.
.NET Remoting. Remoting Introduction The process of programs or components interacting across certain boundaries either different processes or machines.
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
Windows Communication Foundation and Web Services
Presented by: Ramaswamy Krishnan-Chittur
.NET Remoting Priyanka Bharatula.
Using Application Domains Effectively
Presentation 23 .NET Remoting Introduced
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
Presented by: Ramaswamy Krishnan-Chittur
Windows Communication Foundation and Web Services
Programming Models for Distributed Application
Lecture 4: RPC Remote Procedure Call Coulouris et al: Chapter 5
Lecture 4: RPC Remote Procedure Call CDK: Chapter 5
WEB SERVICES From Chapter 19, Distributed Systems
Distributed System using Web Services
Presentation transcript:

.NET Framework Advanced Topics Name Title Department Company

Prerequisites  This module assumes that you understand the fundamentals of: Programming Variables, statements, functions, loops, etc. Object-oriented programming Classes, inheritance, polymorphism, members, etc. C#.NET Framework Class Library

Learning Objective  Provide an overview on several advanced.NET Framework topics

Agenda  Reflection  Remoting  Serialization

Reflection  Looking back: Automation and COM type information  Reflection core concepts  Exploring metadata  Detail information  Attributes  Putting it together

Reflection Looking Back: Automation  TypeLibraries contain type information Exploration through ITypeLib/ITypeInfo  Attributes describe behavior of elements For example, directionality of parameters For example, method role (instance method, property)  Dynamic Invocation using IDispatch  Type system supports most popular simple types  Dynamic types using VARIANT  Arrays passed using SAFEARRAY  Strings expressed as BSTR

Reflection Core Concepts  Metadata Single location for type information and code Code is literally contained within type information Every.NET object can be queried for its type Type metadata can be explored with Reflection  Dynamic Type System Highly dynamic and language independent Types may be extended and built at run time Allows on-the-fly creation of assemblies.NET Compilers use.NET to emit.NET code

Reflection Exploring Metadata [serializable] public class Person : { public event OnSaveChange onsv; public Date DOB; public string FirstName; public string LastName; public string Name { get { return FirstName + " " + LastName; } } public void Person(string First,string Last) { FirstName=First;LastName=Last; } public bool Save() { System.Type t = this.GetType() ; foreach( FieldInfo f in t.GetFields() ) {... } } System.Type Attributes Fields Properties Constructors Methods Events Parameters

Reflection MetaData Samples // Test sample class public class Test { private int n; public Test(int a) { n=a;}... } //Retrieve the Type object public static int Main(string[] args) { Type type1 = typeof(Test); Test t1 = new Test(0); Type type2 = t1.GetType(); Console.WriteLine(“type of t1 is (0)”, type2); return 0 }

Reflection System.Type  Provides access to metadata for any.NET type  Returned by System.Object.GetType()  Allows drilling down into all facets of a type Category: Simple, Enum, Struct or Class Methods and Constructors, Parameters and Return Fields and Properties, Arguments and Attributes Events, Delegates, and Namespaces

Reflection Type and Instances  Type Safety First! Type checking at run time C#: if (o is Customer) { … } VB: If TypeOf o Is Customer Then … End If  Dynamic Invocation through Reflection Support for late binding: MethodInfo.Invoke() FieldInfo.SetValue()

Reflection GetMethods Example //Get a list of methods supported by a class public static int Main(string[] args) { Type type1 = typeof(Test); MethodInfo[] minf = type1.GetMethods(); foreach (MethodInfo m in minf) //Print out the method name and whether it is public Console.WriteLine(“Name: “+ m.Name + “,” + ((m.IsPublic) ? “ public” “ “”) + ((m.IsVirtual) ? “virtual” : “”); //Get the list of paramerters ParamerterInfo[] pi = m.GetParameters(); foreach (ParameterInfo p in pi) Console.WriteLine(“ “ + p.ParameterType + “ “ + p.Name); return 0 }

Reflection MemberInfo  Base class for all "member" element descriptions Fields, Properties, Methods, etc.  Provides member kind, name, and declaring class MemberInfo MethodBaseParameterInfoFieldInfoEventInfoPropertyInfo MethodInfoConstructorInfo

Reflection Dynamic Creation Example public static int Main(string[] args) { Type type1 = typeof(Test); //Instantiate the Test Object object[] ctorParams = new object[] (1); object obj = Adtivator.CreateInstance(type1, ctorParams); //Invoke a method object[] ctorParams = new object[] (3); int res = (int)type1.InvokeMember(“Amethod”, BindingFlags.Default|BindingFlags.InvokeMethod, null, obj.methodParams); return 0 }

Reflection Attributes  Custom attributes are the killer-app for Reflection!  Attributes enable declarative behavior  Attributes allow data augmentation

Reflection Attributes [dbcolumn("Address1")] string Street; [dbcolumn("Postcode")] string ZIP; [serializable] class Person {... Map fields to database columns with FieldInfo.GetCustomAttributes() Mark class as serializable Type.GetCustomAttributes()

Reflection The Bigger Picture  Types know their module; modules know their types  Modules know their assembly and vice versa  Code can browse and search its entire context Assembly Module Class Struct Constructor Method Field Class Interface Class Delegate Class Interface

Reflection Introducing System.Reflection.Emit  Full representation of physical structure  Allows building modules and assemblies at run time Transient code only used at run time Persistent code for reuse  Create classes and types, and emit IL  Used by.NET compilers to build.NET apps

Component Class Description DefaultValue Help Localizable ReadOnly ComponentModel Attributes Toolbox Properties Window Designers Help Reflection Visual Studio.NET and Reflection

Reflection ASP.NET and Reflection ASP.NET compiler Reflection Page Assembly IIS ASP.NET runtime 1 2 2a 3 File exists? Assembly exists, same time stamp? No? Compile Run class pg : Page {... }

Reflection Summary  Reflection = System.Type + GetType()  Explore type information at runtime  Enables attribute-driven programming  Use Emit classes to produce.NET assemblies  Bottom line: Fully self-contained structural model

Agenda  Reflection .NET Remoting  Serialization

.NET Remoting  Overview  Remoting architecture  Context and interception  Serving and accessing objects  Putting it together

.NET Remoting 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

.NET Remoting Scenarios  Web Services Anywhere Expose Web Service endpoints from any process over any transport (pluggable channels) using any payload encoding (pluggable serialization formatters SOAP and Binary provided in the box) SOAP=HTTP+XML

.NET Remoting Scenarios  CLR Object Remoting Built on top of Web Services Anywhere Full Common Language Runtime type system fidelity Marshal by Value (make a copy) and Marshal by Ref (pass an ObjRef) objects between Web Services over the wire using any of the pluggable channels. Distributed Identity, Activation, Lease-based Lifetime and CallContext A TCP Channel (using sockets) with a Binary Encoding is provided

WebService Providers Trading Partners.NET Building Block Services.NET Remoting Core Concepts: Federated Service Model Financial News B2B.NET Enterprise Servers SQL Server XML BizTalk Messaging Open Standards: TCP/IP XML HTTP SMTP SOAP Enterprise Applications Accounting Organization Sales Procurement Knowledge Management Website XML EDIFACT X12 Exchange WebStorage

.NET Remoting Application Domains  Isolated execution space for applications  Independent of O/S concept of thread, process Process AppDomain Object

.NET Remoting Remoting Context  Derived from COM+ context idea  But: Remoting Context != COM+ Context  Encloses objects with same functional context  Carries shared properties that describe behavior RqTxSyncThrd Remoting boundary Object AppDomain Context Object

.NET Remoting “Remote” vs. ”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

.NET Remoting Building a Remote Application Example  Writing a well-known Web service using System; namespace HelloService { // Well Known WebService object public class Hello : MarshalByRefObject { // Return the name prefixed with a string public String HelloMethod(String name) { Console.WriteLine("Hello.HelloMethod : {0}" +, name); return "Hi there " + name; }

.NET Remoting Hosting Example Remoting.cfg for the HelloService Name#HelloService WellKnownObject#HelloService.Hello#HelloService#HelloService /Hello.soap#SingleCall  ASP.NET hosting example Creating an IIS root that points to the app directory Adding a "Remoting.cfg" configuration file

NET Remoting Hosting Example  MyHost (a managed console app) example Name#HelloService WellKnownObject#HelloService.Hello#HelloService#HelloS ervice/Hello.soap#SingleCallChannel#System.Runtime.R emoting#System.Runtime.Remoting.Channels.HTTP.HTTPCh annel#ports=8085

.NET Remoting Using Configuration and New Example using System; using System.Runtime.Remoting; using HelloService; public class SimpleHello { public static void Main(String[] args) { String name = "Bill"; RemotingServices.ConfigureRemoting("MyHello.cfg"); Hello hello = new Hello(); String result = hello.HelloMethod(name); Console.WriteLine("Hello.HelloMethod returned: " + result); } Contents of MyHello.cfg Name#MyHello Assembly#HelloService#HelloService#Hello= host:80/HelloService/Hello.soap RemoteApplication#HelloService# lloService Channel#System.Runtime.Remoting#System.Runtime.Remo ting.Channels.HTTP

.NET Remoting Architecture  What: Messages  Where: Channels  How: Formatters  Marshaling Concepts  Proxies

.NET Remoting 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

Server.NET Remoting Where to Communicate: Channels  Channels transport messages.NET built-in channels: TCP, HTTP, SMTP  Establish endpoint-to-endpoint communication  Channels can listen for and send messages Listener implements IChannelReceiver Sender implements: IChannelSender  Makes no assumptions about endpoint architecture Client Channel "Proxy"Dispatcher

.NET Remoting How to Communicate: Formatters  Formatters serialize.NET objects into wire formats  Used dynamically by channel architecture Selection based on MIME type. Register globally: CoreChannel.RegisterChannel()  Built-in: SOAP and Binary Formatter  Custom Formatters allow talking to any endpoint Channel Encode into wire format Decode from wire format SOAP, Binary, Custom

.NET Remoting 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

.NET Remoting 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

.NET Remoting 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 by real proxy Exact pass-through mirror of the remote object

ClientServer.NET Remoting Proxies Illustrated Channel "Proxy" IMessageSink Transparent Proxy MethodA() MethodB() PropertyQ PropertyP FieldX FieldY Real Proxy Builds Invoke() SyncProcessMessage()

.NET Remoting The Dispatcher  Located at the channel endpoint  Receives messages  Builds stack-frame from message content  Invokes actual method on object  Collects result and creates response message

Server Dispatcher.NET Remoting The Dispatcher Illustrated Client Channel Object MethodA() MethodB() PropertyQ PropertyP FieldX FieldY Dispatcher (ChannelServices) SyncDispatchMessage() Actual method calls

.NET Remoting 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

.NET Remoting Context Attributes and Properties Property Object System. ContextBoundObject Attribute Create object IsContextOK() ? 1 No! GetPropertiesForNewContext() ! 2 3 New Yes! Use existing context No! Create new context ContextBound Class

.NET Remoting Remoting Services  System.Runtime.Remoting.RemotingServices class Provides fundamental remoting infrastructure Remoting configuration Connecting to remote object instances Exposing "well known objects"  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

.NET Remoting 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 only expose "single call" or "singleton" objects

.NET Remoting 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 Can mirror COM's class factory concept Object is created at registration time  RemotingServices.RegisterWellKnownType WellKnownObjectMode.SingleCall WellKnownObjectMode.Singleton

.NET Remoting Server Setup Example  Channels and Objects are AppDomain-Global... HTTPChannel chan = new HTTPChannel(8085); ChannelServices.RegisterChannel(chan); RemotingServices.RegisterWellKnownType( "MyAssembleName", "MyNamespace.ServerClass", "MyEndpointURI", WellKnownObjectMode.SingleCall); Registers the single-call endpoint: Channel registration Object registration

o = Activator. GetObject(" o.methodCall();.NET Remoting Activation Illustrated AppDomain Context Object TCP 8501 HTTP 8088 Identity Table uriAuriBuriCuriD tcp://server:8501/uriD RemotingServices.Connect() Activator.GetObject() Language binding o = new myClass(); o.methodCall();

.NET Remoting Channel Programming Examples // Registering a Channel public class SomeClass { HTTPChannel httpChannel; public void SomeMethod() { httpChannel = new HTTPChannel(); ChannelServices.RegisterChannel(httpChannel); } // Lookup all the registered Channels public class SomeClass { public void LookupAllChannels() { IChannel[] channels = ChannelServices.RegisteredChannels; for(int i=0;i<channels.Length;i++) { Console.WriteLine("ChannelName: " + channels[i].ChannelName); } } //... }

.NET Remoting Proxy Programming Examples Determining if an object is actually a proxy public class SomeClass { //... public void ProxyCheck(Object obj) { if (RemotingServices.IsTransparentProxy(obj) == true) Console.WriteLine("Is a proxy"); else Console.WriteLine("Is not a proxy"); } //... } Obtaining the RealProxy from a Proxy public class SomeClass { //... public void ObtainRealProxy (Object obj) { RealProxy realProxy = RemotingServices.GetRealProxy( obj); //... }

.NET Remoting Context Programming Examples Context Local Data Store Allocated Slots Foo foo = new Foo(); // Allocate data slot on all contexts LocalDataStoreSlot dataslot = Context.AllocateDataSlot(); // Store foo in the Context Local Store Context.SetData(dataslot, oFoo); / Retrieve foo from the Context Local Store Foo foo2 = Context.GetData(dataslot); Writing your own context attribute public class MyContextAttribute : ContextAttribute, IContributeServerContextSink {... public IMessageSink GetServerContextSink(IMessageSink nextSink) { return new MyContextServerSink(nextSink); }... };

Agenda  Reflection  Remoting  Serialization

Serialization  What is Serialization?  System.Serialization  Scenarios in Serialization  Basic Serialization  Custom Serialization

Serialization What is Serialization  Serialization is the process of converting an object, or a connected graph of objects, stored within computer memory, into a linear sequence of bytes  Use the sequence of bytes in several ways: Send it to another process Send it to the clipboard, to be browsed or used by another application Send it to another machine Send it to a file on disk

Serialization Object Graph  What is an object graph? An object graph is a set of objects with some set of references to each other The most obvious problem is how to represent the links between the objects in the Serialized stream Cat Mouse Duck Dog Horse

Serialization How Serialization Works  Because run-time metadata 'knows' about each object's layout in memory, and its field and property definitions, you can serialize objects automatically, without having to write code to serialize each field  The serialized stream might be encoded using XML, or a compact binary representation  The format is decided by the the Formatter object that you call: Binary SOAP Custom

Serializaiton FileStream Example class SerializeExample{ public static void Main(String[] args) { ArrayList l = new ArrayList(); for (int x=0; x< 100; x++) { l.Add (x); } // create the object graph FileStream s = File.Create("foo.bin"); // create the filestream BinaryFormatter b = new BinaryFormatter(); // create the BinaryFormatter b.Serialize(s, l); // serialize the graph to the stream } // end main } // end class

Serializaiton Deserialize Example using System; using System.IO; using System.Collections; using System.Serialization; using System.Serialization.Formatters.Binary; class DeSerialize { public static void Main(String[] args) { FileStream s = File.Open("foo.bin"); // open the filestream BinaryFormatter b = new BinaryFormatter(); // create the formatter ArrayList p = (ArrayList) b.Deserialize(s); // deserialize p.ToString(); // print out the new object graph } // end Main } // end Class DeSerialize

Serialization Scenarios  Persistence  Flat-File Persistence  Remoting-By-Value  Remoting-By-Reference  Transacted Persistence

Serialization Persistence  To Persist an object or collection of objects means to make them somehow survive beyond the life of the process that holds them in its memory.  Conventionally, the objects are saved onto a hard disk, within a file, a storage stream, or a database.  Within.NET runtime, we will use the terms Persist and Persistence in the stronger sense of saving the objects to disk, and retrieving them afterwards, under the protection of transactions

Serialization Flat File Persistence  The runtime provides a default text formatter (e.g., generating XML stream) for serializing an entire object graph to a file ArrayList l = new ArrayList(); for (int x=0; x< 10; x++) { l.Add (x); } Stream s = (new File ("foo.bin")).Open(FileMode.Create); BinaryFormatter b = new BinaryFormatter(); b.Serialize(s, l); s.Close(); Stream r = (new File ("foo.bin")).Open(FileMode.Open); BinaryFormatter c = new BinaryFormatter(); ArrayList p = (ArrayList) c.Deserialize(r);

Serialization Remoting-By-Val and Remoting-By-Ref  Remoting-By-Val Serialize a copy of a graph of objects and pass it to the remote process No guarantee that fields will be laid out in memory in the same order  Rmoting-By-Ref On the remote node, we establish a transparent proxy – it behaves like the real object. However, any accesses of its fields are passed back to the original object. Serialization does not know how to create the proxy object. This is accomplished through the Remoting service using a Surrogate for that Remote-by-ref object.

 The customer order process, represented in the graph, is under transactional control  Serialization is complicated process  Transacted Persistence provides its own formatters and serializers, which would layer on the basic serialization service Serialization Transacted Persistence Salesman Order Customer Order 2 1 3

Serialization Basic Serialization  A Type is NOT Serializable unless Type is specifically marked as Serializable  The Serializable Attribute  The Non-Serializable Attribute [Serializable] public class MyClass {} [Serializable] public class MyClass { [NotSerialized] int _cashSize; }

Serialization Customize Serialization  Implementing ISerializable interface  IDeserializationEventListener  Custom Formatters

Serialization ISerializable Interface  Customize the serialization process  If a class implements ISerializable, that interface will always be called in preference to default serialization.  The ISerializable interface is only contains one method: void GetObjectData (SerializationInfo info, StreamingContext context); And an implied constructor that may be private. private (SerializationInfo info, StreamingContext)

Serialization IDeserializationEventListener  If an object implements IDeserializationEventListener, the serialization infrastructure will call that class‘ OnDeserialization method as soon as the entire graph has been deserialized and all fix- ups completed  Provide a reasonable opportunity for objects that need to do fix-ups based on the state of their children

Serialization Custom Formatter  Implementing IFormatter Interface: public interface IFormatter: { //Properties SerializationBinder Binder { get; set; } StreamingContext Context { get; set; } ISurrogateSelector SurrogateSelector { get; set; } //Methods object Deserialize(Stream serializationStream); void Serialize(Stream serializationStream, object graph); }

Conclusion  Types' metadata can be explored with Reflection  Reflection provides dynamic type system  The Federated Services Model is one of the core concepts for designing.NET applications in Internet  Key.NET Remoting scenarios are: Web Services Anywhere CLR Object Remoting  Serialization is the process of converting an object, or a connected graph of objects, stored within computer memory, into a linear sequence of bytes

Resources  .NET Framework SDK