473,725 Members | 2,075 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

XmlSerializer and inherited objects

Hi I have a hirachy of classes which are Message(base), then
FileMessage and ChatMessage (extended)

I want to serialize the objects and when i am deserizaling i dont know
if i am getting FileMessage or ChatMessage. So how to get that object
and use it
I have written following code for serialization
public void Send(Message message)
{
NetworkStream netWorkStream=n ull;
try
{
XmlSerializer serializer=new XmlSerializer(m essage.GetType( ));
netWorkStream=n ew NetworkStream(_ clientSocket);
Stream stream=(Stream) netWorkStream;
serializer.Seri alize(stream,me ssage);
}
finally
{
netWorkStream.C lose();
}
}

It send the message fine.
but when i deseralize the message i dont know which type of message it
is .. i,e, a FileMessage or a ChatMessage so i get an exception

following is the code of deserlizeation
public bool DeserializeMess age(ref NetworkStream networkStream,r ef
Message message)
{
XmlSerializer deserializer=nu ll;
bool result=false;
int count=0;
Byte []buffer=new Byte[BUFFER_SIZE];
deserializer=ne w XmlSerializer(t ypeof(MessageCo ntainer));
count=networkSt ream.Read(buffe r,0,buffer.Leng th);
if(count <= 0)
{
message=null;
return false;
}
MemoryStream memoryStream=nu ll;
memoryStream=ne w MemoryStream(bu ffer,0,count);
message= ((MessageContai ner)deserialize r.Deserialize(m emoryStream));
//Get An Exception here as the type is ChatMessage and i am expecting
a message
}
Nov 12 '05 #1
1 4319
Bluetears76,

I noticed a few things in the code you posted:

* You don't use the same type when you instantiate the XmlSerializer to
serialize and deserialize the message. Both of them should probably look
like:
XmlSerializer = new XmlSerializer( typeof( Message ) );
Maybe it should be typeof( MessageContaine r ), but I can't tell without
knowing more.

To make sure that XmlSerializer can process FileMessage and ChatMessage, you
need to decorate the MessageClass with XmlInclude attributes like this:

[XmlInclude( typeof( FileMessage ) )]
[XmlInclude( typeof( ChatMessage ) )]
public class Message{
// ...
}

Alternatively you might be able to do:
public class MessageContaine r
{
[XmlElement(type of(FileMessage) )]
[XmlElement(type of(ChatMessage) )]
public Message content;
// other stuff ...
}

* You are instantiating and XmlSerializer for every serialization and
deserialization operation. It's much more efficient to keep the
XmlSerializer around and re-use it.

* You are using ref in your method signatures. Are you going across
AppDomains with these methods? Is there any reason to do that? Crossing
AppDomain boundaries is a very expensive operation. I don't see a reason why
you need to do this here.

* Are you really building a loosely coupled app or is this in a tightly
coupled scenario where the BinaryFormatter might be the better choice. The
decisive criteria here would be: a) do you really need to transmit XML? b)
do both endpoint of the transmission always have the same assemblies with
the serialized types available? If the answer to a) is no and b) is yes then
the BinaryFormatter is the better choice.

--
HTH
Christoph Schittko [MVP]
Software Architect, .NET Mentor
"Bluetears7 6" <bl*********@ya hoo.com> wrote in message
news:3c******** *************** ***@posting.goo gle.com...
Hi I have a hirachy of classes which are Message(base), then
FileMessage and ChatMessage (extended)

I want to serialize the objects and when i am deserizaling i dont know
if i am getting FileMessage or ChatMessage. So how to get that object
and use it
I have written following code for serialization
public void Send(Message message)
{
NetworkStream netWorkStream=n ull;
try
{
XmlSerializer serializer=new XmlSerializer(m essage.GetType( ));
netWorkStream=n ew NetworkStream(_ clientSocket);
Stream stream=(Stream) netWorkStream;
serializer.Seri alize(stream,me ssage);
}
finally
{
netWorkStream.C lose();
}
}

It send the message fine.
but when i deseralize the message i dont know which type of message it
is .. i,e, a FileMessage or a ChatMessage so i get an exception

