Search Results

Search found 34 results on 2 pages for 'ixmlserializable'.

Page 1/2 | 1 2  | Next Page >

  • IXmlSerializable Dictionary

    - by Shimmy
    I was trying to create a generic Dictionary that implements IXmlSerializable. Here is my trial: Sub Main() Dim z As New SerializableDictionary(Of String, String) z.Add("asdf", "asd") Console.WriteLine(z.Serialize) End Sub Result: <?xml version="1.0" encoding="utf-16"?><Entry key="asdf" value="asd" /> I placed a breakpoint on top of the WriteXml method and I see that when it stops, the writer contains no data at all, and IMHO it should contain the root element and the xml declaration. <Serializable()> _ Public Class SerializableDictionary(Of TKey, TValue) : Inherits Dictionary(Of TKey, TValue) : Implements IXmlSerializable Private Const EntryString As String = "Entry" Private Const KeyString As String = "key" Private Const ValueString As String = "value" Private Shared ReadOnly AttributableTypes As Type() = New Type() {GetType(Boolean), GetType(Byte), GetType(Char), GetType(DateTime), GetType(Decimal), GetType(Double), GetType([Enum]), GetType(Guid), GetType(Int16), GetType(Int32), GetType(Int64), GetType(SByte), GetType(Single), GetType(String), GetType(TimeSpan), GetType(UInt16), GetType(UInt32), GetType(UInt64)} Private Shared ReadOnly GetIsAttributable As Predicate(Of Type) = Function(t) AttributableTypes.Contains(t) Private Shared ReadOnly IsKeyAttributable As Boolean = GetIsAttributable(GetType(TKey)) Private Shared ReadOnly IsValueAttributable As Boolean = GetIsAttributable(GetType(TValue)) Private Shared ReadOnly GetElementName As Func(Of Boolean, String) = Function(isKey) If(isKey, KeyString, ValueString) Public Function GetSchema() As System.Xml.Schema.XmlSchema Implements System.Xml.Serialization.IXmlSerializable.GetSchema Return Nothing End Function Public Sub WriteXml(ByVal writer As XmlWriter) Implements IXmlSerializable.WriteXml For Each entry In Me writer.WriteStartElement(EntryString) WriteData(IsKeyAttributable, writer, True, entry.Key) WriteData(IsValueAttributable, writer, False, entry.Value) writer.WriteEndElement() Next End Sub Private Sub WriteData(Of T)(ByVal attributable As Boolean, ByVal writer As XmlWriter, ByVal isKey As Boolean, ByVal value As T) Dim name = GetElementName(isKey) If attributable Then writer.WriteAttributeString(name, value.ToString) Else Dim serializer As New XmlSerializer(GetType(T)) writer.WriteStartElement(name) serializer.Serialize(writer, value) writer.WriteEndElement() End If End Sub Public Sub ReadXml(ByVal reader As XmlReader) Implements IXmlSerializable.ReadXml Dim empty = reader.IsEmptyElement reader.Read() If empty Then Exit Sub Clear() While reader.NodeType <> XmlNodeType.EndElement While reader.NodeType = XmlNodeType.Whitespace reader.Read() Dim key = ReadData(Of TKey)(IsKeyAttributable, reader, True) Dim value = ReadData(Of TValue)(IsValueAttributable, reader, False) Add(key, value) If Not IsKeyAttributable AndAlso Not IsValueAttributable Then reader.ReadEndElement() Else reader.Read() While reader.NodeType = XmlNodeType.Whitespace reader.Read() End While End While reader.ReadEndElement() End While End Sub Private Function ReadData(Of T)(ByVal attributable As Boolean, ByVal reader As XmlReader, ByVal isKey As Boolean) As T Dim name = GetElementName(isKey) Dim type = GetType(T) If attributable Then Return Convert.ChangeType(reader.GetAttribute(name), type) Else Dim serializer As New XmlSerializer(type) While reader.Name <> name reader.Read() End While reader.ReadStartElement(name) Dim value = serializer.Deserialize(reader) reader.ReadEndElement() Return value End If End Function Public Shared Function Serialize(ByVal dictionary As SerializableDictionary(Of TKey, TValue)) As String Dim sb As New StringBuilder(1024) Dim sw As New StringWriter(sb) Dim xs As New XmlSerializer(GetType(SerializableDictionary(Of TKey, TValue))) xs.Serialize(sw, dictionary) sw.Dispose() Return sb.ToString End Function Public Shared Function Deserialize(ByVal xml As String) As SerializableDictionary(Of TKey, TValue) Dim xs As New XmlSerializer(GetType(SerializableDictionary(Of TKey, TValue))) Dim xr As New XmlTextReader(xml, XmlNodeType.Document, Nothing) Return xs.Deserialize(xr) xr.Close() End Function Public Function Serialize() As String Dim sb As New StringBuilder Dim xw = XmlWriter.Create(sb) WriteXml(xw) xw.Close() Return sb.ToString End Function Public Sub Parse(ByVal xml As String) Dim xr As New XmlTextReader(xml, XmlNodeType.Document, Nothing) ReadXml(xr) xr.Close() End Sub End Class

    Read the article

  • IXmlSerializable Dictionary problem

    - by Shimmy
    I was trying to create a generic Dictionary that implements IXmlSerializable. Here is my trial: Sub Main() Dim z As New SerializableDictionary(Of String, String) z.Add("asdf", "asd") Console.WriteLine(z.Serialize) End Sub Result: <?xml version="1.0" encoding="utf-16"?><Entry key="asdf" value="asd" /> I placed a breakpoint on top of the WriteXml method and I see that when it stops, the writer contains no data at all, and IMHO it should contain the root element and the xml declaration. <Serializable()> _ Public Class SerializableDictionary(Of TKey, TValue) : Inherits Dictionary(Of TKey, TValue) : Implements IXmlSerializable Private Const EntryString As String = "Entry" Private Const KeyString As String = "key" Private Const ValueString As String = "value" Private Shared ReadOnly AttributableTypes As Type() = New Type() {GetType(Boolean), GetType(Byte), GetType(Char), GetType(DateTime), GetType(Decimal), GetType(Double), GetType([Enum]), GetType(Guid), GetType(Int16), GetType(Int32), GetType(Int64), GetType(SByte), GetType(Single), GetType(String), GetType(TimeSpan), GetType(UInt16), GetType(UInt32), GetType(UInt64)} Private Shared ReadOnly GetIsAttributable As Predicate(Of Type) = Function(t) AttributableTypes.Contains(t) Private Shared ReadOnly IsKeyAttributable As Boolean = GetIsAttributable(GetType(TKey)) Private Shared ReadOnly IsValueAttributable As Boolean = GetIsAttributable(GetType(TValue)) Private Shared ReadOnly GetElementName As Func(Of Boolean, String) = Function(isKey) If(isKey, KeyString, ValueString) Public Function GetSchema() As System.Xml.Schema.XmlSchema Implements System.Xml.Serialization.IXmlSerializable.GetSchema Return Nothing End Function Public Sub WriteXml(ByVal writer As XmlWriter) Implements IXmlSerializable.WriteXml For Each entry In Me writer.WriteStartElement(EntryString) WriteData(IsKeyAttributable, writer, True, entry.Key) WriteData(IsValueAttributable, writer, False, entry.Value) writer.WriteEndElement() Next End Sub Private Sub WriteData(Of T)(ByVal attributable As Boolean, ByVal writer As XmlWriter, ByVal isKey As Boolean, ByVal value As T) Dim name = GetElementName(isKey) If attributable Then writer.WriteAttributeString(name, value.ToString) Else Dim serializer As New XmlSerializer(GetType(T)) writer.WriteStartElement(name) serializer.Serialize(writer, value) writer.WriteEndElement() End If End Sub Public Sub ReadXml(ByVal reader As XmlReader) Implements IXmlSerializable.ReadXml Dim empty = reader.IsEmptyElement reader.Read() If empty Then Exit Sub Clear() While reader.NodeType <> XmlNodeType.EndElement While reader.NodeType = XmlNodeType.Whitespace reader.Read() Dim key = ReadData(Of TKey)(IsKeyAttributable, reader, True) Dim value = ReadData(Of TValue)(IsValueAttributable, reader, False) Add(key, value) If Not IsKeyAttributable AndAlso Not IsValueAttributable Then reader.ReadEndElement() Else reader.Read() While reader.NodeType = XmlNodeType.Whitespace reader.Read() End While End While reader.ReadEndElement() End While End Sub Private Function ReadData(Of T)(ByVal attributable As Boolean, ByVal reader As XmlReader, ByVal isKey As Boolean) As T Dim name = GetElementName(isKey) Dim type = GetType(T) If attributable Then Return Convert.ChangeType(reader.GetAttribute(name), type) Else Dim serializer As New XmlSerializer(type) While reader.Name <> name reader.Read() End While reader.ReadStartElement(name) Dim value = serializer.Deserialize(reader) reader.ReadEndElement() Return value End If End Function Public Shared Function Serialize(ByVal dictionary As SerializableDictionary(Of TKey, TValue)) As String Dim sb As New StringBuilder(1024) Dim sw As New StringWriter(sb) Dim xs As New XmlSerializer(GetType(SerializableDictionary(Of TKey, TValue))) xs.Serialize(sw, dictionary) sw.Dispose() Return sb.ToString End Function Public Shared Function Deserialize(ByVal xml As String) As SerializableDictionary(Of TKey, TValue) Dim xs As New XmlSerializer(GetType(SerializableDictionary(Of TKey, TValue))) Dim xr As New XmlTextReader(xml, XmlNodeType.Document, Nothing) Return xs.Deserialize(xr) xr.Close() End Function Public Function Serialize() As String Dim sb As New StringBuilder Dim xw = XmlWriter.Create(sb) WriteXml(xw) xw.Close() Return sb.ToString End Function Public Sub Parse(ByVal xml As String) Dim xr As New XmlTextReader(xml, XmlNodeType.Document, Nothing) ReadXml(xr) xr.Close() End Sub End Class

    Read the article

  • Cast errors with IXmlSerializable

    - by Nathan
    I am trying to use the IXmlSerializable interface to deserialize an Object (I am using it because I need specific control over what gets deserialized and what does not. See my previous question for more information). However, I'm stumped as to the error message I get. Below is the error message I get (I have changed some names for clarity): An unhandled exception of type 'System.InvalidCastException' occurred in App.exe Additional information: Unable to cast object of type 'System.Xml.XmlNode[]' to type 'MyObject'. MyObject has all the correct methods defined for the interface, and regardless of what I put in the method body for ReadXml() I still get this error. It doesn't matter if it has my implementation code or if it's just blank. I did some googling and found an error that looks similar to this involving polymorphic objects that implement IXmlSerializable. However, my class does not inherit from any others (besides Object). I suspected this may be an issue because I never reference XmlNode any other time in my code. Microsoft describes a solution to the polymorphism error: https://connect.microsoft.com/VisualStudio/feedback/details/422577/incorrect-deserialization-of-polymorphic-type-that-implements-ixmlserializable?wa=wsignin1.0#details The code the error occurs at is as follows. The object to be read back in is an ArrayList of "MyObjects" IO::FileStream ^fs = gcnew IO::FileStream(filename, IO::FileMode::Open); array<System::Type^>^ extraTypes = gcnew array<System::Type^>(1); extraTypes[0] = MyObject::typeid; XmlSerializer ^xmlser = gcnew XmlSerializer(ArrayList::typeid, extraTypes); System::Object ^obj; obj = xmlser->Deserialize(fs); fs->Close(); ArrayList ^al = safe_cast<ArrayList^>(obj); MyObject ^objs; for each(objs in al) //Error occurs here { //do some processing } Thanks for reading and for any help.

    Read the article

  • handle null values for string when implementing IXmlSerializable interface

    - by user208081
    I have the following class that implements IXmlSerializable. When implementing WriteXml(), I need to handle the case where the string members of this class may be null values. What is the best way of handling this? Currently, I am using the default constructor in which all the string properties are initialized to empty string values. This way, when WriteXml() is called, the string will not be null. One other way I could do this is check using String.IsNullOrEmpty before writing each string in xml. Any suggestions on how I can improve this code? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using System.Globalization; namespace TCS.Common.InformationObjects { public sealed class FaxSender : IXmlSerializable { #region Public Constants private const string DEFAULT_CLASS_NAME = "FaxSender"; #endregion Public Constants #region Public Properties public string Name { get; set; } public string Organization { get; set; } public string PhoneNumber { get; set; } public string FaxNumber { get; set; } public string EmailAddress { get; set; } #endregion Public Properties #region Public Methods #region Constructors public FaxSender() { Name = String.Empty; Organization = String.Empty; PhoneNumber = String.Empty; FaxNumber = String.Empty; EmailAddress = String.Empty; } public FaxSender(string name, string organization, string phoneNumber, string faxNumber, string emailAddress) { Name = name; Organization = organization; PhoneNumber = phoneNumber; FaxNumber = faxNumber; EmailAddress = emailAddress; } #endregion Constructors #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { throw new NotImplementedException(); } public void ReadXml(System.Xml.XmlReader reader) { throw new NotImplementedException(); } public void WriteXml(System.Xml.XmlWriter xmlWriter) { try { // <sender> xmlWriter.WriteStartElement("sender"); // Write the name of the sender as an element. xmlWriter.WriteElementString("name", this.Name.ToString(CultureInfo.CurrentCulture)); // Write the organization of the sender as an element. xmlWriter.WriteElementString("organization", this.Organization.ToString(CultureInfo.CurrentCulture)); // Write the phone number of the sender as an element. xmlWriter.WriteElementString("phone_number", this.PhoneNumber.ToString(CultureInfo.CurrentCulture)); // Write the fax number of the sender as an element. xmlWriter.WriteElementString("fax_number", this.FaxNumber.ToString(CultureInfo.CurrentCulture)); // Write the email address of the sender as an element. xmlWriter.WriteElementString("email_address", this.EmailAddress.ToString(CultureInfo.CurrentCulture)); // </sender> xmlWriter.WriteEndElement(); } catch { // Rethrow any exceptions. throw; } } #endregion IXmlSerializable Members #endregion Public Methods } }

    Read the article

  • representing an XML config file with an IXmlSerializable class

    - by Sarah Vessels
    I'm writing in C# and trying to represent an XML config file through an IXmlSerializable class. I'm unsure how to represent the nested elements in my config file, though, such as logLevel: <?xml version="1.0" encoding="utf-8" ?> <configuration> <logging> <logLevel>Error</logLevel> </logging> <credentials> <user>user123</user> <host>localhost</host> <password>pass123</password> </credentials> <credentials> <user>user456</user> <host>my.other.domain.com</host> <password>pass456</password> </credentials> </configuration> There is an enum called LogLevel that represents all the possible values for the logLevel tag. The tags within credentials should all come out as strings. In my class, called DLLConfigFile, I had the following: [XmlElement(ElementName="logLevel", DataType="LogLevel")] public LogLevel LogLevel; However, this isn't going to work because <logLevel> isn't within the root node of the XML file, it's one node deeper in <logging>. How do I go about doing this? As for the <credentials> nodes, my guess is I will need a second class, say CredentialsSection, and have a property such as the following: [XmlElement(ElementName="credentials", DataType="CredentialsSection")] public CredentialsSection[] AllCredentials; Edit: okay, I tried Robert Love's suggestion and created a LoggingSection class. However, my test fails: var xs = new XmlSerializer(typeof(DLLConfigFile)); using (var stream = new FileStream(_configPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var streamReader = new StreamReader(stream)) { XmlReader reader = new XmlTextReader(streamReader); var file = (DLLConfigFile)xs.Deserialize(reader); Assert.IsNotNull(file); LoggingSection logging = file.Logging; Assert.IsNotNull(logging); // fails here LogLevel logLevel = logging.LogLevel; Assert.IsNotNull(logLevel); Assert.AreEqual(EXPECTED_LOG_LEVEL, logLevel); } } The config file I'm testing with definitely has <logging>. Here's what the classes look like: [Serializable] [XmlRoot("logging")] public class LoggingSection : IXmlSerializable { public XmlSchema GetSchema() { return null; } [XmlElement(ElementName="logLevel", DataType="LogLevel")] public LogLevel LogLevel; public void ReadXml(XmlReader reader) { LogLevel = (LogLevel)Enum.Parse(typeof(LogLevel), reader.ReadString()); } public void WriteXml(XmlWriter writer) { writer.WriteString(Enum.GetName(typeof(LogLevel), LogLevel)); } } [Serializable] [XmlRoot("configuration")] public class DLLConfigFile : IXmlSerializable { [XmlElement(ElementName="logging", DataType="LoggingSection")] public LoggingSection Logging; }

    Read the article

  • Implementing IXmlSerializable on a generated class that has XmlTypeAttribute

    - by Josh
    Basically, the initial problem is I need to make a boolean value serialize as 0 or 1. The solution I found was to implement IXmlSerializable, which I did. Unfortunately the class I'm trying to serialize is generated code off a schema and has an XmlTypeAttribute on it. When I try to (de)serialize the object with the XmlSerializer created in the usual manner ( new XmlSerializer(type)) it throws this exception: System.InvalidOperationException: Only XmlRoot attribute may be specified for the type ______ Please use XmlSchemaProviderAttribute to specify schema type. Two options come to mind immediatly: 1) remove the attribute in the generated code. This change would have to be made every time the code was re-generated. 2) Use an XmlAttributeOverrides object when creating the serializer to remove the attribute. This would require the rest of the code base to "know" that it needs to override that attribute. Also, the exception thrown gives absolutly no clue as to what needs to be done to fix it. Both options kinda stink. Is there a third option?

    Read the article

  • Issue allowing custom Xml Serialization/Deserialization on certain types of field

    - by sw1sh
    I've been working with Xml Serialization/Deserialization in .net and wanted a method where the serialization/deserialization process would only be applied to certain parts of an Xml fragment. This is so I can keep certain parts of the fragment in Xml after the deserialization process. To do this I thought it would be best to create a new class (XmlLiteral) that implemented IXmlSerializable and then wrote specific code for handling the IXmlSerializable.ReadXml and IXmlSerializable.WriteXml methods. In my example below this works for Serializing, however during the Deserialization process it fails to run for multiple uses of my XmlLiteral class. In my example below sTest1 gets populated correctly, but sTest2 and sTest3 are empty. I'm guessing I must be going wrong with the following lines but can't figure out why.. Any ideas at all? Private Sub ReadXml(ByVal reader As System.Xml.XmlReader) Implements IXmlSerializable.ReadXml Dim StringType As String = "" If reader.IsEmptyElement OrElse reader.Read() = False Then Exit Sub End If _src = reader.ReadOuterXml() End Sub Full listing: Imports System Imports System.Xml.Serialization Imports System.Xml Imports System.IO Imports System.Text Public Class XmlLiteralExample Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim MyObjectInstance As New MyObject MyObjectInstance.aProperty = "MyValue" MyObjectInstance.XmlLiteral1 = New XmlLiteral("<test1>Some Value</test1>") MyObjectInstance.XmlLiteral2 = New XmlLiteral("<test2>Some Value</test2>") MyObjectInstance.XmlLiteral3 = New XmlLiteral("<test3>Some Value</test3>") ' quickly serialize the object to Xml Dim sw As New StringWriter(New StringBuilder()) Dim s As New XmlSerializer(MyObjectInstance.[GetType]()), xmlnsEmpty As New XmlSerializerNamespaces xmlnsEmpty.Add("", "") s.Serialize(sw, MyObjectInstance, xmlnsEmpty) Dim XElement As XElement = XElement.Parse(sw.ToString()) ' XElement reads as the following, so serialization works OK '<MyObject> ' <aProperty>MyValue</aProperty> ' <XmlLiteral1> ' <test1>Some Value</test1> ' </XmlLiteral1> ' <XmlLiteral2> ' <test2>Some Value</test2> ' </XmlLiteral2> ' <XmlLiteral3> ' <test3>Some Value</test3> ' </XmlLiteral3> '</MyObject> ' quickly deserialize the object back to an instance of MyObjectInstance2 Dim MyObjectInstance2 As New MyObject Dim xmlReader As XmlReader, x As XmlSerializer xmlReader = XElement.CreateReader x = New XmlSerializer(MyObjectInstance2.GetType()) MyObjectInstance2 = x.Deserialize(xmlReader) Dim sProperty As String = MyObjectInstance2.aProperty ' equal to "MyValue" Dim sTest1 As String = MyObjectInstance2.XmlLiteral1.Text ' contains <test1>Some Value</test1> Dim sTest2 As String = MyObjectInstance2.XmlLiteral2.Text ' is empty Dim sTest3 As String = MyObjectInstance2.XmlLiteral3.Text ' is empty ' sTest3 and sTest3 should be populated but are not? xmlReader = Nothing End Sub Public Class MyObject Private _aProperty As String Private _XmlLiteral1 As XmlLiteral Private _XmlLiteral2 As XmlLiteral Private _XmlLiteral3 As XmlLiteral Public Property aProperty As String Get Return _aProperty End Get Set(ByVal value As String) _aProperty = value End Set End Property Public Property XmlLiteral1 As XmlLiteral Get Return _XmlLiteral1 End Get Set(ByVal value As XmlLiteral) _XmlLiteral1 = value End Set End Property Public Property XmlLiteral2 As XmlLiteral Get Return _XmlLiteral2 End Get Set(ByVal value As XmlLiteral) _XmlLiteral2 = value End Set End Property Public Property XmlLiteral3 As XmlLiteral Get Return _XmlLiteral3 End Get Set(ByVal value As XmlLiteral) _XmlLiteral3 = value End Set End Property Public Sub New() _XmlLiteral1 = New XmlLiteral _XmlLiteral2 = New XmlLiteral _XmlLiteral3 = New XmlLiteral End Sub End Class <System.Xml.Serialization.XmlRootAttribute(Namespace:="", IsNullable:=False)> _ Public Class XmlLiteral Implements IXmlSerializable Private _src As String Public Property Text() As String Get Return _src End Get Set(ByVal value As String) _src = value End Set End Property Public Sub New() _src = "" End Sub Public Sub New(ByVal Text As String) _src = Text End Sub #Region "IXmlSerializable Members" Private Function GetSchema() As System.Xml.Schema.XmlSchema Implements IXmlSerializable.GetSchema Return Nothing End Function Private Sub ReadXml(ByVal reader As System.Xml.XmlReader) Implements IXmlSerializable.ReadXml Dim StringType As String = "" If reader.IsEmptyElement OrElse reader.Read() = False Then Exit Sub End If _src = reader.ReadOuterXml() End Sub Private Sub WriteXml(ByVal writer As System.Xml.XmlWriter) Implements IXmlSerializable.WriteXml writer.WriteRaw(_src) End Sub #End Region End Class End Class

    Read the article

  • Proper way to implement IXmlSerializable?

    - by Greg
    Once a programmer decides to implement IXmlSerializable, what are the rules and best practices for implementing it? I've heard that GetSchema() should return null and ReadXml should move to the next element before returning. Are these true? And what about WriteXml: should it write a root element for the object or is it assumed that the root is already written? How should child objects be treated and written. Here's a sample of what I have now. I'll update it as I get good responses. public class Calendar: IEnumerable<Gvent>, IXmlSerializable { public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { if (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "Calendar") { _Name = reader["Name"]; _Enabled = Boolean.Parse(reader["Enabled"]); _Color = Color.FromArgb(Int32.Parse(reader["Color"])); if (reader.ReadToDescendant("Event")) { while (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "Event") { var evt = new Event(); evt.ReadXml(reader); _Events.Add(evt); } } reader.Read(); } } public void WriteXml(XmlWriter writer) { writer.WriteAttributeString("Name", _Name); writer.WriteAttributeString("Enabled", _Enabled.ToString()); writer.WriteAttributeString("Color", _Color.ToArgb().ToString()); foreach (var evt in _Events) { writer.WriteStartElement("Event"); evt.WriteXml(writer); writer.WriteEndElement(); } } } public class Event : IXmlSerializable { public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { if (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "Event") { _Title = reader["Title"]; _Start = DateTime.FromBinary(Int64.Parse(reader["Start"])); _Stop = DateTime.FromBinary(Int64.Parse(reader["Stop"])); reader.Read(); } } public void WriteXml(XmlWriter writer) { writer.WriteAttributeString("Title", _Title); writer.WriteAttributeString("Start", _Start.ToBinary().ToString()); writer.WriteAttributeString("Stop", _Stop.ToBinary().ToString()); } }

    Read the article

  • In my WCF service with IXmlSerializable class, I get ArrayOfXElement[] instead of ObservableCollecti

    - by Scott
    I have an existing class (I didn't write) that implements IXmlSerializable. I decided to create a WCF service so my Silverlight application could access this class. I return the class as List. In the generated proxy, instead of an ObservableCollection like I'm expecting, I get ArrayOfXElement[]. If I remove the IXmlSerializable attribute, I get an the ObservableCollection. I don't quite understand what is happening, but I just want my SL app to receive an ObservableCollection. Is my only choice to create a DTO class and send back a list of those? Any advice?

    Read the article

  • Different return XML in a WCF Operation

    - by Sean Hederman
    I am writing a service to a international HTTP standard, and there is one method that can return three different XML results, call them Single, Multiple and Error. Now I've written an IXmlSerializable class that can consume each of these results and generate them. However, WCF seems to insist that I can only have a single return XML root name. I have to choose an XmlRoot for my custom object of either Single, Multiple or Error. How can I set up WCF so that I can choose at runtime what the root will be? This is what I have currently. /// <summary> /// A collection of items. /// </summary> [XmlRoot("Multiple", Namespace = "DAV:")] public sealed class ItemCollection : IEnumerable<Item>, IXmlSerializable /// <summary> /// Processes and returns the items. /// </summary> [WebInvoke(Method = "POST", UriTemplate = "{*path}", BodyStyle = WebMessageBodyStyle.Bare)] [OperationContract] [XmlSerializerFormat] ItemCollection Process(string path);

    Read the article

  • Strongly Typed DataSet column requires custom type to implement IXmlSerializable?

    - by Phil
    I have a strongly typed Dataset with a single table with three columns. These columns all contain custom types. DataColumn1 is of type Parent DataColumn2 is of type Child1 DataColumn3 is of type Child2 Here is what these classes look like: [Serializable] [XmlInclude(typeof(Child1)), XmlInclude(typeof(Child2))] public abstract class Parent { public int p1; } [Serializable] public class Child1 :Parent { public int c1; } [Serializable] public class Child2 : Parent { public int c1; } now, if I add a row with DataColumn1 being null, and DataColumns 2 and 3 populated and try to serialize it, it works: DataSet1 ds = new DataSet1(); ds.DataTable1.AddDataTable1Row(null, new Child1(), new Child2()); StringBuilder sb = new StringBuilder(); using (StringWriter writer = new StringWriter(sb)) { ds.WriteXml(writer);//Works! } However, if I try to add a value to DataColumn1, it fails: DataSet1 ds = new DataSet1(); ds.DataTable1.AddDataTable1Row(new Child1(), new Child1(), new Child2()); StringBuilder sb = new StringBuilder(); using (StringWriter writer = new StringWriter(sb)) { ds.WriteXml(writer);//Fails! } Here is the Exception: "Type 'WindowsFormsApplication4.Child1, WindowsFormsApplication4, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not implement IXmlSerializable interface therefore can not proceed with serialization." I have also tried using the XmlSerializer to serialize the dataset, but I get the same exception. Does anyone know of a way to get around this where I don't have to implement IXmlSerializable on all the Child classes? Alternatively, is there a way to implement IXmlSerializable keeping all default behavior the same (ie not having any class specific code in the ReadXml and WriteXml methods)

    Read the article

  • Is there a way to make a serialized member to serialize as an attribute?

    - by Shimmy
    Is there a way to make a serialized member to serialize as an attribute: <Serializable> Public Class Person Public Property Name As String End Class I want than when this class is xml-serialized, it should produce: <Person Name="John Doe" /> And what I mean is that instead of the Name property should be serialized as an element, it should be serialized as an xml attribute.

    Read the article

  • LLBLGen Pro and JSON serialization

    - by FransBouma
    I accidentally removed a reply from my previous blogpost, and as this blog-engine here at weblogs.asp.net is apparently falling apart, I can't re-add it as it thought it would be wise to disable comment controls on all posts, except new ones. So I'll post the reply here as a quote and reply on it. 'Steven' asks: What would the future be for LLBLGen Pro to support JSON for serialization? Would it be worth the effort for a LLBLGenPro user to bother creating some code templates to produce additional JSON serializable classes? Or just create some basic POCO classes which could be used for exchange of client/server data and use DTO to map these back to LLBGenPro ones? If I understand the work around, it is at the expense of losing xml serialization. Well, as described in the previous post, to enable JSON serialization, you can do that with a couple of lines and some attribute assignments. However, indeed, the attributes might make the XML serialization not working, as described in the previous blogpost. This is the case if the service you're using serializes objects using the DataContract serializer: this serializer will give up to serialize the entity objects to XML as the entity objects implement IXmlSerializable and this is a no-go area for the DataContract serializer. However, if your service doesn't use a DataContract serializer, or you serialize the objects manually to Xml using an xml serializer, you're fine. When you want to switch to Xml serializing again, instead of JSON in WebApi, and you have decorated the entity classes with the data-contract attributes, you can switch off the DataContract serializer, by setting a global configuration setting: var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter; xml.UseXmlSerializer = true; This will make the WebApi use the XmlSerializer, and run the normal IXmlSerializable interface implementation.

    Read the article

  • In VB.NET how do you specify Inherits/implements on a generic class with multi-constraints

    - by Romel Evans
    When I write the following statement in VB.Net (C# is my normal language), I get an "end of statement expected" referring to the "Implements" statement. <Serializable()> _ <XmlSchemaProvider("EtgSchema")> _ Public Class SerializeableEntity(Of T As {Class, ISerializable, New}) _ Implements IXmlSerializable, ISerializable ... End Class The C# version that I'm trying to emulate is: [Serializable] [XmlSchemaProvider("MySchema")] public class SerializableEntity<T> : IXmlSerializable, ISerializable where T : class, new() { .... } Sometimes I feel like I have 5 thumbs with VB.NET :)

    Read the article

  • Strategies for serializing an object for auditing/logging purpose in .NET?

    - by Jiho Han
    Let's say I have an application that processes messages. Messages are just objects in this case that implements IMessage interface which is just a marker. In this app, if a message fails to process, then I want to log it, first of all for auditing and troubleshooting purposes. Secondly I might want to use it for re-processing. Ideally, I want the message to be serialized into a format that is human-readable. The first candidate is XML although there are others like JSON. If I were to serialize the messages as XML, I want to know whether the message object is XML-serializable. One way is to reflect on the type and to see if it has a parameter-less constructor and the other is to require IXmlSerializable interface. I'm not too happy with either of these approaches. There is a third option which is to try to serialize it and catch exceptions. This doesn't really help - I want to, in some way, stipulate that IMessage (or a derived type) should be xml-serializable. The reflection route has obvious disadvantages such as security, performance, etc. IXmlSerializable route locks down my messages to one format, when in the future, I might want to change the serialization format to be JSON. The other thing is even the simplest objects now must implement ReadXml and WriteXml methods. Is there a route that involves the least amount of work that lets me serialize an arbitrary object (as long as it implements the marker interface) into XML but not lock future messages into XML?

    Read the article

  • Virtual properties duplicated during serialization when XmlElement attribute used

    - by Laramie
    The Goal: XML serialize an object that contains a list of objects of that and its derived types. The resulting XML should not use the xsi:type attribute to describe the type, to wit the names of the serialized XML elements would be an assigned name specific to the derived type, not always that of the base class, which is the default behavior. The Attempt: After exploring IXmlSerializable and IXmlSerializable with eerie XmlSchemaProvider methods and voodoo reflection to return specialized schemas and an XmlQualifiedName over the course of days, I found I was able to use the simple [XmlElement] attribute to accomplish the goal... almost. The Problem: Overridden properties appear twice when serializing. The exception reads "The XML element 'overriddenProperty' from namespace '' is already present in the current scope. Use XML attributes to specify another XML name or namespace for the element." I attempted using a *Specified property (see code), but it didn't work. Sample Code: Class Declaration using System; using System.Collections.Generic; using System.Xml.Serialization; [XmlInclude(typeof(DerivedClass))] public class BaseClass { public BaseClass() { } [XmlAttribute("virt")] public virtual string Virtual { get; set; } [XmlIgnore] public bool VirtualSpecified { get { return (this is BaseClass); } set { } } [XmlElement(ElementName = "B", Type = typeof(BaseClass), IsNullable = false)] [XmlElement(ElementName = "D", Type = typeof(DerivedClass), IsNullable = false)] public List<BaseClass> Children { get; set; } } public class DerivedClass : BaseClass { public DerivedClass() { } [XmlAttribute("virt")] public override string Virtual { get { return "always return spackle"; } set { } } } Driver: BaseClass baseClass = new BaseClass() { Children = new List<BaseClass>() }; BaseClass baseClass2 = new BaseClass(){}; DerivedClass derivedClass1 = new DerivedClass() { Children = new List<BaseClass>() }; DerivedClass derivedClass2 = new DerivedClass() { Children = new List<BaseClass>() }; baseClass.Children.Add(derivedClass1); baseClass.Children.Add(derivedClass2); derivedClass1.Children.Add(baseClass2); I've been wrestling with this on and off for weeks and can't find the answer anywhere.

    Read the article

  • XML Serializing a class with a Dictionary<string, List<string>> object

    - by Matt
    Is it possible to implement IXmlSerializable and in my XML file capture an object of type Dictionary ? I have the following public class coolio : IXmlSerializable { private int a; private bool b; private string c; private Dictionary<string, List<string>> coco; public coolio(int _a, bool _b, string _c, Dictionary<string, List<string>> _coco) { a=_a; b=_b; c=_c; coco=_coco; } public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void WriteXml(XmlWriter writer) { const string myType = "coolio"; writer.WriteStartElement(myType); writer.WriteAttributeString("a", a.ToString()); writer.WriteAttributeString("b", b.ToString()); writer.WriteAttributeString("c", c); // How do I add a subelement for Dictionary<string, List<string>> coco? writer.WriteEndElement(); } public void ReadXml(XmlReader reader) { if (reader.MoveToContent() != XmlNodeType.Element || reader.LocalName != "coolio") return; a= int.Parse(reader["a"]); b = bool.Parse(reader["b"]); c= reader["c"]; // How do I read subelement into Dictionary<string, List<string>> coco? } } But I am stumped as to how I could add the Dictionary (XML seriliazed to my XML file)

    Read the article

  • Create an Xml file from an object

    - by remi bourgarel
    I work as a web developer with a web designer and we usually do like this : - I create the system , I generate some Xml files - the designer display the xml files with xslt Nothing new. My problem is that I use Xml Serialization to create my xml files, but I never use Deserialization. So I'd like to know if there is a way to avoid fix like these : empty setter for my property empty parameter-less constructor implement IXmlSerializable and throw "notimplementedexception" on deserialization do a copy of the class with public fields

    Read the article

  • Create an Xml file from an object (c#)

    - by remi bourgarel
    Hi All, I work as a web developer with a web designer and we usually do like this : - I create the system , I generate some Xml files - the designer display the xml files with xslt Nothing new. My problem is that I use Xml Serialization to create my xml files, but I never use Deserialization. So I'd like to know if there is a way to avoid fix like these : empty setter for my property empty parameter-less constructor implement IXmlSerializable and throw "notimplementedexception" on deserialization do a copy of the class with public fields thanks.

    Read the article

  • help me "dry" out this .net XML serialization code

    - by Sarah Vessels
    I have a base collection class and a child collection class, each of which are serializable. In a test, I discovered that simply having the child class's ReadXml method call base.ReadXml resulted in an InvalidCastException later on. First, here's the class structure: Base Class // Collection of Row objects [Serializable] [XmlRoot("Rows")] public class Rows : IList<Row>, ICollection<Row>, IEnumerable<Row>, IEquatable<Rows>, IXmlSerializable { public Collection<Row> Collection { get; protected set; } public void ReadXml(XmlReader reader) { reader.ReadToFollowing(XmlNodeName); do { using (XmlReader rowReader = reader.ReadSubtree()) { var row = new Row(); row.ReadXml(rowReader); Collection.Add(row); } } while (reader.ReadToNextSibling(XmlNodeName)); } } Derived Class // Acts as a collection of SpecificRow objects, which inherit from Row. Uses the same // Collection<Row> that Rows defines which is fine since SpecificRow : Row. [Serializable] [XmlRoot("MySpecificRowList")] public class SpecificRows : Rows, IXmlSerializable { public new void ReadXml(XmlReader reader) { // Trying to just do base.ReadXml(reader) causes a cast exception later reader.ReadToFollowing(XmlNodeName); do { using (XmlReader rowReader = reader.ReadSubtree()) { var row = new SpecificRow(); row.ReadXml(rowReader); Collection.Add(row); } } while (reader.ReadToNextSibling(XmlNodeName)); } public new Row this[int index] { // The cast in this getter is what causes InvalidCastException if I try // to call base.ReadXml from this class's ReadXml get { return (Row)Collection[index]; } set { Collection[index] = value; } } } And here's the code that causes a runtime InvalidCastException if I do not use the version of ReadXml shown in SpecificRows above (i.e., I get the exception if I just call base.ReadXml from within SpecificRows.ReadXml): TextReader reader = new StringReader(serializedResultStr); SpecificRows deserializedResults = (SpecificRows)xs.Deserialize(reader); SpecificRow = deserializedResults[0]; // this throws InvalidCastException So, the code above all compiles and runs exception-free, but it bugs me that Rows.ReadXml and SpecificRows.ReadXml are essentially the same code. The value of XmlNodeName and the new Row()/new SpecificRow() are the differences. How would you suggest I extract out all the common functionality of both versions of ReadXml? Would it be silly to create some generic class just for one method? Sorry for the lengthy code samples, I just wanted to provide the reason I can't simply call base.ReadXml from within SpecificRows.

    Read the article

  • Help with XML SerializableDictionary in C#

    - by psilos
    Hi I am using the class public class SerializableDictionary : Dictionary, IXmlSerializable in order to serialize a dictionary. However it doesnt work when as values I have collelctions (eg List) or tyes other than the primitive types (eg. int, double, string....). My question is which types the TKey, TValue imply or can hold, and if there is way to have a serializable dictionary which collections as values.

    Read the article

  • An Xml Serializable PropertyBag Dictionary Class for .NET

    - by Rick Strahl
    I don't know about you but I frequently need property bags in my applications to store and possibly cache arbitrary data. Dictionary<T,V> works well for this although I always seem to be hunting for a more specific generic type that provides a string key based dictionary. There's string dictionary, but it only works with strings. There's Hashset<T> but it uses the actual values as keys. In most key value pair situations for me string is key value to work off. Dictionary<T,V> works well enough, but there are some issues with serialization of dictionaries in .NET. The .NET framework doesn't do well serializing IDictionary objects out of the box. The XmlSerializer doesn't support serialization of IDictionary via it's default serialization, and while the DataContractSerializer does support IDictionary serialization it produces some pretty atrocious XML. What doesn't work? First off Dictionary serialization with the Xml Serializer doesn't work so the following fails: [TestMethod] public void DictionaryXmlSerializerTest() { var bag = new Dictionary<string, object>(); bag.Add("key", "Value"); bag.Add("Key2", 100.10M); bag.Add("Key3", Guid.NewGuid()); bag.Add("Key4", DateTime.Now); bag.Add("Key5", true); bag.Add("Key7", new byte[3] { 42, 45, 66 }); TestContext.WriteLine(this.ToXml(bag)); } public string ToXml(object obj) { if (obj == null) return null; StringWriter sw = new StringWriter(); XmlSerializer ser = new XmlSerializer(obj.GetType()); ser.Serialize(sw, obj); return sw.ToString(); } The error you get with this is: System.NotSupportedException: The type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] is not supported because it implements IDictionary. Got it! BTW, the same is true with binary serialization. Running the same code above against the DataContractSerializer does work: [TestMethod] public void DictionaryDataContextSerializerTest() { var bag = new Dictionary<string, object>(); bag.Add("key", "Value"); bag.Add("Key2", 100.10M); bag.Add("Key3", Guid.NewGuid()); bag.Add("Key4", DateTime.Now); bag.Add("Key5", true); bag.Add("Key7", new byte[3] { 42, 45, 66 }); TestContext.WriteLine(this.ToXmlDcs(bag)); } public string ToXmlDcs(object value, bool throwExceptions = false) { var ser = new DataContractSerializer(value.GetType(), null, int.MaxValue, true, false, null); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, value); return Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length); } This DOES work but produces some pretty heinous XML (formatted with line breaks and indentation here): <ArrayOfKeyValueOfstringanyType xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <KeyValueOfstringanyType> <Key>key</Key> <Value i:type="a:string" xmlns:a="http://www.w3.org/2001/XMLSchema">Value</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>Key2</Key> <Value i:type="a:decimal" xmlns:a="http://www.w3.org/2001/XMLSchema">100.10</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>Key3</Key> <Value i:type="a:guid" xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/">2cd46d2a-a636-4af4-979b-e834d39b6d37</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>Key4</Key> <Value i:type="a:dateTime" xmlns:a="http://www.w3.org/2001/XMLSchema">2011-09-19T17:17:05.4406999-07:00</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>Key5</Key> <Value i:type="a:boolean" xmlns:a="http://www.w3.org/2001/XMLSchema">true</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>Key7</Key> <Value i:type="a:base64Binary" xmlns:a="http://www.w3.org/2001/XMLSchema">Ki1C</Value> </KeyValueOfstringanyType> </ArrayOfKeyValueOfstringanyType> Ouch! That seriously hurts the eye! :-) Worse though it's extremely verbose with all those repetitive namespace declarations. It's good to know that it works in a pinch, but for a human readable/editable solution or something lightweight to store in a database it's not quite ideal. Why should I care? As a little background, in one of my applications I have a need for a flexible property bag that is used on a free form database field on an otherwise static entity. Basically what I have is a standard database record to which arbitrary properties can be added in an XML based string field. I intend to expose those arbitrary properties as a collection from field data stored in XML. The concept is pretty simple: When loading write the data to the collection, when the data is saved serialize the data into an XML string and store it into the database. When reading the data pick up the XML and if the collection on the entity is accessed automatically deserialize the XML into the Dictionary. (I'll talk more about this in another post). While the DataContext Serializer would work, it's verbosity is problematic both for size of the generated XML strings and the fact that users can manually edit this XML based property data in an advanced mode. A clean(er) layout certainly would be preferable and more user friendly. Custom XMLSerialization with a PropertyBag Class So… after a bunch of experimentation with different serialization formats I decided to create a custom PropertyBag class that provides for a serializable Dictionary. It's basically a custom Dictionary<TType,TValue> implementation with the keys always set as string keys. The result are PropertyBag<TValue> and PropertyBag (which defaults to the object type for values). The PropertyBag<TType> and PropertyBag classes provide these features: Subclassed from Dictionary<T,V> Implements IXmlSerializable with a cleanish XML format ToXml() and FromXml() methods to export and import to and from XML strings Static CreateFromXml() method to create an instance It's simple enough as it's merely a Dictionary<string,object> subclass but that supports serialization to a - what I think at least - cleaner XML format. The class is super simple to use: [TestMethod] public void PropertyBagTwoWayObjectSerializationTest() { var bag = new PropertyBag(); bag.Add("key", "Value"); bag.Add("Key2", 100.10M); bag.Add("Key3", Guid.NewGuid()); bag.Add("Key4", DateTime.Now); bag.Add("Key5", true); bag.Add("Key7", new byte[3] { 42,45,66 } ); bag.Add("Key8", null); bag.Add("Key9", new ComplexObject() { Name = "Rick", Entered = DateTime.Now, Count = 10 }); string xml = bag.ToXml(); TestContext.WriteLine(bag.ToXml()); bag.Clear(); bag.FromXml(xml); Assert.IsTrue(bag["key"] as string == "Value"); Assert.IsInstanceOfType( bag["Key3"], typeof(Guid)); Assert.IsNull(bag["Key8"]); //Assert.IsNull(bag["Key10"]); Assert.IsInstanceOfType(bag["Key9"], typeof(ComplexObject)); } This uses the PropertyBag class which uses a PropertyBag<string,object> - which means it returns untyped values of type object. I suspect for me this will be the most common scenario as I'd want to store arbitrary values in the PropertyBag rather than one specific type. The same code with a strongly typed PropertyBag<decimal> looks like this: [TestMethod] public void PropertyBagTwoWayValueTypeSerializationTest() { var bag = new PropertyBag<decimal>(); bag.Add("key", 10M); bag.Add("Key1", 100.10M); bag.Add("Key2", 200.10M); bag.Add("Key3", 300.10M); string xml = bag.ToXml(); TestContext.WriteLine(bag.ToXml()); bag.Clear(); bag.FromXml(xml); Assert.IsTrue(bag.Get("Key1") == 100.10M); Assert.IsTrue(bag.Get("Key3") == 300.10M); } and produces typed results of type decimal. The types can be either value or reference types the combination of which actually proved to be a little more tricky than anticipated due to null and specific string value checks required - getting the generic typing right required use of default(T) and Convert.ChangeType() to trick the compiler into playing nice. Of course the whole raison d'etre for this class is the XML serialization. You can see in the code above that we're doing a .ToXml() and .FromXml() to serialize to and from string. The XML produced for the first example looks like this: <?xml version="1.0" encoding="utf-8"?> <properties> <item> <key>key</key> <value>Value</value> </item> <item> <key>Key2</key> <value type="decimal">100.10</value> </item> <item> <key>Key3</key> <value type="___System.Guid"> <guid>f7a92032-0c6d-4e9d-9950-b15ff7cd207d</guid> </value> </item> <item> <key>Key4</key> <value type="datetime">2011-09-26T17:45:58.5789578-10:00</value> </item> <item> <key>Key5</key> <value type="boolean">true</value> </item> <item> <key>Key7</key> <value type="base64Binary">Ki1C</value> </item> <item> <key>Key8</key> <value type="nil" /> </item> <item> <key>Key9</key> <value type="___Westwind.Tools.Tests.PropertyBagTest+ComplexObject"> <ComplexObject> <Name>Rick</Name> <Entered>2011-09-26T17:45:58.5789578-10:00</Entered> <Count>10</Count> </ComplexObject> </value> </item> </properties>   The format is a bit cleaner than the DataContractSerializer. Each item is serialized into <key> <value> pairs. If the value is a string no type information is written. Since string tends to be the most common type this saves space and serialization processing. All other types are attributed. Simple types are mapped to XML types so things like decimal, datetime, boolean and base64Binary are encoded using their Xml type values. All other types are embedded with a hokey format that describes the .NET type preceded by a three underscores and then are encoded using the XmlSerializer. You can see this best above in the ComplexObject encoding. For custom types this isn't pretty either, but it's more concise than the DCS and it works as long as you're serializing back and forth between .NET clients at least. The XML generated from the second example that uses PropertyBag<decimal> looks like this: <?xml version="1.0" encoding="utf-8"?> <properties> <item> <key>key</key> <value type="decimal">10</value> </item> <item> <key>Key1</key> <value type="decimal">100.10</value> </item> <item> <key>Key2</key> <value type="decimal">200.10</value> </item> <item> <key>Key3</key> <value type="decimal">300.10</value> </item> </properties>   How does it work As I mentioned there's nothing fancy about this solution - it's little more than a subclass of Dictionary<T,V> that implements custom Xml Serialization and a couple of helper methods that facilitate getting the XML in and out of the class more easily. But it's proven very handy for a number of projects for me where dynamic data storage is required. Here's the code: /// <summary> /// Creates a serializable string/object dictionary that is XML serializable /// Encodes keys as element names and values as simple values with a type /// attribute that contains an XML type name. Complex names encode the type /// name with type='___namespace.classname' format followed by a standard xml /// serialized format. The latter serialization can be slow so it's not recommended /// to pass complex types if performance is critical. /// </summary> [XmlRoot("properties")] public class PropertyBag : PropertyBag<object> { /// <summary> /// Creates an instance of a propertybag from an Xml string /// </summary> /// <param name="xml">Serialize</param> /// <returns></returns> public static PropertyBag CreateFromXml(string xml) { var bag = new PropertyBag(); bag.FromXml(xml); return bag; } } /// <summary> /// Creates a serializable string for generic types that is XML serializable. /// /// Encodes keys as element names and values as simple values with a type /// attribute that contains an XML type name. Complex names encode the type /// name with type='___namespace.classname' format followed by a standard xml /// serialized format. The latter serialization can be slow so it's not recommended /// to pass complex types if performance is critical. /// </summary> /// <typeparam name="TValue">Must be a reference type. For value types use type object</typeparam> [XmlRoot("properties")] public class PropertyBag<TValue> : Dictionary<string, TValue>, IXmlSerializable { /// <summary> /// Not implemented - this means no schema information is passed /// so this won't work with ASMX/WCF services. /// </summary> /// <returns></returns> public System.Xml.Schema.XmlSchema GetSchema() { return null; } /// <summary> /// Serializes the dictionary to XML. Keys are /// serialized to element names and values as /// element values. An xml type attribute is embedded /// for each serialized element - a .NET type /// element is embedded for each complex type and /// prefixed with three underscores. /// </summary> /// <param name="writer"></param> public void WriteXml(System.Xml.XmlWriter writer) { foreach (string key in this.Keys) { TValue value = this[key]; Type type = null; if (value != null) type = value.GetType(); writer.WriteStartElement("item"); writer.WriteStartElement("key"); writer.WriteString(key as string); writer.WriteEndElement(); writer.WriteStartElement("value"); string xmlType = XmlUtils.MapTypeToXmlType(type); bool isCustom = false; // Type information attribute if not string if (value == null) { writer.WriteAttributeString("type", "nil"); } else if (!string.IsNullOrEmpty(xmlType)) { if (xmlType != "string") { writer.WriteStartAttribute("type"); writer.WriteString(xmlType); writer.WriteEndAttribute(); } } else { isCustom = true; xmlType = "___" + value.GetType().FullName; writer.WriteStartAttribute("type"); writer.WriteString(xmlType); writer.WriteEndAttribute(); } // Actual deserialization if (!isCustom) { if (value != null) writer.WriteValue(value); } else { XmlSerializer ser = new XmlSerializer(value.GetType()); ser.Serialize(writer, value); } writer.WriteEndElement(); // value writer.WriteEndElement(); // item } } /// <summary> /// Reads the custom serialized format /// </summary> /// <param name="reader"></param> public void ReadXml(System.Xml.XmlReader reader) { this.Clear(); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "key") { string xmlType = null; string name = reader.ReadElementContentAsString(); // item element reader.ReadToNextSibling("value"); if (reader.MoveToNextAttribute()) xmlType = reader.Value; reader.MoveToContent(); TValue value; if (xmlType == "nil") value = default(TValue); // null else if (string.IsNullOrEmpty(xmlType)) { // value is a string or object and we can assign TValue to value string strval = reader.ReadElementContentAsString(); value = (TValue) Convert.ChangeType(strval, typeof(TValue)); } else if (xmlType.StartsWith("___")) { while (reader.Read() && reader.NodeType != XmlNodeType.Element) { } Type type = ReflectionUtils.GetTypeFromName(xmlType.Substring(3)); //value = reader.ReadElementContentAs(type,null); XmlSerializer ser = new XmlSerializer(type); value = (TValue)ser.Deserialize(reader); } else value = (TValue)reader.ReadElementContentAs(XmlUtils.MapXmlTypeToType(xmlType), null); this.Add(name, value); } } } /// <summary> /// Serializes this dictionary to an XML string /// </summary> /// <returns>XML String or Null if it fails</returns> public string ToXml() { string xml = null; SerializationUtils.SerializeObject(this, out xml); return xml; } /// <summary> /// Deserializes from an XML string /// </summary> /// <param name="xml"></param> /// <returns>true or false</returns> public bool FromXml(string xml) { this.Clear(); // if xml string is empty we return an empty dictionary if (string.IsNullOrEmpty(xml)) return true; var result = SerializationUtils.DeSerializeObject(xml, this.GetType()) as PropertyBag<TValue>; if (result != null) { foreach (var item in result) { this.Add(item.Key, item.Value); } } else // null is a failure return false; return true; } /// <summary> /// Creates an instance of a propertybag from an Xml string /// </summary> /// <param name="xml"></param> /// <returns></returns> public static PropertyBag<TValue> CreateFromXml(string xml) { var bag = new PropertyBag<TValue>(); bag.FromXml(xml); return bag; } } } The code uses a couple of small helper classes SerializationUtils and XmlUtils for mapping Xml types to and from .NET, both of which are from the WestWind,Utilities project (which is the same project where PropertyBag lives) from the West Wind Web Toolkit. The code implements ReadXml and WriteXml for the IXmlSerializable implementation using old school XmlReaders and XmlWriters (because it's pretty simple stuff - no need for XLinq here). Then there are two helper methods .ToXml() and .FromXml() that basically allow your code to easily convert between XML and a PropertyBag object. In my code that's what I use to actually to persist to and from the entity XML property during .Load() and .Save() operations. It's sweet to be able to have a string key dictionary and then be able to turn around with 1 line of code to persist the whole thing to XML and back. Hopefully some of you will find this class as useful as I've found it. It's a simple solution to a common requirement in my applications and I've used the hell out of it in the  short time since I created it. Resources You can find the complete code for the two classes plus the helpers in the Subversion repository for Westwind.Utilities. You can grab the source files from there or download the whole project. You can also grab the full Westwind.Utilities assembly from NuGet and add it to your project if that's easier for you. PropertyBag Source Code SerializationUtils and XmlUtils Westwind.Utilities Assembly on NuGet (add from Visual Studio) © Rick Strahl, West Wind Technologies, 2005-2011Posted in .NET  CSharp   Tweet (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Correct XML serialization and deserialization of "mixed" types in .NET

    - by Stefan
    My current task involves writing a class library for processing HL7 CDA files. These HL7 CDA files are XML files with a defined XML schema, so I used xsd.exe to generate .NET classes for XML serialization and deserialization. The XML Schema contains various types which contain the mixed="true" attribute, specifying that an XML node of this type may contain normal text mixed with other XML nodes. The relevant part of the XML schema for one of these types looks like this: <xs:complexType name="StrucDoc.Paragraph" mixed="true"> <xs:sequence> <xs:element name="caption" type="StrucDoc.Caption" minOccurs="0"/> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="br" type="StrucDoc.Br"/> <xs:element name="sub" type="StrucDoc.Sub"/> <xs:element name="sup" type="StrucDoc.Sup"/> <!-- ...other possible nodes... --> </xs:choice> </xs:sequence> <xs:attribute name="ID" type="xs:ID"/> <!-- ...other attributes... --> </xs:complexType> The generated code for this type looks like this: /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="StrucDoc.Paragraph", Namespace="urn:hl7-org:v3")] public partial class StrucDocParagraph { private StrucDocCaption captionField; private object[] itemsField; private string[] textField; private string idField; // ...fields for other attributes... /// <remarks/> public StrucDocCaption caption { get { return this.captionField; } set { this.captionField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("br", typeof(StrucDocBr))] [System.Xml.Serialization.XmlElementAttribute("sub", typeof(StrucDocSub))] [System.Xml.Serialization.XmlElementAttribute("sup", typeof(StrucDocSup))] // ...other possible nodes... public object[] Items { get { return this.itemsField; } set { this.itemsField = value; } } /// <remarks/> [System.Xml.Serialization.XmlTextAttribute()] public string[] Text { get { return this.textField; } set { this.textField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute(DataType="ID")] public string ID { get { return this.idField; } set { this.idField = value; } } // ...properties for other attributes... } If I deserialize an XML element where the paragraph node looks like this: <paragraph>first line<br /><br />third line</paragraph> The result is that the item and text arrays are read like this: itemsField = new object[] { new StrucDocBr(), new StrucDocBr(), }; textField = new string[] { "first line", "third line", }; From this there is no possible way to determine the exact order of the text and the other nodes. If I serialize this again, the result looks exactly like this: <paragraph> <br /> <br />first linethird line </paragraph> The default serializer just serializes the items first and then the text. I tried implementing IXmlSerializable on the StrucDocParagraph class so that I could control the deserialization and serialization of the content, but it's rather complex since there are so many classes involved and I didn't come to a solution yet because I don't know if the effort pays off. Is there some kind of easy workaround to this problem, or is it even possible by doing custom serialization via IXmlSerializable? Or should I just use XmlDocument or XmlReader/XmlWriter to process these documents?

    Read the article

  • Scripting.dictionary to c#

    - by naresh
    Facing one problem please help me.... We are product development company and our existing application is in ASP, I am trying to send scripting.dictionary object to c#'s com visible class. I am using the System.Collections.Generic class here is my code ASP: dim dictForm set dictForm=CreateObject("scripting.dictionary") dictForm("First") ="one" dictForm("Second") ="two" SET OBJMSGBOX = Server.CreateObject("DictionarySerializer.DictionarySerializer") call OBJMSGBOX.ConvertDictionary(dictForm) c#: [ComVisible(true)] public class DictionarySerializer : IXmlSerializable { Dictionary dict = new Dictionary(); public void ConvertDictionary(Dictionary dictionary) { this.dict = dictionary; } } I am getting error Invalid procedure call or argument: 'ConvertDictionary' Please tell me where I am going in wrong way.

    Read the article

  • .NET XML Serialization, possibly to use a different method name than PropertySpecified for ignoring

    - by Lasse V. Karlsen
    I have a bunch of classes that I intend to serialize in order to transport over a webservice call. These classes already have properties that return whether a given "real" property has a value or not, that is ingrained in a lot of code of our product. Is it possible, for instance through attributes, for me to specify that each "real" property should be included if a specified other property returns true, but not one that is called RealPropertyNameSpecified? ie. for instance if I have this class: [XmlType("test")] public class TestClass { [XmlIgnore] public bool NameHasGotAValue { get; set; } [XmlElement("name")] public string Name { get; set; } } Is it possible for me to use the NameHasGotAValue as the "*Specified" method for the Name property, or is my only option to either rename NameHasGotAValue, add a NameSpecified method, or implement IXmlSerializable?

    Read the article

1 2  | Next Page >