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=null;
	try
	{
	XmlSerializer serializer=new XmlSerializer(message.GetType());
	netWorkStream=new NetworkStream(_clientSocket);
	Stream stream=(Stream)netWorkStream;
	serializer.Serialize(stream,message); 
	}
	finally
	{
		netWorkStream.Close();
	}
}

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 DeserializeMessage(ref NetworkStream networkStream,ref
Message message)
{
	XmlSerializer deserializer=null;
	bool result=false;
	int count=0;
	Byte []buffer=new Byte[BUFFER_SIZE];
	deserializer=new XmlSerializer(typeof(MessageContainer));
	count=networkStream.Read(buffer,0,buffer.Length);
	if(count <= 0)
	{
		message=null;
		return false;
	}
	MemoryStream memoryStream=null;
	memoryStream=new MemoryStream(buffer,0,count); 
	message= ((MessageContainer)deserializer.Deserialize(memoryStream));
//Get An Exception here as the type is ChatMessage and i am expecting
a message
}
0
11/14/2003 11:08:43 AM
dotnet.xml 7266 articles. 0 followers. Follow

1 Replies
963 Views

Similar Articles

[PageSpeed] 12

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( MessageContainer ), 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 MessageContainer
{
    [XmlElement(typeof(FileMessage))]
    [XmlElement(typeof(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


"Bluetears76" <bluetears76@yahoo.com> wrote in message
news:3c1cfe69.0311140308.284ef512@posting.google.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=null;
> try
> {
> XmlSerializer serializer=new XmlSerializer(message.GetType());
> netWorkStream=new NetworkStream(_clientSocket);
> Stream stream=(Stream)netWorkStream;
> serializer.Serialize(stream,message);
> }
> finally
> {
> netWorkStream.Close();
> }
> }
>
> 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 DeserializeMessage(ref NetworkStream networkStream,ref
> Message message)
> {
> XmlSerializer deserializer=null;
> bool result=false;
> int count=0;
> Byte []buffer=new Byte[BUFFER_SIZE];
> deserializer=new XmlSerializer(typeof(MessageContainer));
> count=networkStream.Read(buffer,0,buffer.Length);
> if(count <= 0)
> {
> message=null;
> return false;
> }
> MemoryStream memoryStream=null;
> memoryStream=new MemoryStream(buffer,0,count);
> message= ((MessageContainer)deserializer.Deserialize(memoryStream));
> //Get An Exception here as the type is ChatMessage and i am expecting
> a message
> }


0
11/17/2003 2:51:27 AM
Reply:

Similar Artilces:

Printing objects on a worksheet
I have a simple macro that sets the pagesetup properties (more or less just the printarea) and then prints the worksheet. Every time I do this two of the objects move - a command button and a spinner; it doesn't matter if the properties are set to print or not, they move over to the left. Is there some property I should be setting to anchor to a cell or something? Regards -- Les Gordon Hi Less http://support.microsoft.com/d�efault.aspx?scid=kb;EN-US;8389�10 Controls move to the left of the worksheet in Microsoft Excel 2002 -- Regards Ron de Bruin http://www.rondebruin.nl &quo...

XmlSerializer Collection with Collections
Hello I got this working but it is not how I really want it, basically I have an xml file which has a root of <test> and can be filled with 3 different types of <question> elements with different attributes, all share a base set of 4, one of the question types can have children with <option> elements, this is how the xml looks after serialization.... If you notice there is an extra <SelectionList> around the <option>'s in the final <question>, how can I write my class so I don't have this extra <SelectionList> element....my class follows, you ...

In-line objects
I'm trying to design a questionnaire and I've used the drawing tools to put in a lot of lines and boxes. I'd like these to stay where they are, but I'm having some problems. For example: There is a question with some lines below it for the answer. When I make the lines in-line objects they become invisible and move against the left margin. Then if I try to resize them I can't get them perfectly straight again. Please help! When you re-size, hold the shift key down. Working with graphics and objects http://office.microsoft.com/en-us/assistance/CH062524651033.a...

XmlSerializer
I'm having a basic problem with the XmlSerializer & i'm at my wits end trying to sort it out i have a basic clas <Serializable()> Class Tes Public Name as Strin End Clas when this serializes i wan <Test><Name>Value</Name></Test the problem is if i use the XmlSerializer clas Dim t as Tes t.Name="Value Dim sb As New StringBuilde Dim sw As New StringWriter(sb Dim Serializer As New XmlSerializer(Message.GetType Serializer.Serialize(sw, t Serializer = Nothin Console.Write(sb.ToStr...

Can't Assign Value to this Object
I think I've seen this problem before but I can't remember the reason or solution. I have a form (in add mode) whose record source is a single table. For most fields on the form, the user will input data, but for a couple of fields I am trying to populate them with the values of global variables. I've got the global variables working (I can assign one to an unbound text box on the form), but when I try to assign the variable value to a bound text box, I get an error message that "Run-time error 2448: You can't assign a value to this object". Here is ...

XmlSerializer and shared objects (or How to generate IDREFs using XmlSerializer)
This is a multi-part message in MIME format. ------=_NextPart_000_007F_01C34AC1.11D4FB20 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable 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): <...

The operation failed. An object cannot be found. Yet again.
Last Thursday, my outlook 2007 (Vista machine) began to present this error while trying to send an e-mail. I am able to receive e-mails. Troubleshooting to date: 1. New profile. 2. Uninstall/reinstall. 3. Point to different .pst file. 4. Every recommendation on MS help/Google query response files. No joy. Went to my admin user profile, set up an e-mail account and pointed to the original .pst file. Works like a charm. However, trying to attach files from my project files to send to clients forces me to save those files to an external back-up drive, switch users, ...

Sheet Protection / Edit Objects 12-05-09
I have a spreadsheet with multiple objects that I'm trying to lock. My problem is I also have cells that I need to have comment insertion capabilites. When going to Tools/Protection/Protect Sheet and allow Edit Objects is checked I can insert a comment. However, it also allows the other objects on the sheet to be accessed. Is there a way to allow the Edit Objects option in a specified range of cells and still protect the sheet? Perplexed.... Keyrookie -- Keyrookie You would have to have that range without the checkbox for locked checked: FORMAT CELLS>PR...

Static CMap object #2
Hi all, Excuse but the other message is wrong I've declared in my .h file the following CMap type : typedef CMap<CString, CString&, MyClass*, MyClass*&> Map; ... ... class AnotherClass { ... public: static Map BuilderMap; ... ... static void Register(CString name, MyClass* instance); }; In one of my CPP file call the Register method as following: AnotherClass::Register(_T("TEST"), this); The code of Register method is : void AnotherClass::Register(CString name, MyClass* instance) { AnotherClass::BuilderMap.SetAt(name, instance); } When linking my project there t...

All CRM objects have been updated in one weekend. Not sure how.
I noticed that every Lead, Opp, Account and Contact has a Modified On date of this past Saturday or more recently. The records with Saturday's modified date don't show any particular changes, just the Modified On date and the Modified By user. It's more than a trivial issue. There are business reasons for knowing when things are being updated. Some of these Modified By values are disabled, former users. They were the original creators of the objects. CRM is running on its own server. This SQL Server is also running Veritas Backup Exec. did these users create any work...

Chart Object and Worksheet Object
What are the difference? I insert a Excel chart into PPT by Insert>object>create from file>[browse]... It always comes out as a worksheet object whether I get a chart of the data. Whereas, Edit>Paste special method clearly differenciate a chart object from a worksheet object. I know I could convert to either way but any difference? In article <CE92D095-8E17-4AD4-85B9-317AC15A13BF@microsoft.com>, Win wrote: > What are the difference? > > I insert a Excel chart into PPT by Insert>object>create from file>[browse]... As I suggested earlier...

disconnected chart objects
Consider the following: A B 1 15 15 2 25 15 3 25 35 4 15 35 5 15 15 6 7 45 45 8 75 45 9 75 105 10 45 105 11 45 45 In Excel with row 6 present & blank you get two disconnected boxes using XY-scatter format with lines and points. If you remove the empty row 6 you get the boxes plus a line connecting points 15,15 and 45,45. In Open Office Calc (OOC), you get the boxes connected in either case unless you move one of the y sets to column B (creating two series.) Although this is an Excel group, since I haven't been able to get any re...

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=null; try { XmlSerializer serializer=new XmlSerializer(message.GetType()); netWorkStream=new NetworkStream(_clientSocket); Stream stream=(Stream)netWorkStream; serializer.Serialize(stream,message); } finally { netWorkStrea...

"Object or class does not support the set of events" Quick Question
All, I built a MS Access database in MS Access 2003, which I have set up in a shared folder. I have a form with some standard components such as text boxs, bottons. When a user updates the form I wish to record the time/date and username in the record. I have posted a copy of the code I'm using for the "BeforeUpdate" event below. Now this works fine on my machine and updates without a problem. However when a user on another machine (also using MS Access 2003) tries to update the same field, he gets the following error: "The expression Before Update you entered as the eve...

Worksheets Inheriting Contents
Hi All, I'm currently working on creating a set of specifications using Excel These specifications are contained within a single Excel spreadshee which contain multiple worksheets, each relating to a different aspec of the form (say calculations, form rules, dependencies). The proble is that anytime you make a change to one form, say you change text, o add another column, you must make the corresponding changes in all th other tabs. This can be very time consuming - especially if there are tabs. My question is this: Is it possible to create a parent 'Look and Feel worksheet and hav...

XMLSerializer Serialize
Iam trying to create a xml file by serializing a custom business object. Iam using a xmltextwriter, but the problem there are invalid characters at the end of the generated file anyone knows a way around it ? tia Dim myStream As New IO.MemoryStream Dim myXMLWriter As New System.Xml.XmlTextWriter(myStream, System.Text.Encoding.UTF8) myXMLWriter.Formatting = System.Xml.Formatting.Indented Dim myShipments As OrderShipments myShipments = CType(myOrder.OrderAddresses(0), COrderAddress).Shipments myShipments.ToXML(myXMLWriter) ...

XmlSerializer help
Hi, I have a class: public class Note { public string name; public string information; } And i Serialize this class, but want to Serialize it to an XmlDocument which will contain many of these elements. How do i do this? Thank you, Tim. Timothy, take a look at Chris Lovett's XmlNodeWriter on www.gotdotnet.com [0]. Simply pass the node where you want to insert the serialized XML into the XmlDocument to an XmlNodeWriter and pass the XmlNodeWriter to the Serialize method. -- HTH Christoph Schittko [MVP] Software Architect, .NET Mentor [0] http://gotdotnet.com/Communit...

read-only objects (CRM 3)
I'm building an Order workflow that's triggered by a change to Canceled status. It generate several tasks and emails, and I need it to update a custom date field on the order with the current date. The update entity portion of the workflow fails because once the order is cancelled the field is read-only. Here's the question: How to I make a specific field not read-only once the order is cancelled? -- Tracy Bourgoine, IT Analyst On Nov 5, 5:59=A0am, TracyB <Tra...@discussions.microsoft.com> wrote: > I'm building an Order workflow that's triggered by a...

problem inheriting from XmlDocument and XmlElement
hello there everyone.. I have created a class called "ProcessLog" inheriting from XmlDocument and two classes ("UploadedItem", "ProcessError") inheriting from XmlElement. I then have two classes ("UploadedTemplate", "UploadedPresentation") which inherit from "UploadedItem")... so far so good. I have overriden the CreateElement method of "ProccessLog" and it creates the correct elements as expected. The problem is I need to override SelectSingleNode and SelectNodes to return types "UploadedPresentation", &qu...

SeriesCollection object in Excel 2007 and 2003
I created a program that in Excel 2007 that assigns an array to a new series SeriesCollection.XValues and SeriesCollection.Values. It then shows up on the chart. In Excel 2003, there are apparently limits on how long the series information can be. Is there any fix from MS on this or a way around it that doesn't involve referencing a data range on the worksheet? It dynamically adds series, and I'd prefer to not have them on the worksheet. I have tried transposing and still run into limits and get errors. I have also tried putting the in .xvalues as array(x(1), x(2), x(3),...

plugin object in C#
How can I make plugin object in C# ? Thanks :) On 12-05-2010 15:20, Mr. X. wrote: > How can I make plugin object in C# ? ..NET has excellent possibilities for creating plugins. From simple load of class and instantiation via reflection over use og IoC framework like Spring.NET and a config file to the huge add-in framework. Arne Give me an example, please. Thanks :) "Arne Vajhøj" <arne@vajhoej.dk> wrote in message news:4beb07d2$0$280$14726298@news.sunsite.dk... > On 12-05-2010 15:20, Mr. X. wrote: >> How can I make plugin object in C# ...

Need help using objects and charts together
I have a line chart that tracks data for a 12 month period. So as not to mess up the chart, I added a drawn line and text box for information covering only the two most recent months. When I click in the sheet anywhere off the chart, you can see the line, but when I click on the chart anywhere the drawn objects disappear. I am copying the charts to a powerpoint presentation and the drawn objects also don't transfer to that. I have tried selecting the items and telling it to move forward or to the front, I have also tried telling the chart to move to the back. Neither of these o...

Problems with XmlSerializer and namespaces
I have an object, Teacher, that has a namespace. Let's call it http://foo. Teacher has a child object called Name, composed of String first, middle, last, etc. Problem I have is when I try to deserialize it. When I deserialize a single Teacher, it works when I put the namespace on the Teacher element. However, if I have just the namespace on Teacher, it will deserialize fine as Teacher. *However*, if I try to deserialize an ArrayOfTeacher, Teacher.Name doesn't deserialize (it's null); without the array, it's OK. What I wound up doing was serializing both a Teacher ...

Save Word with embedded objects as a PDF
Is there a way to perserve an embedded object (excel etc.) in Word when saving as a PDF? You mean preserve the embedded object so that it is active in the PDF (meaning that you can open it in the PDF file)? No. -- Stefan Blom Microsoft Word MVP "tjv" <tjv@discussions.microsoft.com> wrote in message news:8BBD79B9-4809-4DC9-BA30-B5947CA12020@microsoft.com... > Is there a way to perserve an embedded object (excel etc.) in Word when > saving as a PDF? ...

identical smtp address - more than one user object
I have just come back form a client site, inherited, where we were trying to work out why certain email addresses were not working as expected. Basically they had a user object in AD - user@domain.com - with the primary smtp set as user@domain.com with no delivery options set. However when I examined another user object in the same active directory I found the identical smtp address listed in their email address list. How is this possible? I was under the impression that you would not be allowed to create the smtp address as it was already in existence. SBS 2003 BTW. ...