following is the code of deserlizeation
public bool DeserializeMess age(ref NetworkStream networkStream,r ef
Message message)
{
XmlSerializer deserializer=nu ll;
bool result=false;
int count=0;
Byte []buffer=new Byte[BUFFER_SIZE];
deserializer=ne w XmlSerializer(t ypeof(MessageCo ntainer));
count=networkSt ream.Read(buffe r,0,buffer.Leng th);
if(count <= 0)
{
message=null;
return false;
}
MemoryStream memoryStream=nu ll;
memoryStream=ne w MemoryStream(bu ffer,0,count);
message= ((MessageContai ner)deserialize r.Deserialize(m emoryStream));
//Get An Exception here as the type is ChatMessage and i am expecting
a message
}

Nov 12 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1774
by: Kevin Conroy | last post by:
I'm making a 6-tiered application that is using Xml to tie the various layers together in a very clean manner. I'm also trying to do this on the 1.1 Framework although I'm willing to switch to the 1.0 Framework if need be. One layer, which I call a Data Persistence Layer, uses the System.Xml.Serialization.XmlSerializer to transform our business/domain objects into the appropriate Xml format.
5
5427
by: Stuart Robertson | last post by:
I am trying to find a solution that will allow me to use XmlSerializer to serialize/deserialize a collection of objects where a given object is shared between two or more other objects, and not create duplicate XML representations of the shared object, but instead use IDREFs to refer to the shared object. The XML I'm trying to produce is as follows (where "href" is an IDREF): <?xml version="1.0" encoding="utf-8"?> <MyRootClass...
4
11398
by: Andy Neilson | last post by:
I've run across a strange behaviour with XmlSerializer that I'm unable to explain. I came across this while trying to use XmlSerializer to deserialize from a the details of a SoapException. This should have worked fine since the class in question was already being serialized and deserialized as part of a Web service interface. What I found was that by deserializing from an XmlNodeReader instead of an XmlTextReader, XML Serialization doesn't work...
3
9039
by: Bob Rundle | last post by:
I'm trying to serialize a class with XmlSerializer. This class implements the IEnumerable interface. I implemented the IEnumerable interface for reasons other than Xml serialization. However I find that the XmlSerializer, because I have an IEnumerable interface on this class, wants to ignore the public properties of this class and simply serialize an array of objects. I wand XmlSerializer to ignore the IEnumerable interface that I...
4
1991
by: Steve Long | last post by:
Hello, I hope this is the right group to post this to. I'm trying to serialize a class I've written and I'd like to be able to serialze to both binary and xml formats. Binary serialization is working fine but when I try to instantiate an XmlSerializer object with: Dim xmls As New XmlSerializer(GetType(CLayerDefinition)) I get the following error:
0
1105
by: Bluetears76 | last post by:
Now Hierarchy is that there is a class named "Student" There are two child classes "GraduateStudent" and "HighSchoolStudent". I worte the following code for serializing the student and deserializing. Now the problem is that as i do not know the type of Student while deserializing so i get an error on line student= (Student)deserializer.Deserialize(memoryStream); Any help will be highly appriciated
4
5412
by: Ultrakorne | last post by:
hi, i have some problems with my client talk to my server... i am using xmlserializer to serialize object and send them to the other side of the connection. I need to send / recive by both client and server. client after login waits all the time listening for objects on a thread, and sends objects on users events on the main thread. server waits connections, start a new thread for each connection and after validating login waits for...
3
3301
by: kimtherkelsen | last post by:
Hi, I want to send XML data from a server to some clients over a network connection using the TCP/IP protocol. If I send the XMLs as byte arrays I need to insert header information in the data to distinguish the XMLs from each other in the stream of data. Is there any way to avoid this (for instance by sending SOAP telegrams))? I have tried using the XMLSerializer.Serialize(stream) to serialize the XML telegrams and send them over the...
5
7261
by: =?Utf-8?B?RXRoYW4gU3RyYXVzcw==?= | last post by:
Hi, I am using XML serialization for the first time and I have noticed something unexpected. The object I am serializing contains a field private NumericSettings _numericSettings; public NumericSettings NumericSettings { get { return _numericSettings; } }
0
8870
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8746
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9390
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9161
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6692
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5997
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4505
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3211
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2150
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.