System.InvalidOperationException
Hi,
I get an exception when I run this code:
Code:
try
{
ArrayList arrayList = new ArrayList();
TicketBL ticket = new TicketBL();
arrayList = ticket.GetTicketsForOffline();
FileStream fs = new FileStream(FILE_PATH, FileMode.Create);
XmlSerializer serializer = new XmlSerializer(typeof(ArrayList));
serializer.Serialize(fs, arrayList); <--System.InvalidOperationException: There was an error generating the XML document.
fs.Close();
MessageBox.Show("List Pull complete");
}
catch (Exception ex)
{
MessageBox.Show("Error Pulling list", ex.ToString());
}
The file creates the .xml file but doesn't serialize the data.
Any thoughts?
Re: System.InvalidOperationException
1. Don't use ArrayList. That class has been obsolete since generics debuted in .NET 2.0
2. You cannot serialize an ArrayList, hence the InvalidOperation exception. ArrayList is not a typed collection and thus cannot be serialized directly. You can use a generic collection List<T> or convert the ArrayList to an array.
Re: System.InvalidOperationException
Thanks BigED!!!
Resulting code:
Code:
try
{
TicketBL ticket = new TicketBL();
ArrayList arrList = new ArrayList();
arrList = ticket.GetTicketsForOffline();
// Convert ArraList to List type
List<TicketVO> listResult = new List<TicketVO>(arrList.Count);
foreach (TicketVO tickets in arrList)
{
listResult.Add(tickets);
}
FileStream fs = new FileStream(FILE_PATH, FileMode.Create);
XmlSerializer serializer = new XmlSerializer(typeof(List<TicketVO>));
serializer.Serialize(fs, listResult);
fs.Close();
MessageBox.Show("List Pull complete");
}
catch (Exception ex)
{
MessageBox.Show("Error Pulling list", ex.ToString());
}
Re: System.InvalidOperationException
You're welcome. I would suggest a couple more changes though...
Code:
// I would make GetTicketsForOffline a static method instead of an instance method
ArrayList arrList = new TicketBL().GetTicketsForOffline();
// there are fancier ways to do this with LINQ, but this is fine
List<TicketVO> listResult = new List<TicketVO>();
foreach (TicketVO ticket in arrList)
{
listResult.Add(ticket);
}
// using this pattern ensures that the stream is disposed.
// if an error had occurred before you called Close previously
// you would have left the file with an open handle and perhaps
// not flushed the contents to disk.
using (FileStream fs = new FileStream(FILE_PATH, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<TicketVO>));
serializer.Serialize(fs, listResult);
}
MessageBox.Show("List Pull complete");
Re: System.InvalidOperationException
I will follow your advise... Thanks Again!