.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
MarieAdela
Imran Ghani
Post New Web Links

Serialize / DeSerialize XElement objecs using BinaryFormatter.

Posted By:      Posted Date: August 31, 2010    Points: 0   Category :.NET Framework
 
Hi, I'm having some business objects which contains XElement properties. I have some offline framework which serialize / deserialize using binary formatter. I'm getting the error "Type 'System.Xml.Linq.XElement' in Assembly 'System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable." when i try to serialize the xelement object I'm getting the XElement serializer error. We are bit too far with design and need to find some work around to solve this issue. The following program should give you the same error behavior. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml.Linq; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace XElementBinaryformatter {     public partial class Form1 : Form     {         private BinaryFormatter formatter = new BinaryFormatter();         public Form1()         {             InitializeComponent();         }         private void btnSerialize_Clic


View Complete Post


More Related Resource Links

Serialize / DeSerialize XElement objecs using BinaryFormatter.

  
Hi, I'm having some business objects which contains XElement properties. I have some offline framework which serialize / deserialize using binary formatter. I'm getting the error "Type 'System.Xml.Linq.XElement' in Assembly 'System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable." when i try to serialize the xelement object I'm getting the XElement serializer error. We are bit too far with design and need to find some work around to solve this issue. The following program should give you the same error behavior. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml.Linq; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace XElementBinaryformatter {     public partial class Form1 : Form     {         private BinaryFormatter formatter = new BinaryFormatter();         public Form1()         {             InitializeComponent();         }         private void btnSerialize_Clic

Can serialize but not deserialize class containing an xs:list attribute using XmlSerializer

  
I have a simple serializable class along the lines of: [Serializable] [XmlType] public class MyClass { [XmlAttribute("values")] public int[] Values { get; set; } } If I create an instance of this class with Values set to an empty collection the XmlSerializer class produces this output as expected: <?xml version="1.0" encoding="utf-16" ?> <MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" values="" /> However, deserializing this exact output throws a System.FormatException: Input string was not in a correct format. Shouldn't the XmlSerializer be able to deserialize this, since it produced the xml string in the first place?

how to serialize/deserialize image in vb.net

  

hi guys,

i need to serialize and deserialize an image for my project. i have been googling it for a few days but i cannot find any VB codes related to image serialization... can someone give me some hints on how i should start??

for my program, i need to save the image to sql database and then i need to retrieve all the image for my product catalog

thank you in advance for you help!

rgds,


BinaryFormatter.Deserialize: specified cast is not valid

  

I'm trying to run code like this.

Declare custom data type

    [Serializable]
    public struct Configuration
    {
      public int a;
      public string[] b;
      public string c;
    }

