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


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

Serialize CustomType simply as T

Posted By:      Posted Date: September 19, 2010    Points: 0   Category :WCF
 

Consider the following custom classes (simplified for this discussion):

class MyCustomProperty<T>
{
  T Value { get; set;}
}

class MyCustomClass
{
  public MyCustomProperty<String> Prop1 {get; protected set;}
}

I would like to serialize MyCustomClass as if it was written as:

class MyCustomClass //simple version
{
  public String Prop1;
}

Is there a simple way for the serializer to see Prop1 as it's underlying type.  My first shot was going to be to implement IXmlSerializable on MyCustomProp but I was wondering if there was a better way. Ideally, a user could serialize MyCustomClass with any serializer and get an xml stream that looked exactly like the xml from //simple version if serialized with the same serializer.  In other words, does implementing IXmlSerializable handcuff me to the XmlSerializer rather than the DataContractSerializer?




View Complete Post


More Related Resource Links

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 ???



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

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

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 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"

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?

Logging Simply Not Working

  
I have been trying now for hours to get basic logging working in SQL2005 and have had zero luck. I have a very simple package. It consists of one task: abckup a user database. I create a Connection Manager that isa file connection manager. I choose the location of the file and choose "Create File". The directory exists. I'm an administrator on the box in question. In the package I choose "SSIS", go to Logging. I choose the component I want to log for. I add a logging provider for text files and choose the appropriate connection manager. On the details pane, I pick every category, and for each category I pick every event. So regardless, there should be SOMETHING logged. I choose "Save" and give a name for the xml file. I choose okay. I then choose "Save All". I run the package. Nothing is logged. The file never gets created. I haev seen dozens of people having the asme issue and their questions seem to go unanswered. This should be the easiest thing to do, so why is this so difficult to get to work properly? Any help would be appreciated.A. M. Robinson

How do I parse/serialize when parent list element is missing?

  
First thank you ahead of time for you help. I really need some help with this. Background, this is to be a REST service in .net 4.0 and I understand I have to use xmlserializer instead of datacontract serializer. The xsd and the generated class assumes there can be one or more geo locations in a Locations element. However, based on an unchangable requirement, I have to assume the parent Locations element may not be there and the xml can contain only one child location element. So instead of <?xml version="1.0" encoding="UTF-8"?> <findService   xmlns="urn:ietf:params:xml:ns:lost1"   xmlns:p2="http://www.opengis.net/gml"   serviceBoundary="value"   recursive="true"> <Locations>   <location id="12334456" profile="geodetic-2d">     <p2:Point id="point1" srsName="urn:ogc:def:crs:EPSG::4326">       <p2:pos>40.85614955747385 -73.77044677734375</p2:pos>     </p2:Point>   </location> </Locations>   <service>urn:service:sos</service> </findService> they can send the following instead <?xml version="1.0" encoding="UTF-8"?> <findService   xmlns="urn:ietf:params:xml:ns:lost1&

XmlSerializer: Serialize an array of System.Drawing.Color

  
Ok,  here is my problem... I am building a UI configuration tool that utiliizes a PropertyGrid.  One of the properties is a indexed list of Colors contained in an array: CategoryAttribute("Style"), DisplayName("Data Set Colors"), DescriptionAttribute(""), XmlArray("SetColors"), XmlArrayItem(ElementName="Color",Type=typeof(SColor))] public Color[] SetColors { get; set; } The beauty of the PropertyGrid is it knows how to handle this Poperty and properly handles array and list of Colors. BUT...   As we already know in order to serialize a Color,  we have to use a surrigate property,  which is very unfortunate, and I fear is one of those little thing MS just overlooked.  (I understand it is actually a structure and not a class and has not default properties from which to get type info from.) I am really amazed that when I do serialize the class,  the XML is soooo  close to what I need,  its just missing the actual color value data: <AppGridColumnConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Name>Label</Name> <SetColors> <Color /> <Color /> <Color /> </SetColors> <IsDefaultEditable>false</IsDefaultEditable> <IsDirtyCheck&

