- •Table of Contents
- •C# and the .NET Platform, Second Edition
- •Introduction
- •Part One: Introducing C# and the .NET Platform
- •Part Two: The C# Programming Language
- •Part Three: Programming with .NET Assemblies
- •Part Four: Leveraging the .NET Libraries
- •Part Five: Web Applications and XML Web Services
- •Obtaining This Book's Source Code
- •The .NET Solution
- •What C# Brings to the Table
- •The Role of the Assembly Manifest
- •Summary
- •Chapter 2: Building C# Applications
- •Summary
- •Chapter 3: C# Language Fundamentals
- •Defining Program Constants
- •Defining Custom Class Methods
- •C# Enumerations
- •Summary
- •The Second Pillar: C#'s Inheritance Support
- •Summary
- •Catching Exceptions
- •Finalizing a Type
- •Garbage Collection Optimizations
- •Summary
- •Chapter 6: Interfaces and Collections
- •Building Comparable Objects (IComparable)
- •Summary
- •Summary
- •Internal Representation of Type Indexers
- •Summary
- •An Overview of .NET Assemblies
- •Understanding Delayed Signing
- •Using a Shared Assembly
- •GAC Internals
- •Summary
- •Spawning Secondary Threads
- •A More Elaborate Threading Example
- •Summary
- •Summary
- •Object Persistence in the .NET Framework
- •The .NET Remoting Namespaces
- •Understanding the .NET Remoting Framework
- •All Together Now!
- •Terms of the .NET Remoting Trade
- •Testing the Remoting Application
- •Revisiting the Activation Mode of WKO Types
- •Deploying the Server to a Remote Machine
- •Summary
- •Control Events
- •The Form Class
- •Summary
- •Regarding the Disposal of System.Drawing Types
- •Understanding the Graphics Class
- •Summary
- •The TextBox Control
- •Working with Panel Controls
- •Configuring a Control's Anchoring Behavior
- •Summary
- •Chapter 16: The System.IO Namespace
- •The Static Members of the Directory Class
- •The Abstract Stream Class
- •Summary
- •The Role of ADO.NET Data Providers
- •The Types of System.Data
- •Selecting a Data Provider
- •The Types of the System.Data.OleDb Namespace
- •Working with the OleDbDataReader
- •Summary
- •Submitting the Form Data (GET and POST)
- •Some Benefits of ASP.NET
- •Creating an ASP.NET Web Application by Hand
- •The Composition of an ASP.NET Page
- •The Derivation of an ASP.NET Page
Summary C# and the .NET Platform, Second Edition
by Andrew Troelsen ISBN:1590590554
Reflection is a very interesting aspect of a robust OO environment. In the world of .NET, the keys to
Apress © 2003 (1200 pages)
reflection services revolve around the System.Type class and the System.Reflection namespace. As you
This comprehensive text starts with a brief overview of the
have seen, reflectionC# languageis the processand thenof placingqui kly movesa type tounderkey theechnicalmagnifyingand glass at runtime to understand the "who, what, where,architecturalwhy, andissueshow"forof.NETa givend velopersitem. .
Late binding is the process of creating a type and invoking its members without foreknowledge of the
Tablesp cificof Contentsnames of said members. As shown during our extendible application example, this is a very C#powerfuland thetechnique.NET Platform,usedSecondby tool Editionbuilders as well as tool consumers.
Introduction
This chapter also examined the role of attribute-based programming. When you adorn your types with attributes, the result is the augmentation of the underlying assembly metadata. While you may never find yourself in the position of absolutely having to build custom attributes, you are bound to find the predefined attributes invaluable, especially when building a bridge between your classic COM servers and .NET
assemblies, or leveraging .NET serialization services and the .NET Remoting layer.
Chapter 3 - C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
List of Figures
List of Tables
Part Four:C# andLeveragingthe .NET Platform,theSecond.NETEdition Libraries
by Andrew Troelsen |
ISBN:1590590554 |
Apress © 2003 (1200 pages)
Chapter ListThis comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.
Chapter 12: Object Serialization and the .NET Remoting Layer
Table of Contents
Chapter 13: Building a Better Window (Introducing Windows Forms)
C# and the .NET Platform, Second Edition
Introduction
Chapter 14: A Better Painting Framework (GDI+)
Part One - Introducing C# and the .NET Platform
Chapter 15: Programming with Windows Forms Controls
Chapter 1 - The Philosophy of .NET
Chapter 2 - Building C# Applications
Chapter 16: The System.IO Namespace
Part Two - The C# Programming Language
Chapter 3 - C# Language Fundamentals
Chapter 17: Data Access with ADO.NET
Chapter 4 - Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
List of Figures
List of Tables
Chapter C#12:andObjectthe .NET Platform,SerializationSecond Editi n and the .NET
by Andrew Troelsen |
ISBN:1590590554 |
Apress © 2003 (1200 pages) |
|
Remoting Layer |
|
This comprehensive text starts with a brief overview of the
C# language and then quickly moves to key technical and
Overview architectural issues for .NET developers.
Developers who are new to the .NET platform naturally assume that .NET is all about building Internet-
Tablecentricof Contenapplications (given the term ".NET"). As you have already seen however, this is simply not the C#caseand. Inthefact,.NETthePlatform,constructionSecondofEditionWeb-centric programs is simply one tiny (but quite well-touted) aspect of
the .NET platform. In this same vein of misinformation, many new .NET developers tend to assume that
Introduction
XML Web services are the only way to interact with remote objects. Again, this is not true. The .NET
Part One - Introducing C# and the .NET Platform
platform provides numerous namespaces devoted to the creation of traditional distributed applications,
Chapter 1 - The Philosophy of .NET
which have nothing to do whatsoever with XML Web services (or Web applications). In short, using .NET
Chapter 2 - Building C# Applications
you are able to build peer-to-peer distributed applications that have nothing to do with HTTP or XML (if you
Part Two - The C# Programming Language
so choose). As you will see over the course of this chapter, the .NET Remoting architecture is a managed
Chapter 3 - C# Language Fundamentals
replacement for classic DCOM.
Chapter 4 - Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime
The first goal of this chapter is to describe a critical remoting-centric topic: object serialization. Simply put,
Chapter 6 - Interfaces and Collections
serialization is the act of persisting an object's state data to a given location (e.g., a memory stream,
Chapter 7 - Callback Interfaces, Delegates, and Events
physical file, etc.). Deserialization, on the other hand, is the process of reading the persisted data from Chsaidpterlocation8 - Advancedand recreatingC# Typea newConstructiontype basedTechoniquthespreserved stateful values. As you might imagine, the
Pabilityrt Threeto serialize- Programmingtypes iswithcritical.NETwhenAssembliesattempting to copy an object to a remote machine (e.g., marshal-
Chapterby-value)9 .-Understand,Understandinghowever,.NET Assembliesthat serialization is quite useful in its own right, and will likely play a role in
Chaptermany of10your- Processes,.NET applicationsAppD mains,(distributedCont xts,oranot)d Threads.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Once you have seen the .NET serialization protocol in action, the next goal is to examine the low-level
Part Four - Leveraging the .NET Libraries
grunge used by the CLR to move information between application boundaries. Along the way, you will
Chapter 12 - Object Serialization and the .NET Remoting Layer
come to understand the numerous terms used when discussing .NET Remoting, such as proxies, channels, marshaling by reference (as opposed to by value), server-activated (versus client-activated)
objects, and so forth. With these background elements complete, the remainder of this chapter offers
Chapter 15 - Programming with Windows Forms Controls
numerous code examples that illustrate the process of building distributed systems using the .NET
Chapter 16 - The System.IO Namespace platform.
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
List of Figures
List of Tables
Object Persistence in the .NET Framework |
|
C# and the .NET Platform, Second Edition |
|
by Andrew Troelsen |
ISBN:1590590554 |
Object serialization is one of the key underlying technologies used by the .NET Remoting layer. Simply
Apress © 2003 (1200 pages)
put,serialization is the term describing the process of converting the state of an object to a linear
This comprehensive text starts with a brief overview of the
sequence of dataC#. Thislanguagedata sequenceand then quicklycontainsmovesall necessaryto key technicalinformationnd needed to reconstruct (or deserialize) the statearchitecturalof the objectissuesforforuse.NETlaterdevelopers. The .NET. serialization services are quite sophisticated:
When a given object is serialized to a stream, any associated object references required by the root object are automatically serialized as well. For example, when a derived class is serialized, each serializable
Table of Contents
object in the chain of inheritance is able to write its own custom state data into the data stream.
C# and the .NET Platform, Second Edition
Furthermore, if a given type contains serializable member variables, the member variables themselves Introductialso automaticallyn participate in the serialization process.
Part One - Introducing C# and the .NET Platform
Once a set of objects has been saved to a stream, the data pattern can be relocated as necessary. For
Chapter 1 - The Philosophy of .NET
example, imagine you have serialized an object graph into a memory location using the
Chapter 2 - Building C# Applications
System.IO.MemoryStream type. This stream could be forwarded to a remote computer, the Windows
Part Two - The C# Programming Language
clipboard, burned to a CD, or simply written to a physical file. The object itself does not care where it is
Chapter 3 - C# Language Fundamentals
stored. All that matters is the fact that this stream of 1s and 0s (or, depending on your choice of formatter, |
|
Chapter 4 - Object-Oriented Programming with C# |
|
XML elements) correctly represents the state of the serialized objects. |
|
Chapter 5 |
- Exceptions and Object Lifetime |
Chapter 6 |
- Interfaces and Collections |
Note The System.IO namespace defines numerous types that allow you to read (and write) |
|
Chapter 7 |
- Callback Interfaces, Delegates, and Events |
|
information to (and from) files, memory locations, and character buffers. Chapter 16 examines |
Chapter 8 |
- Adv nc d C# Type Construction Techniqu |
|
this namespace in detail; however, by necessity, you will be introduced to some System.IO types |
Part Three -duringP ogrammingthis chapter'swith .NETexaminationAssembliesof object serialization.
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
List of Figures
List of Tables
The Role ofC#Objectand the .GraphsNET Platform, Second Edition
by Andrew Troelsen |
ISBN:1590590554 |
As mentioned, when a type is serialized by the CLR, the runtime will account for each related object. The
Apress © 2003 (1200 pages)
chain of related objects serialized to a stream is collectively referred to as an object graph. Object graphs
This comprehensive text starts with a brief overview of the
provide a simple C#waylanguageto documentand thenhowquicklya set ofmobjectsves to referkey technicalto eachandother and are not intended to directly model classic OOarchitecturalrelationshipsi sues(suchforas.NETthedevelopers"is-a" or "has. -a" relationship), although they do map to this paradigm quite well. To establish the relations among objects in a graph, each object is assigned a unique numerical value, followed by a graph of all related items. Keep in mind that the numbers assigned to the
Table of Contents
members in an object graph are arbitrary and have no real meaning to the outside world.
C# and the .NET Platform, Second Edition
As a simple example, assume you have created a set of classes that model some automobiles (of
Introduction
course). You have a topmost type named Car, which "has-a" Radio. Another class named JamesBondCar
Part One - Introducing C# and the .NET Platform
extends the basic Car type. An object graph that models these relationships is shown in Figure 12-1.
Chapter 1 - The Philosophy of .NET
Chapter 2 - Building C# Applications
Part
Chapter |
|
Chapter |
with C# |
Chapter |
|
Chapter |
|
Chapter |
and Events |
Chapter |
Techniques |
Part |
|
Chapter |
|
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Figure 12-1: A simple object graph
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
ChapterInFigure1212--Object1 you canSerializaseethation andthe Carthe .classNET Remotingrefers toLayerthe Radio class (given the "has-a" relationship). The ChJamesBondCarpt r 13 - Buildingrefersa Betterto theWindowCar (given(I troducingthe "is-a"Windowsrelationship)Forms)as well as the Radio (as it inherits this
protected member variable). Given that we have assigned an arbitrary value to each member in the object
Chapter 14 - A Better Painting Framework (GDI+)
graph, we could represent the relationship documented in the previous diagram with the following formula:
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
Chapter[Car 3,17 -refData2],Access[Radiowith ADO2],.NET[JamesBondCar 1, ref 3, ref 2]
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
If we parse this formula, you can see that the Car type has a dependency on item 2 (the Radio). Also, the
Chapter 19 - ASP.NET Web Applications
JamesBondCar has a dependency on item 3 (the Car) as well as item 2 (the Radio). Item 2, the Radio, is
a lone wolf. If you serialize an instance of JamesBondCar to a stream, the object graph ensures that the
Index
Radio and Car types also participate in the process. The beautiful thing about the default serialization
List of Figures
process is that the graph representing the relationships among your objects is established automatically
List of Tables behind the scenes.
ConfiguringC#Objectsand the .NETforPlatform,SerializationSecond Edition
by Andrew Troelsen |
ISBN:1590590554 |
To make an object available to .NET serialization services, all you need to do is decorate each class with
Apress © 2003 (1200 pages)
the [Serializable] attribute. That's it (really). If you determine that a given class has some member data that
This comprehensive text starts with a brief overview of the
should not participateC# languagein the serializationand then quischeme,kly movesyoutocankeymarktechnicalsuchandfields with the [NonSerialized] attribute. This canarchitecturalbe helpful ifissuesyou havefor .NETmemberdevelopersvariables. in a serializable class that do not need to be "remembered" (e.g., constants, transient data, and so on). For example, here is the Radio class, which has been marked as serializable (except for a single member variable):
Table of Contents
C# and the .NET Platform, Second Edition
// The Radio class can participate in the .NET serialization scheme.
Introduction
[Serializable]
Part One - Introducing C# and the .NET Platform
public class Radio
Chapter |
1 |
- The Philosophy of .NET |
|
{ |
|
|
|
Chapter |
2 |
- Building C# Applications |
|
|
// This member will not be persisted. |
||
Part Two - The C# Programming Language |
|
||
|
[NonSerialized] |
|
|
Chapter |
3 |
- C# Language Fundamentals |
|
|
private int objectIDNumber = 9; |
|
|
Chapter |
4 |
- Obj ct-Oriented Programming with C# |
|
|
// |
Other serialized state data |
|
Chapter |
5 |
- Exceptions and Object Lifetime |
|
|
... |
|
|
Chapter public6 - InterfacesRadio(){and Collections} |
|
||
Chapter public7 - CallbackvoidInterfaces,On(boolDelegates,state)and Events |
|
||
Chapter {8 |
- Advanced C# Type Construction Techniques |
||
Part Three - Programmingif(statewith== .NETtrue)Assemblies |
is on..."); |
||
Chapter |
9 |
- UnderstandingMessageBox.Show("Music.NET Assemblies |
|
Chapter |
10 |
- Processes,else AppDomains, Contexts, and Threads |
|
Chapter |
11 |
- Type Reflection,MessageBox.Show("NoLate Binding, and Attributetunes-Based...");Programming |
|
Part Four}- Leveraging the .NET Libraries |
|
||
Chapter} |
12 |
- Object Serialization and the .NET Remoting Layer |
|
Chapter |
13 |
- Building a Better Window (Introducing Windows Forms) |
|
Chapter |
14 |
- A Better Painting Framework (GDI+) |
|
As you would guess, these attributes are embedded within the type's metadata, as you can see using |
|||
Chapter |
15 |
- Programming with Windows Forms Controls |
|
ildasm.exe (Figure 12-2). |
|
||
Chapter |
16 |
- The System.IO Namespace |
|
Chapter |
17 |
- Data Access with ADO.NET |
|
Part |
|
Services |
|
Chapter |
|
Controls |
|
Chapter |
|
|
|
Chapter |
|
|
|
Index
List of
List of
Figure 12-2: The Serializable and NonSerialized attributes
To finish the coding of this car hierarchy, here are the definitions for the Car base class and JamesBondCar subtype, each marked with the [Serializable] attribute:
// The Car class is serializable!
[Serializable]
public class Car
{
protected string petName; protected int maxSpeed;
protected Radio theRadio = new Radio();
C# and the .NET Platform, Second Edition public Car(string petName, int maxSpeed)
ISBN:1590590554
{
}
public Car() { } public String PetName
{
Table of Contents
get { return petName; }
C# and the .NET Platform, Second Edition
set { petName = value; }
Introduction
}
Part One - Introducing C# and the .NET Platform
public int MaxSpeed
Chapter 1 - The Philosophy of .NET
{
Chapter 2 - Building C# Applications
get { return maxSpeed; }
Part Two - The C# Programming Language
set { maxSpeed = value; }
Chapter 3 - C# Language Fundamentals
}
Chapter 4 - Object-Oriented Programming with C# public void TurnOnRadio(bool state)
Chapter 5 - Exceptions and Object Lifetime
{ theRadio.On(state); }
Chapter 6 - Interfaces and Collections
}
Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter// The8 JamesBondCar- Advanced # TypeclassConstructionis alsoTechniquesserializable!
Part[Serializable]Three - Programming with .NET Assemblies
Chapterpublic9 class- UnderstJamesBondCarnding .NET Assemblies: Car
{
Chapter 10 - Processes, AppDomains, Contexts, and Threads
// Made public for easy access.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
// Feel free to make use of type properties.
Part Four - Leveraging the .NET Libraries
public bool isFlightWorthy;
Chapter 12 - Object Serialization and the .NET Remoting Layer
public bool isSeaWorthy;
Chapter 13 - Building a Better Window (Introducing Windows Forms)
public JamesBondCar(){ }
Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
{
Part Five - Web Applications and XML Web Services
this.isFlightWorthy = canFly;
Chapter 18 - ASP.NET Web Pages and Web Controls this.isSeaWorthy = canSubmerge;
Chapter 19 - ASP.NET Web Applications
}
Chapter 20 - XML Web Services
public void Fly()
Index {
List of Figures if(isFlightWorthy)
List of Tables |
MessageBox.Show("Taking off!"); |
|
else
MessageBox.Show("Falling off cliff!");
}
public void GoUnderWater()
{
if(isSeaWorthy) MessageBox.Show("Diving....");
else
MessageBox.Show("Drowning!!!");
}
}
Choosing a Serialization Formatter
Once you have configuredC# and theyour.NETtypesPlatoform,participateSecondin Editionthe .NET serialization scheme, your next step is to choose which formatby AndrewshouldTroelsenbe used when persisting your objectISBN:1590590554graph. The System.Runtime.ApressSerialization© 2003.(1200Formattersp ges) namespace contains two additional nested namespaces
(*.Binary and *.Soap) that provide two out-of-the-box formatters. As you can guess, the BinaryFormatter
This comprehensive text starts with a brief overview of the
type serializes yourC#objectlanguagraphe andtothena streamquicklyusingmovesa compactto key technicalbinaryandformat. The SoapFormatter type
architectural issues for .NET developers.
represents your graph as a SOAP (Simple Object Access Protocol) message that is expressed using XML data representation.
TableTheofSystemContents.Runtime.Serialization.Formatters.Binary.BinaryFormatter type is defined within mscorlib.dll.
C#Therefore,and the .NETto serializePl tform,yourSecobjectsnd Editionusing a binary format, all you need to do is specify the following C#
Introductionusing directive:
Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy of .NET
// Persist object graph using a binary format!
Chapter 2 - Building C# Applications
using System.Runtime.Serialization.Formatters.Binary;
Part Two - The C# Programming Language
Chapter 3 - C# Language Fundamentals
However, the System.Runtime.Serialization.Formatters.Soap.SoapFormatter type is defined in a separate
Chapter 4 - Object-Oriented Programming with C#
assembly. To format your object graph into a SOAP message, you must set a reference to
Chapter 5 - Exceptions and Object Lifetime
System.Runtime.Serialization.Formatters.Soap.dll and make the following C# using directive:
Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
// Persist object graph using a SOAP format!
Chapter 8 - Advanced C# Type Construction Techniques
using System.Runtime.Serialization.Formatters.Soap;
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Regardless of which formatter you choose to make use of, do be aware that .NET formatters supply a
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
common set of functionality through the implementation of the IFormatter and IRemotingFormatter
Part Four - Leveraging the .NET Libraries
interfaces. IFormatter defines the key Serialize() and Deserialize() methods, which do the grunt work to
Chapter 12 - Object Serialization and the .NET Remoting Layer
move your object graphs into and out of a specific stream (represented by the System.IO.Stream abstract
Chapter 13 - Building a Better Window (Introducing Windows Forms) base class). Here is the formal definition of IFormatter:
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
public interface System.Runtime.Serialization.IFormatter
Chapter 16 - The System.IO Namespace
{
Chapter 17 - Data Access with ADO.NET
SerializationBinder Binder { get; set; }
Part Five - Web Applications and XML Web Services
StreamingContext Context { get; set; }
Chapter 18 - ASP.NET Web Pages and Web Controls
ISurrogateSelector SurrogateSelector { get; set; }
Chapter 19 - ASP.NET Web Applications
object Deserialize(System.IO.Stream serializationStream);
Chapter 20 - XML Web Services
void Serialize(System.IO.Stream serializationStream, object graph);
Index}
List of Figures
List of Tables
The IRemotingFormatter interface (which is leveraged internally by the .NET Remoting layer) overloads the Serialize() and Deserialize() members, into a manner more appropriate for remoting-centric persistence. Note that IRemotingFormatter derives from the more general IFormatter interface:
public interface System.Runtime.Remoting.Messaging.IRemotingFormatter
: System.Runtime.Serialization.IFormatter
{
object Deserialize(System.IO.Stream serializationStream, System.Runtime.Remoting.Messaging.HeaderHandler handler);
void Serialize(System.IO.Stream serializationStream, object graph, System.Runtime.Remoting.Messaging.Header[] headers);
}
SerializationC#Usingand the .NETa BinaryPlatform,FormatterSecond Edition
by Andrew Troelsen |
ISBN:1590590554 |
To illustrate how easy it is to persist an instance of our JamesBondCar to a physical file, let's make use of
Apress © 2003 (1200 pages)
the BinaryFormatter type. Again, the two key methods of the BinaryFormatter type to be aware of are
This comprehensive text starts with a brief overview of the Serialize() and Deserialize()C# language(Tableand then12-quickly1). moves to key technical and
architectural issues for .NET developers.
Table 12-1: BinaryFormatter Members
|
|
|
|
|
|
|
|
|
TableBinaryFormatterof Contents |
Member |
|
Meaning in Life |
|
||||
|
|
|
|
|
|
|||
C# and the .NET Platform, Second Edition |
|
|||||||
|
|
|
|
Deserialize() |
|
|
Deserializes a stream of bytes to an object graph |
|
|
Introduction |
|
|
|
|
|||
|
|
|
|
|
||||
|
|
|
|
|
|
|
|
|
PartSerialize()One - Introducing C# and the .NETSerializesPlatform an object or graph of related objects to a stream |
|
|||||||
|
|
|
|
|
|
|
|
|
|
Chapter 1 - The Philosophy of .NET |
|
|
|
ChapterIn addition2 -toBuildingthe Deserialize()C# Applicationsand Serialize() methods, the BinaryFormatter type defines a small number Partof propertiesTwo - ThethatC# Programmingconfigure specificLanguagedetails regarding the (de)serialization process. By and large, the
default configuration of BinaryFormatter is all you need to concern yourself with; however we will check
Chapter 3 - C# Language Fundamentals
out additional details as needed over the course of this chapter.
Chapter 4 - Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime
Now, assume you have created an instance of JamesBondCar, modified some state data, and want to
Chapter 6 - Interfaces and Collections
persist your spy-mobile in a *.dat file. The first task is to create the *.dat file itself. This can be achieved
Chapter 7 - Callback Interfaces, Delegates, and Events
using the static System.IO.File.Create() method, which returns an instance of the System.IO.FileStream
Chapter 8 - Advanced C# Type Construction Techniques
type (again, file IO will be examined in Chapter 16). Given that the BinaryFormatter.Serialize() method
Part Three - Programming with .NET Assemblies
requires a Stream-derived type as its first parameter, be sure to maintain this variable. Here is the
Chapter 9 - Understanding .NET Assemblies complete serialization code:
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
using System.Runtime.Serialization.Formatters.Binary,
Part Four - Leveraging the .NET Libraries
using System.IO;
Chapter 12 - Object Serialization and the .NET Remoting Layer
public static void Main()
Chapter 13 - Building a Better Window (Introducing Windows Forms)
{
Chapter 14 - A Better Painting Framework (GDI+)
// Make a car and change some state data.
Chapter 15 - Programming with Windows Forms Controls
JamesBondCar myAuto = new JamesBondCar("Fred", 50, false, true);
Chapter myAuto16 - The.SystemTurnOnRadio(true);.IO Namespace
Chapter myAuto17 - Data.GoUnderWater();Access with ADO.NET
Part Five//- WebCreateApplicationsfileandstreamXML WebtoServiceshold the object's state.
Chapter FileStream18 - ASP.NET WebmyStreamPag s and=WebFileControls.Create("CarData.dat");
// Move the object graph into the file stream using a binary format.
Chapter 19 - ASP.NET Web Applications
BinaryFormatter myBinaryFormat = new BinaryFormatter();
Chapter 20 - XML Web Services
Index myBinaryFormat.Serialize(myStream, myAuto);
myStream.Close();
List of Figures
}
List of Tables
As you can see, the BinaryFormatter.Serialize() method is the member responsible for composing the object graph and moving the byte sequence to some Stream-derived type. In this case, the stream happens to be a physical file. However, you could also serialize your object types to any Stream-derived type (such as a memory location, given that MemoryStream is a descendent of the Stream type). If you open the *.dat file, you can peek inside the byte sequence (Figure 12-3).
Second Edition
ISBN:1590590554
starts with a brief overview of the
moves to key technical and
developers.
Table
C# and
Part
ChapterFigure1 - 12The-3:PhilosophyJamesBondCarof .NETserialized using a BinaryFormatter
Chapter 2 - Building C# Applications
Now suppose you want to read the persisted JamesBondCar back to an object variable. Once you have
Part Two - The C# Programming Language
programmatically opened the correct *.dat file (via the File.OpenRead() method), simply call Deserialize().
Chapter 3 - C# Language Fundamentals
Be aware that Deserialize() returns a generic System.Object type, and therefore you need to impose an
Chapter 4 - Object-Oriented Programming with C#
explicit cast, as shown here:
Chapter 5 - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections
// Read in the Car from the binary stream.
Chapter 7 - Callback Interfaces, Delegates, and Events
myStream = File.OpenRead("CarData.dat");
Chapter 8 - Advanced C# Type Construction Techniques
JamesBondCar carFromDisk =
Part Three - Programming with .NET Assemblies
(JamesBondCar)myBinaryFormat.Deserialize(myStream);
Chapter 9 - Understanding .NET Assemblies
Console.WriteLine("{0} is alive!", carFromDisk.PetName);
Chapter 10 - Processes, AppDomains, Contexts, and Threads carFromDisk.TurnOnRadio(true);
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming myStream.Close();
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
ChapterNotice 13that-whenBuildingyoua callBetterDeserialize(),Window (IntryouducingpassWindowsthe StreamForms)-derived type that represents the location of
Chapterthe persisted14 - AobjectsBetter Painting(again Frameworkfile stream(GDI+)in this case). Now if that is not painfully simple, I'm not sure what
Chapteris. In a 15nutshell,- Programmingmark eachwithclassWindyouwswishFormsto persistControlsto a stream with the [Serializable] attribute. After this Chapterpoint, use16 -theTheBinaryFormatterSystem.IO Namespacetype to move your object graph to and from a binary stream.
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
List of Figures
List of Tables
SerializationC#Usingand the .NETa SOAPPlatform,FormatterSecond Edition
by Andrew Troelsen |
ISBN:1590590554 |
The other available formatter you may use when serializing your types is SoapFormatter. Remember you
Apress © 2003 (1200 pages)
must set a reference to System.Runtime.Serialization.Formatters.Soap.dll to use this type! The following
This comprehensive text starts with a brief overview of the
block of code extendsC# languagethe previousand thenserializationquickly movesexampleto keyto technicalpersist theandJamesBondCar using the SoapFormatter type:architectural issues for .NET developers.
using System.Runtime.Serialization.Formatters.Soap;
Table of Contents
...
C# and the .NET Platform, Second Edition
// Save the same car using a soap format.
Introduction
FileStream myStream = File.Create("CarSoapData.xml");
Part One - Introducing C# and the .NET Platform
SoapFormatter mySoapFormat = new SoapFormatter();
Chapter 1 - The Philosophy of .NET
mySoapFormat.Serialize(myStream, myAuto);
Chapter 2 - Building C# Applications
myStream.Close();
Part Two - The C# Programming Language
// Read in the Car from the XML file.
Chapter 3 - C# Language Fundamentals
myStream = File.OpenRead("CarSoapData.xml");
ChJamesBondCarpt r 4 - Object-Oriented Programming with C# carFromSoap =
Chapter 5 - Exceptions(JamesBondCar)mySoapFormatand Object Lifetime .Deserialize(myStream);
ChapterConsole6 .-WriteLine("{0}Interfaces and Collectisonsalive!", carFromSoap.PetName);
ChaptermyStream7 -.CaClose();lback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
As you can see, the SoapFormatter type has the same public interface as the BinaryFormatter. As before,
Chapter 9 - Understanding .NET Assemblies
use Serialize() and Deserialize() to move the object graph in and out of the stream. If you open the
Chapter 10 - Processes, AppDomains, Contexts, and Threads
resulting *.xml file (Figure 12-4), you can locate the XML tags that mark the stateful values of the current
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
JamesBondCar (as well as the relationship maintained by the graph).
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter |
Windows Forms) |
Chapter |
|
Chapter |
Controls |
Chapter |
|
Chapter |
|
Part
Chapter
Chapter
Chapter
Index
List of
List of
Figure 12-4: JamesBondCar serialized using a SoapFormatter
SerializationC#Usingand the .NETan XMLPlatform,FormatterSecond Edition
by Andrew Troelsen |
ISBN:1590590554 |
In addition to the SOAP and binary formatters, the System.Xml.dll assembly provides a third formatter
Apress © 2003 (1200 pages)
(System.Xml.Serialization.XmlFormatter) that can be used to persist the state of a given object using pure
This comprehensive text starts with a brief overview of the
XML (as opposedC#tolanguageXML dataandexpressedthen quicklyvia amovesSOAPtomessage)key technical. Assumingand your application has set a reference to Systemarchitectural.Xml.dll (andissuesyouforhave.NETadevelopersC# "using". directive specifying the System.Xml.Serialization namespace), you are able to serialize and deserialize your JamesBondCar as pure XML:
Table of Contents
// Now save car using a pure XML format.
C# and the .NET Platform, Second Edition
Console.WriteLine("\n***** Saving car to CarXmlData.xml file *****");
Introduction
myStream = File.Create("CarXmlData.xml");
Part One - Introducing C# and the .NET Platform
XmlSerializer myXmlFormat =
Chapter 1 - The Philosophy of .NET
new XmlSerializer(typeof(JamesBondCar), "Cars");
Chapter 2 - Building C# Applications
myXmlFormat.Serialize(myStream, myAuto);
Part Two - The C# Programming Language
myStream.Close();
Chapter 3 - C# Language Fundamentals
// Read in the Car from the XML file.
Chapter 4 - Object-Oriented Programming with C#
Console.WriteLine("\n***** Reading car from Xml file *****");
ChaptermyStream5 - Exceptions= File.OpenRead("CarXmlDataand Object Lifetime .xml");
ChJamesBondCarpt r 6 - Inte facarFromXmles and Collections=
Chapter(JamesBondCar)myXmlFormat7 - Callback Interfaces, Delegates,.Deserialize(myStream);and Events
Console.WriteLine("{0} is alive!", carFromXml.PetName);
Chapter 8 - Advanced C# Type Construction Techniques
carFromSoap.TurnOnRadio(true);
Part Three - Programming with .NET Assemblies
myStream.Close();
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
As you can see, the process is more or less identical to working with the BinaryFormatter and
Part Four - Leveraging the .NET Libraries
SoapFormatter types. The key difference is that the XmlFormatter type requires you to specify type
Chapter 12 - Object Serialization and the .NET Remoting Layer
information of the item to be serialized as well as the name of the XML namespace of the *.xml file via a
Chapter 13 - Building a Better Window (Introducing Windows Forms) constructor parameter.
Chapter 14 - A Better Painting Framework (GDI+)
ChapterNote15 The- ProgrammingXmlFormatterwithdemandsWindows thatFormsallControlsserialized types in the object graph support a default Chapter 16 constructor- The System(so.IObeNamespacesure to add it back if you define custom constructors).
Chapter 17 - Data Access with ADO.NET
If you were to look within the newly generated CarXmlData.xml file you would find the following:
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
<?xml version="1.0"?>
Chapter 19 - ASP.NET Web Applications
<JamesBondCar
Chapter 20 - XML Web Services
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
Index
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
List of Figures xmlns="Cars">
List of Tables
<PetName>Fred</PetName>
<MaxSpeed>50</MaxSpeed>
<isFlightWorthy>false</isFlightWorthy>
<isSeaWorthy>true</isSeaWorthy>
</JamesBondCar>
SOURCE The CarToFile application is located under the Chapter 12 subdirectory.
CODE
CustomizingC# theand theSerialization.NET Platform, SecondProcessEdition
by Andrew Troelsen |
ISBN:1590590554 |
Now that you understand how the .NET platform makes use of serialization services to persist an object to a
Apress © 2003 (1200 pages)
given stream, you are just about ready to check out the details of the .NET Remoting layer. Before moving on
This comprehensive text starts with a brief overview of the however, let's digC#a bitlanguagedeeperaintod thenthe .quicklyNET serializationmoves to keyprocesstechnical. and
architectural issues for .NET developers.
In a vast majority of cases, you will configure a type as serializable by applying the [Serializable] attribute. This attribute enables a given formatter to encode the type into the client-supplied stream. While this is typically
Tableexactlyof Contentsthe behavior you desire, the System.Runtime.Serialization namespace provides several ways to C#customizeand the .theNET.NETPlatform,serializationSecond Editionprocess.
Introduction
The types within this namespace allow you to build custom formatters, as well as extend the default
Part One - Introducing C# and the .NET Platform
serialization processes provided by the [Serializable] attribute. Table 12-2 describes some (but not all) of the
Chapter 1 - The Philosophy of .NET core types to be aware of.
Chapter 2 - Building C# Applications
Part Two - The C# Programming Language
Table 12-2: System.Runtime.Serialization Namespace Core Types
|
|
Chapter 3 |
- C# Language Fundamentals |
|
|
|
|
|
|
ChapterTypes4 |
of- Objectthe-Oriented Programming with C# |
Meaning in Life |
|
||
|
|
ChapterSystem5 .-RuntimeExceptions.Serializationand Object Lifetime |
|
|
|
||
|
|
ChapterNamespace6 - Interfaces and Collections |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Chapter 7 |
- Callback Interfaces, Delegates, and |
Events |
|
||
|
|
Formatter |
|
An abstract base class that provides base functionality |
|
||
|
|
Chapter 8 |
- Advanced C# Type Construction Techniques |
|
|||
Part Three - Programming with .NET Assemblies |
|
|
for runtime serialization formatters. |
|
|||
|
|
|
|
||||
|
|
|
|
||||
ChapterObjectIDGenerator9 - U derstanding .NET Assemblies |
|
|
Generates IDs for objects in an object graph. |
|
|||
|
|
|
|
|
|
||
|
|
Chapter 10 |
- Processes, AppDomains, Contexts, and |
Threads |
|
||
|
|
ObjectManager |
|
Keeps track of objects as they are being deserialized. |
|
||
|
|
Chapter 11 |
- Type Reflection, Late Binding, and Attribute-Based Programming |
|
|||
|
|
|
|||||
PartSerializationBinderFour - Leveraging the .NET Libraries |
An abstract base class that provides functionality to |
|
|||||
Chapter 12 |
- Object Serialization and the .NET RemotingserializeLayera type to a stream. |
|
|||||
|
|
|
|
|
|
||
|
|
Chapter 13 |
- Building a Better Window (Introducing |
|
Windows Forms) |
|
|
|
|
SerializationInfo |
|
|
Used by objects that have custom serialization |
|
|
|
Chapter 14 |
- A Better Painting Framework (GDI+) |
|
|
behavior. SerializationInfo holds together all the data |
|
|
|
Chapter 15 |
- Programming with Windows Forms |
Controls |
|
|||
|
|
Chapter 16 |
- The System.IO Namespace |
|
|
needed to serialize or deserialize an object. In |
|
|
|
essence, this class is a "property bag" that allows you |
|
||||
|
Chapter 17 |
- Data Access with ADO.NET |
|
to establish name/value pairs to represent the state of |
|
||
Part Five - Web Applications and XML Web Services |
an object. |
|
|||||
|
|
|
|
|
|
|
|
|
Chapter 18 |
- ASP.NET Web Pages and Web Controls |
|
|
ChapterIn addition19 -toASPthese.NETtypes,W b Applicationsthere are two key interfaces used during the serialization process: IFormatter
Chapter(mentioned20 - XMLpreviously)Web Servicesand ISerializable. Regardless of which formatter you choose (including any custom Indexformatter you might dream up), the formatter is in charge of transmitting all of the information required to
persist the object during the serialization process. Specifically, the necessary information includes:
List of Figures
List of Tables
The fully qualified name of the object (e.g., MyNamespace.MyClasses.Foo)
The name of the assembly containing the object (e.g., myAsm.dll)
The object's stateful information, contained within a SerializationInfo type
During the deserialization process, the formatter uses this same information to build an identical copy of the object, using the information extracted from the underlying stream. The big picture can be visualized as shown inFigure 12-5.
ISBN:1590590554
of the
and
Table of Contents
Figure 12-5: The serialization process
C# and the .NET Platform, Second Edition
IntroductionWhen you wish to "get involved" with the serialization process, your first step is to implement the standard
PartISerializableOne - IntroducinginterfaceC#onandthetheclass.NETrequiringPlatformcustom serialization. This interface is quite simple, given that it Chapteronly defines1 - Thea singlePhilosophymethod,of .GetObjectData():NET
Chapter 2 - Building C# Applications
Part// TwoWhen- TheyouC#wishProgrammingto tweakL nguagethe serialization process,
Chapter// implement3 - C# LanguageISerializableFundamentals.
Chapterpublic4 interface- Object-OrientedISerializableProgramming with C#
Chapter{ 5 - Exceptions and Object Lifetime
public virtual void GetObjectData(SerializationInfo info,
Chapter 6 - Interfaces and Collections
StreamingContext context);
Chapter 7 - Callback Interfaces, Delegates, and Events
}
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
The GetObjectData() method is called automatically by a given formatter during the serialization process. The
Chapter 10 - Processes, AppDomains, Contexts, and Threads
implementation of this method populates the incoming SerializationInfo parameter with a series of name/value
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
pairs. If you check out this type using wincv.exe, you essentially find numerous variations on the overloaded
Part Four - Leveraging the .NET Libraries
AddValue() method, in addition to a small set of properties that allow the type to get and set the type's name,
Chapter 12 - Object Serialization and the .NET Remoting Layer defining assembly, and member count. Here is a partial snapshot:
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
public sealed class SerializationInfo : object
Chapter 15 - Programming with Windows Forms Controls
{
Chapter 16 - The System.IO Namespace
public SerializationInfo(Type type,
Chapter 17 - Data Access with ADO.NET
System.Runtime.Serialization.IFormatterConverter converter);
Part Five - Web Applications and XML Web Services
public string AssemblyName { get; set; }
Chapter 18 - ASP.NET Web Pages and Web Controls
public string FullTypeName { get; set; }
Chapter 19 - ASP.NET WebMemberCountApplicatio s
public int { get; }
Chapter public20 - XML WebvoidServicesAddValue(string name, short value);
Index public void AddValue(string name, UInt16 value);
List of Figurespublic void AddValue(string name, int value);
...
List of Tables
}
In addition to implementing the ISerializable interface, all objects that make use of custom serialization must provide a special constructor taking the following signature:
//You must supply a custom constructor with this signature
//to allow the runtime engine to set the state of your object.
[Serializable]
class SomeClass : ISerializable
{
private SomeClass (SerializationInfo si, StreamingContext ctx) {...}
...
}
Notice that the visibility of this constructor is set as private. This is permissible given that the formatter will have
C# and the .NET Platform, Second Edition
access to this member regardless of its visibility. These special constructors tend to be marked as private to
by Andrew Troelsen ISBN:1590590554 ensure that the casual object user would never create an object in this manner.
Apress © 2003 (1200 pages)
As you can see, theThisfirstcomprehensiveparameter oftextthistartsconstructorwith a briefis anoverviewinstanceofofthethe SerializationInfo type (seen
C# language and then quickly moves to key technicStreamingContextl and
previously). The second parameter of special constructor is a type, which contains
architectural issues for .NET developers.
information regarding the source or destination of the bits. The most informative member of this type is the State property, which represents a value from the StreamingContextStates enumeration (Table 12-3).
Table of Contents
Table 12-3: StreamingContextStates Enumeration Members
C# and the .NET Platform, Second Edition
IntroductionStreamingContextStates |
Meaning in Life |
|
||||
PartMemberOne - IntroducingName |
C# and the .NET Platform |
|
||||
|
|
|
|
|
|
|
|
|
Chapter 1 |
- The Philosophy of .NET |
Specifies that the serialized data can be transmitted to or |
|
|
|
|
All |
- Building C# Applications |
|
||
|
|
Chapter 2 |
received from any of the other contexts. |
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public void GetObjectData(SerializationInfo si, StreamingContext ctx)
C# and the .NET Platform, Second Edition
{
by Andrew Troelsen |
ISBN:1590590554 |
// What context is the stream? |
|
Apress © 2003 (1200 pages)
Console.WriteLine("[GetObjectData] Context State: {0} ",
This comprehensive text startsStatewi h a brief overview of the ctx. .ToString());
C# language and then quickly moves to key technical and si.AddValue("CapPetName", petName.ToUpper());
architectural issues for .NET developers. si.AddValue("maxSpeed", maxSpeed);
}
// Rehydrate a new object based on incoming SerializationInfo type.
Table of Contents
private CustomCarType(SerializationInfo si, StreamingContext ctx)
C# and the .NET Platform, Second Edition
{
Introduction
// What context is the stream?
Part One - Introducing C# and the .NET Platform
Console.WriteLine("[ctor] Context State: {0} ", ctx.State.ToString());
Chapter 1 - The Philosophy of .NET
petName = si.GetString("CapPetName");
Chapter 2 - Building C# Applications
maxSpeed = si.GetInt32("maxSpeed");
Part Two}- The C# Programming Language
Chapter 3 - C# Language Fundamentals
}
Chapter 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime
ChapterNow that6 the- Interfacestype has andbeenCollectionsconfigured with the correct infrastructure, you will be happy to see that the caller's
serialization and deserialization process remains unaltered (see Figure 12-6 for output):
Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
PartpublicThree -staticProgrammingint withMain(string[].NET Assembliesargs)
Chapter{ 9 - Understanding .NET Assemblies
Chapter CustomCarType10 - Processes, AppDomains,myAuto Cont= newxts,CustomCarType("Sid",and Thre ds 50);
Stream myStream = File.Create("CarData.dat");
Chapter 11 - Type Reflection, Late B nding, and Attribute-B sed Programming
// ISerializable interface obtained!
Part Four - Leveraging the .NET Libraries
BinaryFormatter myBinaryFormat = new BinaryFormatter();
Chapter 12 - Object Serialization and the .NET Remoting Layer
myBinaryFormat.Serialize(myStream, myAuto);
Chapter 13 - Building a Better Window (Introducing Windows Forms)
myStream.Close();
Chapter 14 - A Better Painting Framework (GDI+)
myStream = File.OpenRead("CarData.dat");
Chapter 15 - Programming with Windows Forms Controls
// Special constructor called!
Chapter 16 - The System.IO Namespace
CustomCarType carFromDisk =
Chapter 17 - Data Access with ADO.NET
(CustomCarType)myBinaryFormat.Deserialize(myStream);
Part Five - Web Applications and XML Web Services
Console.WriteLine("{0} is alive!", carFromDisk.petName);
Chapter 18 - ASP.NET Web Pages and Web Controls return 0;
Chapter 19 - ASP.NET Web Applications
}
Chapter 20 - XML Web Services
Index
List of Figures
List of
Figure 12-6: Custom serialization
SOURCE The CustomSerialization project is included under the Chapter 12 subdirectory.
CODE
So at this point you should have a solid handle on the .NET serialization process. Understand that this
C# and the .NET Platform, Second Edition
technology is useful in a variety of circumstances, even when you are not building a distributed application. For
by Andrew Troelsen ISBN:1590590554
example, you could save applicationspecific data, user preferences, or whatnot with these same techniques.
Apress © 2003 (1200 pages)
As you would expect however, the .NET Remoting layer makes substantial use of these serialization primitives.
This comprehensive text starts with a brief overview of the
Next question: what exactly is remoting?
C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table of Contents
C# and the .NET Platform, Second Edition
Introduction
Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy of .NET
Chapter 2 - Building C# Applications
Part Two - The C# Programming Language
Chapter 3 - C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections
Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
List of Figures
List of Tables
Defining .NETC# andRemotingthe .NET Platform, Second Edition
by Andrew Troelsen |
ISBN:1590590554 |
As you recall from your reading in Chapter 10, an application domain is a logical boundary for a .NET
Apress © 2003 (1200 pages)
assembly, which is itself contained within a Process type. Understanding these concepts is critical when
This comprehensive text starts with a brief overview of the
discussing distributedC# languagecomputingandunderthen quickly.NET, movesgiven thatto keyremotingtechnicalis nothingand more than the act of two pieces of softwarearcommunicatinghitect ral issuesacrossfor .NETapplicationdevelopersdomains. . The two application domains in question could be physically configured in any of the following manners:
Table Twoof Contentsapplication domains in the same process (and thus on the same machine)
C# and the .NET Platform, Second Edition
Two application domains in separate processes on the same machine
Introduction
Part One - Introducing C# and the .NET Platform
Two application domains in separate processes on different machines
Chapter 1 - The Philosophy of .NET
ChapterGiven these2 - Buildingthree possibilities,C# Applicatiyounscan see that remoting does not necessarily need to involve two (or
Partmore)Twonetworked- The C# Prcomputersgramming. InLanguagefact, each of the examples presented in this chapter can be successfully Chapterrun on 3a single,- C# Languagestand-aloneFundamentalsmachine (but don't worry, you'll see how to distribute your applications across
machine boundaries as well).
Chapter 4 - Object-Oriented Programming with C#
Chapter 5 - Exceptions and Object Lifetime
Regardless of the distance between two software entities, it is common to refer to each agent using the
Chapter 6 - Interfaces and Collections
terms client and server. Simply put, the client is a piece of software that attempts to interact with a remote
Chapter 7 - Callback Interfaces, Delegates, and Events
object. The server is the software agent that provides remote access to select objects. As you will see over
Chapter 8 - Advanced C# Type Construction Techniques
the course of this chapter, a .NET server application is quite a different beast from that of classic DCOM.
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Index
List of Figures
List of Tables