Serialize data to the file

      Configuration config;
      // Assign values to config 
      ...
      // Serialize data
      FileStream fs = new FileStream(configFile, FileMode.Create);
      BinaryFormatter formatter = new BinaryFormatter();
      try
      {
        formatter.Serialize(fs, config);
      }
      catch (SerializationException e)
      {
        ErrorRecord errorRecord = new ErrorRecord(e, "Error writting to the config file.", ErrorCategory.WriteError, config);
        Wr

how to serialize objects ??

  

Is there any way or process to serialize the the objects?? i am trying to store the instance of few control in viewstate but it shows error msg that it is not a serialized object. should i perform some steps to serialize the objects ???



System.Xml.Linq.XElement and XPathDocument

  

I have an XPathDocument that I want to save to a table using LINQ, but I get this error

cannot implicitly convert type 'System.Xml.XPath.XPathDocument' to 'System.Xml.Linq.XElement'


I create the XPathDocument from some (valid) xml contained in a resource file


XPathDocument xDoc = new XPathDocument(new StringReader(Resource1.TestXML));


when I try to assign it with LINQ, it flags up an error


NewDataItem.XML = xDoc  ----  error here

NewDataitem is a LINQ to SQL object created from the underlying table, 'NewDataItem.XML' is a column type of 'XML'


how do i (easily) convert xDoc so I can pass it into the LINQ object ?




JSON Deserialize into Entity Framework Object and setting the DataMemberAttribute "Name="

  

Hi,

 

I'm in the process of deserializing a JSON object into an Entity Framework object.  The property names in the JSON do not match up totally with the property names in the Entity Framework Objects. What I'd like to do is set "Name=" on the  "DataContractAttribute" for the table and the "DataMemberAttribute" for the properties in the Designer.cs file.  I tried setting these in the Designer.cs file manually just to see if it would work - which it did (using JSON.Net) but of course when I went into the .edmx designer I lost all my changes.  Is there a way to do this?

 

Thanks in advance


How to: Serialize Hashtable contained inside another object that is serialized as an array of object

  
Update:  I've added the entire program in a single block of C# text near the end of these posts that can be placed into a C# Program.cs file of a console project.   I have a class called MyHashtable that inherits from Hashtable and implements IXmlSerializable.  MyHashtable is contained inside another object called MyObject and I need to xml serialize an array of MyObject[].  Whenever I xml deserialize, the hashtable is deserialized, but only 1 of MyObjects from the MyObject[] array is deserialized.  The ReadXml uses "while (reader.NodeType != XmlNodeType.EndElement)" so I don't think the reader is consuming all of the xml internally.   Does anyone know why this is happening?  Thanks.    

WSE 3.0 Can't Serialize String Types as Escaped CDATA

  
I know I should be using WCF.  HOWEVER, I'm utilizing services provided by Omniture that simply only work well with WSE 3.0 as Omniture's WSDL definitions and service endpoints have compatibility issues that are beyond my control.   While I was able to solve a lot of my compatibility problems with Omniture but there is one issue that is still causing me a lot of heartburn.  When passing strings values through WSE3.0 the Microsoft.Web.Services3.WebServicesClientProtocol class encodes the values as denoted below for the "script" argument.         <soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">       <tns:ProductSubmitProductScript>       <productCode xsi:type="xsd:string">123456789</productCode>       <script xsi:type="xsd:string">&lt;genesis&gt;&lt;/genesis&gt;</script>       </tns:ProductSubmitProductScript>    Unfortunately, this encoding isn't going is promptly rejected by Omniture because the xml values are not subsequently decoded on their side.  When passing string values to Omniture they MUST be enclosed in the escape sequenice <![CDATA[ ]]>.  Thus, the prior request should be

The formatter threw an exception while trying to deserialize the message

  
Hi I got this error when programming in C# 2008 The formatter threw an exception when trying to deserialize the message: Error while trying to deserialize parameter http://tempuri.org/:GetListSitesResponse. The InnerException message was' Error on line 1, position 314. The item 'http://tempuri.org/:anyType' contains data data contract 'http://tempuri.org/:Site'. The deserializer has no knowledge of any type that is assigned to this contract. Add the type corresponding to 'Site' to the list of known types (eg, using the attribute KnownTypeAttribute or adding it to the list of known types passed to DataContractSerializer). '. See InnerException for more information. This happen in my button_click event (this is a project on C# 2008 express windows form application) private void button1_Click(object sender, EventArgs e)         {             SiteDevelopmentReference.Service1SoapClient sd = new SiteDevelopmentReference.Service1SoapClient();             listBox1.Items.AddRange(sd.GetListSites().ToArray());                            } I have a service reference from another project

Small issue extracting soap from xml using Xelement

  
The following code works fine, except it only gives me the value being returned (integer), with no XML tags at all.  I want the raw XML without the soap (not just the value). display code:                 Dim path1 As String                 path1 = "c:\temp\testing.xml"                 ExtractSoap()                 File.WriteAllText(path1, ExtractSoap.Value.ToString())   function: Public Function ExtractSoap() As XElement         internalStream.Position = 0         Dim xmlMessage As XElement = XElement.Load(XmlReader.Create(internalStream))         Dim soap As XNamespace = "http://schemas.xmlsoap.org/soap/envelope/"         Dim body As XElement = xmlMessage.Element(soap + "Body")         If body IsNot Nothing Then             Return DirectCast(body.FirstNode, XElement)         End

Deserialize JSON object in C#

  
Hi, I am new to JSON and one of my service is returning JSON object as a string to my application. I need to Deserialize JSON object in C#. My JSON string is in the current format. string str = "{\"candidates\":[{\"address\":\"1580 MARKET ST, SAN FRANCISCO, CA, 94102\",\"location\":{\"x\":-122.42054,\"y\":37.7745960000001},\"score\":40,\"attributes\":{}},{\"address\":\"1576 MARKET ST, SAN FRANCISCO, CA, 94102\",\"location\":{\"x\":-122.420355,\"y\":37.7747030000001},\"score\":40,\"attributes\":{}}]}"; Can anyone please help me how to get all the address, locations, score and attributes from the above string. Thankyou, Ravi.

binary serialize weird error

  
i got this class, when i wanna serialize it, i keep getting error System.Runtime.Serialization.SerializationException was unhandled by user code   Message=Type 'System.Linq.Enumerable+WhereSelectListIterator`2[[Data.Models],[System.Int32, mscorlib, Version=4.0.0.0, ...' in Assembly 'System.Core, Version=4.0.0.0, ... is not marked as serializable. [Serializable] public class XXX : ... { public IEnumerable<int> CardFilters { get; set; } //public void RequeryCardFilters() //{ //} public void RequeryCardFilters() { this.CardFilters = null; ... //IEnumerable<Data.Models> var rslt = RFDataViewModelFactory.GetReportCardFilters(this.Identifiers, this.PostcodeFrom, this.PostcodeTo, this.LastContactBefore, this.RecontactBy, this.SelectedCardType); ... IEnumerable<int> rsltIds = from i in rslt select i.Id; } } you can see inside the RequeryCardFilters(), i only play with 3 data/var, 1 of them is local public prop, the other 2 are local var. If you remark this out, and just use an empty method, it worked fine. what can cause the serialization to fail? IFormatter formatter = new BinaryFormatter(); MemoryStream memStrem = new MemoryStream(); formatter.Serialize(memStrem, myObj);

How to serialize a File using Filestream

  
Is there a way to serialize a file using File stream. If no how it can be done Any one please help

BinaryFormatter, SortedSet base class and a few instance variables.

  
/* This example successfully serializes and deserializes the SortedSet<string> base contents, but all the instance variables show up uninitialized. Here's the output: n1: 0 n2: 0 str: s == "String 1" s == "String 2" s == "String 3" Any ideas? */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; using System.IO; [Serializable] public class MyObject : SortedSet<string> {     public MyObject() : base() { }     protected MyObject(SerializationInfo info, StreamingContext context)         : base(info, context)     {     }     public int n1 = 0;     public int n2 = 0;     public String str = null; } namespace BasicBinarySerializationInheritanceFromSortedSet {     class BasicBinarySerializationInheritenaceFromSortedSetTest     {         static void Main(string[] args)         {             {                 MyObject obj = new MyObject();   &nb

How could I deserialize a object which is serialized in JAVA??

  
When I try to do it with the code below. FileStream fileStream = new FileStream( "C:\\apps\\user.tmp", FileMode.Open, FileAccess.Read, FileShare.Read);     BinaryFormatter bf=new BinaryFormatter();     pd = (PianoData)bf.Deserialize(fileStream);     System.Console.WriteLine();     fileStream.Close(); Exception occurred as I had excepted. "The input stream is not a valid binary format."   I wonder if I can do it by another way

Can you Serialize a Derived class, cast as it's base?

  
Can you Serialize a Derived class, cast as it's base? (Using the stock XmlSerializer.Serialize?)   (The overall goal I'm trying to achieve, is I have 1 object, and I need to serialize it in 2 different ways, 1 with full info, one with half info, and I *thought* a base class would be the way to do it)   e.g. I have a base and derived class   [XmlRoot("MyBaseXml" )] public class MyBaseClass { public string baseField = "base" ; } [XmlRoot("MyDerivedXml" )] public class MyDerviedClass : MyBaseClass { public string derivedField = "derived" ; }   I make a new instance of my derived class MyDerviedClass obj = new MyDerivedClass();   And then I have the following serialization method(s)   /// <summary> /// Saves an object to a file /// </summary> /// <param name="obj"> Object to save</param> /// <param name="fileName"> Path to output to</param> public void Serialize(object obj, string fileName) { Type type = obj.GetType(); XmlSerializer xmlSerializer = new XmlSerializer(type); Serialize(obj, fileName, type); } /// <summary> /// Saves an object to a file casting it as a specific type /// </summary> /// <param name="obj"> Object to save</param> /// <param name="fileName"
Categories: 
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend