Marshal-by-value objects are not remote objects. By-value objects are marked with the SerializableAttribute or implement the ISerializable interface. When a serializable object is requested from a remote server, the object is serialized into an XML or binary format and transmitted to the requester. Only data is shipped. Thus, if the serialized object has methods that need to be invoked, the code must exist on the recipient device. This is similar to how Web Services work. A Web Service returns an XML representation of an object that is comprised of data only. If you want to invoke operations on the data, you need the assembly that contains the methods. (This approach is used to return serialized data sets from an XML Web Service.)
In this section I offer another example using the Factory and Trade classes. The Factory class is a MarshalByRefObject that returns a by-value object, an instance of the serialized Trade class. In this example I need to share the implementation of the Trade class between client and server. The server will serialize a representation of the Trade class, and the client will deserialize the representation. Implicitly the deserialized data will be mapped to the shared implementation of the Trade class. The end result is that we get the data from the server—passing just the data—and reconstitute the actual object on the client.
On top of the basic example, I will provide an example of a customer version of the Trade class that implements ISerializable.
Employing By-Value Classes
In our revised example the Factory class is a marshal-by-reference class. (Recall this means that it inherits from MarshalByRefObject.) Further, I have converted the implementation of the Trade class to be a marshal-by-value class. Both classes inherit from their respective interfaces: Trade implements ITrade, and Factory implements IFactory. Interface.dll, containing the interfaces ITrade and IFactory, is shared by both client and server. On the server we configure and register the Factory class as remotable by using a .config file (as demonstrated in Listing 8.6) to manage registration of the server-activated class. As a result, only the Trade class contains modification. Listing 8.9 shows the complete, revised listing of the Trade class as defined on the server. The absence of MarshalByRefObject inheritance and the SerializableAttribute indicates that the Trade class is a by-value object in this listing.
Listing 8.9 Implementing the Trade Class as a By-Value Object
1: <Serializable()>_ 2: Public Class Trade 3: 4: Private FCustomerId As Integer 5: Private FNumberOfShares As Double 6: Private FEquityName As String 7: Private FEquityPrice As Double 8: Private FCommission As Double 9: Private FRepId As String 10: 11: Public Property CustomerId() As Integer 12: Get 13: Return FCustomerId 14: End Get 15: Set(ByVal Value As Integer) 16: FCustomerId = Value 17: End Set 18: End Property 19: 20: Public Property NumberOfShares() As Double 21: Get 22: Return FNumberOfShares 23: End Get 24: Set(ByVal Value As Double) 25: FNumberOfShares = Value 26: End Set 27: End Property 28: 29: Public Property EquityName() As String 30: Get 31: Return FEquityName 32: End Get 33: Set(ByVal Value As String) 34: Console.WriteLine("EquityName was {0}", FEquityName) 35: FEquityName = Value 36: Console.WriteLine("EquityName is {0}", FEquityName) 37: Console.WriteLine([Assembly].GetExecutingAssembly().FullName) 38: 39: End Set 40: End Property 41: 42: Public Property EquityPrice() As Double 43: Get 44: Return FEquityPrice 45: End Get 46: Set(ByVal Value As Double) 47: FEquityPrice = Value 48: End Set 49: End Property 50: 51: ReadOnly Property Cost() As Double 52: Get 53: Return FEquityPrice * _ 54: FNumberOfShares + FCommission 55: End Get 56: End Property 57: 58: Property Commission() As Double 59: Get 60: Return FCommission 61: End Get 62: Set(ByVal Value As Double) 63: FCommission = Value 64: End Set 65: End Property 66: 67: Property RepId() As String 68: Get 69: Return FRepId 70: End Get 71: Set(ByVal Value As String) 72: FRepId = Value 73: End Set 74: End Property 75: 76: End Class
After a quick observation you will see that only the first couple of lines have changed and all the interface implementation code has been removed. Line 1 shows the use of the SerializableAttribute (defined in the System namespace), and I removed the statement Inherits MarshalByRefObject. This is all you need to do to indicate that an object can be sent back and forth in a serialized form, such as an XML document.
Additionally, the IFactory interface (not shown here, see Listing 8.1) has been modified to return a Trade value rather than the ITrade interface, and the ITrade interface—no longer required—has been removed from the Interface.vb source file.
Revising the Client to Use the By-Value Object
The client has to change very little to accommodate the marshal-by-value object. Factory is the remote object and it returns the Trade type, which we have referenced in both the client and the server. Because we are using a server-activated object—Factory—we only need to get an instance of the factory and invoke the GetTrade method. .NET automatically serializes the Trade object, and our locally declared Trade variable can handle the deserialized instance. We do not have to manage serialization on the server or deserialization on the client; this is automatic. Listing 8.10 contains the client code for the marshal-by-value Trade object.
Listing 8.10 Client Code for the By-Value Trade Object
1: Imports System 2: Imports System.Runtime.Remoting 3: Imports System.Runtime.Remoting.Channels 4: Imports System.Runtime.Remoting.Channels.Http 5: Imports System.Reflection 6: Imports [Interface] 7: 8: Public Class Form1 9: Inherits System.Windows.Forms.Form 10: 11: [ Windows Form Designer generated code ] 12: 13: Private Generator As Generator 14: Private trade As Trade 15: 16: Private Sub Form1_Load(ByVal sender As System.Object, _ 17: ByVal e As System.EventArgs) Handles MyBase.Load 18: 19: Dim channel As HttpChannel = New HttpChannel() 20: ChannelServices.RegisterChannel(channel) 21: 22: Dim Instance As Object = _ 23: Activator.GetObject(GetType(IFactory), _ 24: "http://localhost:8080/Factory.soap") 25: 26: Dim Factory As IFactory = CType(Instance, IFactory) 27: trade = Factory.GetTrade(1234) 28: 29: trade.EquityName = "MSFT" 30: Debug.WriteLine(trade.Cost.ToString()) 31: Generator = New Generator(Me, _ 32: GetType(Trade), trade) 33: Generator.AddControls() 34: 35: End Sub 36: 37: End Class
Note that in the example the trade variable (line 14) is declared as a Trade type. We are actually getting a serialized form of the Trade object from the server, and the client is automatically deserializing the object returned by the Factory method and reconstituting it as a Trade object. Because we have an implementation of the Trade class shared between client and server, this works nicely.
The balance of the code registers the server-activated Factory and uses the Generator class I defined to create a user interface. You can download Example4\Client.sln to experiment with this code.
Implementing ISerializable
The default behavior of the SerializableAttribute is to serialize all public properties. In a serialized form they are transmitted as public fields. However, because we have the binary code on both the client and the server, the deserialized object can be reconstituted as a complete object. Completeness, here, means that we have properties, fields, methods, attributes, and events.
Generally this default behavior is sufficient. However, it may be insufficient if you want to serialize additional data that may not be part of the public properties but is beneficial to the class or intensive to calculate. Whenever you need extra data serialized you can get it by implementing the System.Runtime.Serialization.ISerializable interface. The help documentation tells you that you need to implement GetObjectData, which is the serialization method. What is implied is that you need the symmetric deserialization behavior. Deserialization is contrived in the form of a constructor that initializes an object based on serialized data.
In order to demonstrate custom serialization in the Example4\Client.sln file I added a contrived value to the Trade class used for debugging purposes. This contrived field, DateTime, holds the date and time when the object was serialized. When a Trade object is serialized, I include the current DateTime value. When the object is deserialized, the DateTime value is written to the Debug window. To affect the custom serialization I needed to change only the shared class we have been using all along. The complete listing of the Trade class is shown in Listing 8.11 with the revisions (compared with Listing 8.9) in bold font. (The actual source is contained in Example4\Interface\Interface.vb.)
Listing 8.11 Implementing Custom Serialization for .NET Remoting
1: <Serializable()>_ 2: Public Class Trade 3: Implements ISerializable 4: 5: Private FCustomerId As Integer 6: Private FNumberOfShares As Double 7: Private FEquityName As String 8: Private FEquityPrice As Double 9: Private FCommission As Double 10: Private FRepId As String 11: 12: Public Sub New() 13: End Sub 14: 15: Public Sub New(ByVal info As SerializationInfo, _ 16: ByVal context As StreamingContext) 17: 18: Debug.WriteLine("Started deserializing Trade") 19: FCustomerId = CType(info.GetValue("CustomerId", _ 20: GetType(Integer)), Integer) 21: FNumberOfShares = CType(info.GetValue("NumberOfShares", _ 22: GetType(Double)), Double) 23: 24: FEquityName = CType(info.GetValue("EquityName", _ 25: GetType(String)), String) 26: 27: FEquityPrice = CType(info.GetValue("EquityPrice", _ 28: GetType(Double)), Double) 29: 30: FCommission = CType(info.GetValue("Commission", _ 31: GetType(Double)), Double) 32: 33: FRepId = CType(info.GetValue("RepId", _ 34: GetType(String)), String) 35: 36: Dim SerializedAt As DateTime _ 37: = CType(info.GetValue("SerializedAt", _ 38: GetType(DateTime)), DateTime) 39: 40: Debug.WriteLine(String.Format( _ 41: "{0} was serialized at {1}", _ 42: Me.GetType.Name(), SerializedAt)) 43: 44: Debug.WriteLine("Finished deserializing Trade") 45: End Sub 46: 47: Protected Sub GetObjectData( _ 48: ByVal info As SerializationInfo, _ 49: ByVal context As StreamingContext _ 50: ) Implements ISerializable.GetObjectData 51: 52: Console.WriteLine("Started serializing Trade") 53: 54: info.AddValue("CustomerId", FCustomerId) 55: info.AddValue("NumberOfShares", FNumberOfShares) 56: info.AddValue("EquityName", FEquityName) 57: info.AddValue("EquityPrice", FEquityPrice) 58: info.AddValue("Commission", FCommission) 59: info.AddValue("RepId", FRepId) 60: info.AddValue("SerializedAt", DateTime.Now) 61: 62: Console.WriteLine("Finished serializing Trade") 63: End Sub 64: 65: 66: Public Property CustomerId() As Integer 67: Get 68: Return FCustomerId 69: End Get 70: Set(ByVal Value As Integer) 71: FCustomerId = Value 72: End Set 73: End Property 74: 75: Public Property NumberOfShares() As Double 76: Get 77: Return FNumberOfShares 78: End Get 79: Set(ByVal Value As Double) 80: FNumberOfShares = Value 81: End Set 82: End Property 83: 84: Public Property EquityName() As String 85: Get 86: Return FEquityName 87: End Get 88: Set(ByVal Value As String) 89: Console.WriteLine("EquityName was {0}", FEquityName) 90: FEquityName = Value 91: Console.WriteLine("EquityName is {0}", FEquityName) 92: Console.WriteLine([Assembly].GetExecutingAssembly().FullName) 93: End Set 94: End Property 95: 96: Public Property EquityPrice() As Double 97: Get 98: Return FEquityPrice 99: End Get 100: Set(ByVal Value As Double) 101: FEquityPrice = Value 102: End Set 103: End Property 104: 105: ReadOnly Property Cost() As Double 106: Get 107: Return FEquityPrice * _ 108: FNumberOfShares + FCommission 109: End Get 110: End Property 111: 112: Property Commission() As Double 113: Get 114: Return FCommission 115: End Get 116: Set(ByVal Value As Double) 117: FCommission = Value 118: End Set 119: End Property 120: 121: Property RepId() As String 122: Get 123: Return FRepId 124: End Get 125: Set(ByVal Value As String) 126: FRepId = Value 127: End Set 128: End Property 129: 130: End Class
TIP
You need to include the SerializableAttribute even when you are implementing the ISerializable interface. Remember to add an Imports statement for System.Runtime.Serialization, or use the completely qualified name for the ISerializable interface when performing custom serialization.
Serialization and deserialization in Listing 8.11 are constrained to lines 15 through 63. The recurring pattern is a constructor and a method named GetObjectData. Both the constructor and GetObjectData take SerializationInfo and StreamingContext arguments. The constructor reads the streamed field values, and the serialization method, GetObjectData, writes the fields to be streamed. Since you will be writing both the serializer and deserializer you will know the order and type of the arguments streamed.
To serialize an object, write the fields using the SerializationInfo object in the GetObjectData method. Call SerializationInfo.SetValue, passing a name for the value and the value itself. For example, line 59 passes the literal "RepId" and the value of the field FRepId. When you deserialize the object in the constructor, use the SerializationInfo argument and call GetValue. Pass the name used to serialize the object and the type information for that value. It is a good practice to perform an explicit type conversion on the return value since GetValue returns an Object type. For example, lines 33 and 34 of Listing 8.11 call GetValue, passing the literal "RepId" and the Type object for the String class, and perform the cast to String.
Line 60 demonstrates how we can serialize an arbitrary value, SerializedAt. Lines 36 through 38 demonstrate how we can deserialize that same value, perform the type conversion, and assign the value to a local variable (or a field). In lines 40 through 42 I use the value SerializedAt to indicate when the client was serialized. Perhaps such a value could be used as a rough measure of latency. If you compared the SerializedAt time with the current time, you would know how long the serialization and deserialization behavior took in a single instance.
Comparing By-Reference to By-Value Objects
There are two ways to pass objects around: by value and by reference. By-reference objects are remoted objects that inherit from MarshalByRefObject. This means that they actually exist on the remote server. By-value objects are copied to the client and use the SerializableAttribute. It's important to decide when to use either technique.
Pass objects by reference to prevent a large object from clogging network bandwidth. You will also have to pass objects by reference when the object refers to resources that exist in the server domain. For example, C:\winnt\system32 on the client is a completely different folder than C:\winnt\system32 on the server.
Consider passing objects by value when the data on the client does not need to be maintained on the server. For example, if we are simply reporting on trade information, we don't necessarily need a reference to a Trade object on the server. Using a by-value Trade object will reduce round-trips to the server since the code resides on the client.
Think of by-value objects as similar to the data returned by a Web application: It is disconnected. Think of by-reference objects as the connected model of programming.