Serialize parameter array

  
Hello again, Since there was no response to my first attempt, I shall re-phrase my question. What I need to do is save an object to an image column in an sql database. Now, as I understand it, any object can be serialized as long as it implements ISerializable. So I did that. Now I run into the issue of - the objects members must implement ISerializable as well. The reason for this is that I need to be able to execute several sqlcommands to create a object containing several datatables. What I need to do is save the parameters (search criteria) somehow so that I can execute the queries at a later time. I am thinking that I can make my own object which is composed of the several SqlParameter arrays, and convert it to a byte[] for inserting into a database as a "saved search criteria" or even put into the ViewState of a webform so that the page can execute the query without going thought the complex process of gather the values from the ui and creating the SqlParameters. Here is what I would like to persist to a byte[]. I have a simple collection of SqlParameter arrays. i.e - [Serializable()] public class SavedCriteria : ISerializable { public SqlParameter[] Params1; public SqlParameter[] Params2; //implement ISerializable public void GetObjectData(SerializationInfo info, StreamingContext context) {

How can Serialize ArrayList ?

  
Hi code sample?????????public class Employee :ISerializable { private int version =1; //ADD emoployee name in this list private ArrayList employeeList; private void  AddEmployee(){ // Adding employee to Employee List}protected TestData(SerializationInfo info,StreamingContext context) { this.version = info.GetInt32("version"); this.name = info.GetString("list"); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("version", this.version); info.AddValue("list", this.employeeList); } }   Thanks in Advance nayakam

How can I serialize out such an XML file?

  
<mappings>   <mapping>     <path>path</path>   </mapping> </mappings> I want exactly the same XML output as above, no any namespace, and the <mappings> has to be the root node. Here's the code. List<Mapping> mappings = new List<Mapping>(); XmlSerializer serializer = new XmlSerializer(typeof(List<Mapping>), new XmlRootAttribute("mappings")); StreamWriter sw = new StreamWriter("Mappings_Output.xml"); Mapping mapping = new Mapping(); mapping.Path = "path"; mappings.Add(mapping); serializer.Serialize(sw, mappings); sw.Close(); public class Mapping { private string _path = string.Empty; [XmlElement("path")] public string Path { get { return _path; } set { _path = value; } } } And the result xml file is here: <?xml version="1.0" encoding="utf-8"?> <mappings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Mapping> <path>path</path> </Mapping> </mappings> It's almost there, with the exception of some automatically added root node attributes, which i don't want. You Can't Stop Me!

Is there any way to serialize the Style ?.

  
I need to know the way to serialize the Style in WPF?..     List<DockingParams> dockingParamsList = GetDockingParams();     XmlSerializer serializer = new XmlSerializer(typeof(List<DockingParams>)); serializer.Serialize(writer, dockingParamsList); My DockingParams custom class has the Style property .. When the program comes to this XmlSerializer() line it throws the following exception. Stack Trace:-        InnerException: System.InvalidOperationException             Message=There was an error reflecting property 'DocumentTabControlStyle'.             Source=System.Xml             StackTrace:                  at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter)                  at System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter)    &nb

Columns collection of a DataGridView within a UserControl won't serialize to designer

  
First of all, I've found this issue on connect which describes my problems exactly, however, I've been able to find a workaround but I don't find it acceptable so I appeal to you for an idea of how to resolve this as cleanly as possible. What I've done is, I've applied a custom designer to my UserControl like so [Designer(typeof(CustomControlDesigner))]public partial class DataGridViewTag : UserControl, ISupportInitialize In the CustomControlDesigner I don't do much at this point, I set selection rules and add a few DesignerVerbs. The important thing is, I also EnableDesignMode for the DataGridView in my UserControl. Then, I expose DataGridView's DataSource and Columns collection like this: [Editor(typeof(CollectionEditor), typeof(UITypeEditor))][Category("Grid")][DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]public DataGridViewColumnCollection Columns{    get { return dgvList.Columns; } set { dgvList.Columns.Clear(); foreach (DataGridViewColumn col in value) dgvList.Columns.Add(col); }} [AttributeProvider(typeof(IListSource))] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [Category("Grid")] public object DataSource{ get { return dgvList.DataSource;&nbs
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