How to remove a property from class at run time - c#

Is it possible to remove a property from class at runtime, like:
public Class A
{
public int num1 {get;set;}
public int num2 {get;set;}
public int num3 {get;set;}
}
Class A Obj = new A();
At run time I want to remove num2 from obj. Is it possible?

This can't be done. Once compiled, a class definition is set.

As others said already, it's not possible.
Instead you can add another property e.g.
public List<string> ignoredProperties {get; set;}
Then at runtime add num2 to that list and check it for properties you should ignore.

You have to comeup with Model/ViewModel approach. Create a ViewModel which will have limited properties for your requirement.

I agree with Nic reply: This can't be done. Once compiled, a class definition is set.
But you can create a class property dynamically what you want by reflection.

My case was much easier
I have a class which is POST
then I need to remove few properties and save this to JSON
I did go around with System.Dynamic.ExpandoObject copy the class
Object value;
System.Dynamic.ExpandoObject cloneData = JsonSerializer.Deserialize<ExpandoObject>(JsonSerializer.Serialize(data));
cloneData.Remove("IP", out value);
value = value;
cloneData.Remove("analytics", out value);
value = value;
string azurecontainer = #"data";
string azureblobJSONDataFilename = #"profile/" + _userInfoSessionB.u + #".json";
string JSONData = JsonSerializer.Serialize(cloneData);
object p = azureStorage.UploadBlob2ContainerTextAsync(JSONData, azurecontainer, azureblobJSONDataFilename, "application/json", "public, max-age=30");

I was not able to REMOVE the property, I was trying to create a dynamic JSON, with 2 different classes merged together but without some properties (not needed for that merged class), so what I did was, I added a custom attribute and added to field/properties which I didn't need, and used reflection to create a custom JSON at runtime after merging 2 classes.

I had a very exact use case. In my case, I want to ignore some properties when posting the data model to ODATA via Json. This property may not be a table field so I want to ignore while serializing this to JSON. I achieved this by below steps.
I used the DataAnnotations to decorate that attribute as [ReadOnly(true)]
I then created a custom JsonSerializer from ISerializer to ignore the ReadOnly Properties like below:
public string Serialize(object obj)
{
return JsonSerializer.Serialize(obj,
new JsonSerializerOptions
{
IgnoreReadOnlyProperties = true
});
}
This solved my problem to ignore some properties that I don't want to pass via Json/OData calls or any Api/endpoint wherever it is.

//Convert your object to JObject
var jsonDoc = JObject.FromObject(doc);
//Select the Property To Remove
var PropertyToRemove= jsonDoc.Property("PropertyToRemove");
// Remove the Property
sig.Remove();

Related

Accessing properties with a dot in their name

I am trying to deserialize JSON. My root object has a single property "en.pickthall". I am using dynamic type for reading my JSON. I thought I could just do away with "." in the property since its a local JSON file but then there must be some way to access such a property
var result = App_Code.FileIOHelper.ReadFromDefaultFile("ms-appx:///Assets/en.pickthall.json");
dynamic stuff = JsonConvert.DeserializeObject(result);
foreach(var x in stuff.(en.pickthall)) //Tried this intellisense didn't like it
{
}
You could create a root class to deserialize into and use JsonProperty
public class Root
{
// Use the proper type instead of object
[JsonProperty(PropertyName = "en.pickthall")]
public IEnumerable<object> EnPickthall { get; set; }
public Root() { }
}
Used as follows
Root stuff = JsonConvert.DeserializeObject<Root>(result);
foreach(var x in stuff.EnPickthall)
{
}
You could serialize not to dynamic but to JObject and then access your property via
JObject stuff = JsonConvert.DeserializeObject<JObject>(Jsonstring);
var x = stuff.Value<String>("my.property")
C# doesn't have any way of quoting identifiers. If it's not a valid identifier, your only option is reflection.
However, it's possible the object returned by your JSON deserializer changed the identifiers to make them useable in C# - you might want to enumerate all the properties to check if that is the case. A dynamic object with indexers might also be a solution (allowing e.g. stuff["en.pickthall"]).
Another alternative is to change the way the serializer maps properties. For example, Newtonsoft.Jsoft allows you to customize this using a IContractResolver. It's quite easy to replace the . for something more C#-sane in this way.
I know you said you were using a dynamic type for your JSON deserialization, but I just wanted to point out that there is a .NET RESTful client out there that supports this with static model definitions too. For you or for anyone else who happens upon this response when searching for an answer to their problems with dots in property names in C# REST calls.
As of the newly released RestSharp 106.1.0 (and I do mean this version because this support was just added), it can handle renaming properties with a dot in their name via the DeserializeAs attribute. An example being when I call the ElasticSearch API for a _cat call with the following model:
public class CatResponse
{
public string index { get; set; }
...
[DeserializeAs(Name = "docs.count")]
public string docscount { get; set; }
}
And actually get back the docs.count property deserialized into docscount now:
var resource = $"_cat/indices/{indexPattern}?format=json&pretty=true";
var request = new RestRequest(resource, Method.GET);
var response = client.Execute<List<CatResponse>>(request);
This support is out of the box and doesn't need to use the Newtonsoft.Json.JsonSerializer which I have also heard is a possible solution to this problem but which I couldn't get to work.
With a dynamic object and NewtonSoft.Json:
dynamic json = JValue.Parse(result);
int Opens = Convert.ToInt32(json.opens);
int Clicks = Convert.ToInt32(json.clicks);
string State = json.state;

JsonProperty - Use different name for deserialization, but use original name for serialization?

I am retrieving JSON from an API. I am using newtonsoft (this is json.net right?) to deserialize this into a list of objects. It works.
Unfortunately I also need to pass this along to someone else as JSON (they can't call the API directly only I have access to it). I say unfortunately because I need to OUTPUT my JSON that is different from what is being received (the property names need to be different).
For example, I have a class called Person, with a property called Name. I want to get "People", so I make my request to that API to get JSON as above, and get back a list of Person. Unfortunately the API doesn't return me people with Name properties, it returns me pname. So to map this, I just do:
[JsonProperty("pname")]
This is all well and good - it converts pname to name and my class now has the value! I have a list of people with names.
Now I need to give this list of objects BACK to someone else as "Name", However when I serialize my people class back to JSON, it writes out the JSON as "pname" when I really want to write it out as "Name". I suspect it's picking up the "JsonProperty".
Is there a way to just have it use pname for deserialization, but use the original property value for serialization?
Thanks!
You can create a custom contract resolver that sets the property names back to the ones you've defined in the C# class before serilization. Below is some example code;
class OriginalNameContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
// Let the base class create all the JsonProperties
IList<JsonProperty> list = base.CreateProperties(type, memberSerialization);
// assign the C# property name
foreach (JsonProperty prop in list)
{
prop.PropertyName = prop.UnderlyingName;
}
return list;
}
}
Use it like this;
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Formatting = Formatting.Indented;
if (useLongNames)
{
settings.ContractResolver = new OriginalNameContractResolver();
}
string response = JsonConvert.SerializeObject(obj, settings);
Maybe I'm late to the party, but this also works:
[JsonPropertyName("pname")]
public string? PName { private get; set; }
public string? Name => PName;
You might be able to write a custom JsonConverter to do it with just one Person class, but I'd recommend having separate classes, since the data is modeled differently in the two places. Even if you don't plan to right now, you might find yourself needing to deserialize from Name or serialize to pname at some point. This also allows your classes to differ more substantially. You could use AutoMapper (or similar) to easily convert between the two. E.g.
public class PersonFromThatApi
{
[JsonProperty("pname")]
public string Name { get; set; }
}
public class Person
{
public string Name { get; set; }
}
Mapper.CreateMap<PersonFromThatApi, Person>();
Mapper.CreateMap<Person, PersonFromThatApi>();
var person1 = JsonConvert.DeserializeObject<PersonFromThatApi>(
#"{""pname"":""George""}");
Person person2 = Mapper.Map<Person>(person1);
string s = JsonConvert.SerializeObject(person2); // {"Name":"George"}
And yes, Newtonsoft.Json is the namespace of Json.NET. Don't ask me why they chose totally different names for those two things.
The simple solution is to create two properties.

XMLDeserialize, "There was an error reflecting type" [duplicate]

Using C# .NET 2.0, I have a composite data class that does have the [Serializable] attribute on it. I am creating an XMLSerializer class and passing that into the constructor:
XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
I am getting an exception saying:
There was an error reflecting type.
Inside the data class there is another composite object. Does this also need to have the [Serializable] attribute, or by having it on the top object, does it recursively apply it to all objects inside?
Look at the inner exception that you are getting. It will tell you which field/property it is having trouble serializing.
You can exclude fields/properties from xml serialization by decorating them with the [XmlIgnore] attribute.
XmlSerializer does not use the [Serializable] attribute, so I doubt that is the problem.
Remember that serialized classes must have default (i.e. parameterless) constructors. If you have no constructor at all, that's fine; but if you have a constructor with a parameter, you'll need to add the default one too.
I had a similar problem, and it turned out that the serializer could not distinguish between 2 classes I had with the same name (one was a subclass of the other). The inner exception looked like this:
'Types BaseNamespace.Class1' and 'BaseNamespace.SubNamespace.Class1' both use the XML type name, 'Class1', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type.
Where BaseNamespace.SubNamespace.Class1 is a subclass of BaseNamespace.Class1.
What I needed to do was add an attribute to one of the classes (I added to the base class):
[XmlType("BaseNamespace.Class1")]
Note: If you have more layers of classes you need to add an attribute to them as well.
Most common reasons by me:
- the object being serialized has no parameterless constructor
- the object contains Dictionary
- the object has some public Interface members
Also be aware that XmlSerializer cannot serialize abstract properties.. See my question here (which I have added the solution code to)..
XML Serialization and Inherited Types
All the objects in the serialization graph have to be serializable.
Since XMLSerializer is a blackbox, check these links if you want to debug further into the serialization process..
Changing where XmlSerializer Outputs Temporary Assemblies
HOW TO: Debug into a .NET XmlSerializer Generated Assembly
If you need to handle specific attributes (i.e. Dictionary, or any class), you can implement the IXmlSerialiable interface, which will allow you more freedom at the cost of more verbose coding.
public class NetService : IXmlSerializable
{
#region Data
public string Identifier = String.Empty;
public string Name = String.Empty;
public IPAddress Address = IPAddress.None;
public int Port = 7777;
#endregion
#region IXmlSerializable Implementation
public XmlSchema GetSchema() { return (null); }
public void ReadXml(XmlReader reader)
{
// Attributes
Identifier = reader[XML_IDENTIFIER];
if (Int32.TryParse(reader[XML_NETWORK_PORT], out Port) == false)
throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_PORT);
if (IPAddress.TryParse(reader[XML_NETWORK_ADDR], out Address) == false)
throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_ADDR);
}
public void WriteXml(XmlWriter writer)
{
// Attributes
writer.WriteAttributeString(XML_IDENTIFIER, Identifier);
writer.WriteAttributeString(XML_NETWORK_ADDR, Address.ToString());
writer.WriteAttributeString(XML_NETWORK_PORT, Port.ToString());
}
private const string XML_IDENTIFIER = "Id";
private const string XML_NETWORK_ADDR = "Address";
private const string XML_NETWORK_PORT = "Port";
#endregion
}
There is an interesting article, which show an elegant way to implements a sophisticated way to "extend" the XmlSerializer.
The article say:
IXmlSerializable is covered in the official documentation, but the documentation states it's not intended for public use and provides no information beyond that. This indicates that the development team wanted to reserve the right to modify, disable, or even completely remove this extensibility hook down the road. However, as long as you're willing to accept this uncertainty and deal with possible changes in the future, there's no reason whatsoever you can't take advantage of it.
Because this, I suggest to implement you're own IXmlSerializable classes, in order to avoid too much complicated implementations.
...it could be straightforward to implements our custom XmlSerializer class using reflection.
I just got the same error and discovered that a property of type IEnumerable<SomeClass> was the problem. It appears that IEnumerable cannot be serialized directly.
Instead, one could use List<SomeClass>.
I've discovered that the Dictionary class in .Net 2.0 is not serializable using XML, but serializes well when binary serialization is used.
I found a work around here.
I recently got this in a web reference partial class when adding a new property. The auto generated class was adding the following attributes.
[System.Xml.Serialization.XmlElementAttribute(Order = XX)]
I needed to add a similar attribute with an order one higher than the last in the auto generated sequence and this fixed it for me.
I too thought that the Serializable attribute had to be on the object but unless I'm being a complete noob (I am in the middle of a late night coding session) the following works from the SnippetCompiler:
using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.Xml.Serialization;
public class Inner
{
private string _AnotherStringProperty;
public string AnotherStringProperty
{
get { return _AnotherStringProperty; }
set { _AnotherStringProperty = value; }
}
}
public class DataClass
{
private string _StringProperty;
public string StringProperty
{
get { return _StringProperty; }
set{ _StringProperty = value; }
}
private Inner _InnerObject;
public Inner InnerObject
{
get { return _InnerObject; }
set { _InnerObject = value; }
}
}
public class MyClass
{
public static void Main()
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
TextWriter writer = new StreamWriter(#"c:\tmp\dataClass.xml");
DataClass clazz = new DataClass();
Inner inner = new Inner();
inner.AnotherStringProperty = "Foo2";
clazz.InnerObject = inner;
clazz.StringProperty = "foo";
serializer.Serialize(writer, clazz);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
}
I would imagine that the XmlSerializer is using reflection over the public properties.
Sometime, this type of error is because you dont have constructur of class without argument
I had a situation where the Order was the same for two elements in a row
[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "SeriousInjuryFlag")]
.... some code ...
[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "AccidentFlag")]
When I changed the code to increment the order by one for each new Property in the class, the error went away.
I was getting the same error when I created a property having a datatype - Type. On this, I was getting an error - There was an error reflecting type. I kept checking the 'InnerException' of every exception from the debug dock and got the specific field name (which was Type) in my case. The solution is as follows:
[XmlIgnore]
public Type Type { get; set; }
Also note that you cannot serialize user interface controls and that any object you want to pass onto the clipboard must be serializable otherwise it cannot be passed across to other processes.
I have been using the NetDataSerialiser class to serialise
my domain classes. NetDataContractSerializer Class.
The domain classes are shared between client and server.
I had the same issue and in my case the object had a ReadOnlyCollection. A collection must implement Add method to be serializable.
I have a slightly different solution to all described here so far, so for any future civilisation here's mine!
I had declared a datatype of "time" as the original type was a TimeSpan and subsequently changed to a String:
[System.Xml.Serialization.XmlElementAttribute(DataType="time", Order=3)]
however the actual type was a string
public string TimeProperty {
get {
return this.timePropertyField;
}
set {
this.timePropertyField = value;
this.RaisePropertyChanged("TimeProperty");
}
}
by removing the DateType property the Xml can be serialized
[System.Xml.Serialization.XmlElementAttribute(Order=3)]
public string TimeProperty {
get {
return this.timePropertyField;
}
set {
this.timePropertyField = value;
this.RaisePropertyChanged("TimeProperty");
}
}
[System.Xml.Serialization.XmlElementAttribute("strFieldName", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
Or
[XmlIgnore]
string [] strFielsName {get;set;}

Why isn't my public property serialized by the XmlSerializer?

This is one i struggled with for ages so thought I'd document somewhere. (Apologies for asking and answering a question.)
(C# .net 2.0)
I had a class that was being serialized by XmlSerializer, I added a new public property however it wasn't being included in the output XML.
It's not mentioned in the docs anywhere I could find, but public properties must have a set as well as a get to be serialized! I guess this is because it assumes that if you're going to serialize then you'll want to deserialize from the same file, so only serializes properties that have both a set and a get.
As mentioned, most properties must have both a getter and setter; the main exception to this is lists - for example:
private readonly List<Foo> bar = new List<Foo>();
public List<Foo> Bar {get { return bar; } } // works fine
which will work fine; however, if XmlSerializer finds a setter - it demands that it is public; the following will not work:
public List<Foo> Bar {get; private set;} // FAIL
Other reasons it might not serialize:
it isn't public with get and set (or is readonly for a field)
it has a [DefaultValue] attribute, and is with that value
it has a public bool ShouldSerializeFoo() method that returned false
it has a public bool FooSpecified {get;set;} property or field that returned false
it is marked [XmlIgnore]
it is marked [Obsolete]
Any of these will cause it not to serialize
The point about getter+setter is made in the 3rd paragraph on the "Intro to Xml Serialization" page. It's actually in a call-out box. Can't miss it!
Intro-to-XML Serialization http://www.freeimagehosting.net/uploads/2f04fea2db.png
(having a little too much fun with Freeimagehosting.net)
Also properties that return null are not serialized!
if you don't want to implement proper Setters (because maybe you are neither wanting to deserialize or change an objects value) you can just use dummy setters like this set { }, so that the XMLSerializer works, but nothing happens if you use the Setter...
i.E.
public string ID { get { return _item.ID.ToString(); } set { } }
And if your class inherits a list and also has its own members, only the elements of the list get serialized. The data present in your class members is not captured.
Took some time figuring out this!
One more thing to add about serialization of collections:
The XmlSerializer ignores collections of interfaces!
And by that I mean ignore. While you will get an exception for a line like:
public IFoo Foo { get; set; }
you will not get an exception for:
public ICollection<IFoo> LotsOfFoos { get { return this.fooBackingField; } }
You can implement the IXmlSerializer and do the serialization manually, and benefit from serializing properties, and vice versa, deserializing them using constructors / private field assignment.

XmlSerializer - There was an error reflecting type

Using C# .NET 2.0, I have a composite data class that does have the [Serializable] attribute on it. I am creating an XMLSerializer class and passing that into the constructor:
XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
I am getting an exception saying:
There was an error reflecting type.
Inside the data class there is another composite object. Does this also need to have the [Serializable] attribute, or by having it on the top object, does it recursively apply it to all objects inside?
Look at the inner exception that you are getting. It will tell you which field/property it is having trouble serializing.
You can exclude fields/properties from xml serialization by decorating them with the [XmlIgnore] attribute.
XmlSerializer does not use the [Serializable] attribute, so I doubt that is the problem.
Remember that serialized classes must have default (i.e. parameterless) constructors. If you have no constructor at all, that's fine; but if you have a constructor with a parameter, you'll need to add the default one too.
I had a similar problem, and it turned out that the serializer could not distinguish between 2 classes I had with the same name (one was a subclass of the other). The inner exception looked like this:
'Types BaseNamespace.Class1' and 'BaseNamespace.SubNamespace.Class1' both use the XML type name, 'Class1', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type.
Where BaseNamespace.SubNamespace.Class1 is a subclass of BaseNamespace.Class1.
What I needed to do was add an attribute to one of the classes (I added to the base class):
[XmlType("BaseNamespace.Class1")]
Note: If you have more layers of classes you need to add an attribute to them as well.
Most common reasons by me:
- the object being serialized has no parameterless constructor
- the object contains Dictionary
- the object has some public Interface members
Also be aware that XmlSerializer cannot serialize abstract properties.. See my question here (which I have added the solution code to)..
XML Serialization and Inherited Types
All the objects in the serialization graph have to be serializable.
Since XMLSerializer is a blackbox, check these links if you want to debug further into the serialization process..
Changing where XmlSerializer Outputs Temporary Assemblies
HOW TO: Debug into a .NET XmlSerializer Generated Assembly
If you need to handle specific attributes (i.e. Dictionary, or any class), you can implement the IXmlSerialiable interface, which will allow you more freedom at the cost of more verbose coding.
public class NetService : IXmlSerializable
{
#region Data
public string Identifier = String.Empty;
public string Name = String.Empty;
public IPAddress Address = IPAddress.None;
public int Port = 7777;
#endregion
#region IXmlSerializable Implementation
public XmlSchema GetSchema() { return (null); }
public void ReadXml(XmlReader reader)
{
// Attributes
Identifier = reader[XML_IDENTIFIER];
if (Int32.TryParse(reader[XML_NETWORK_PORT], out Port) == false)
throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_PORT);
if (IPAddress.TryParse(reader[XML_NETWORK_ADDR], out Address) == false)
throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_ADDR);
}
public void WriteXml(XmlWriter writer)
{
// Attributes
writer.WriteAttributeString(XML_IDENTIFIER, Identifier);
writer.WriteAttributeString(XML_NETWORK_ADDR, Address.ToString());
writer.WriteAttributeString(XML_NETWORK_PORT, Port.ToString());
}
private const string XML_IDENTIFIER = "Id";
private const string XML_NETWORK_ADDR = "Address";
private const string XML_NETWORK_PORT = "Port";
#endregion
}
There is an interesting article, which show an elegant way to implements a sophisticated way to "extend" the XmlSerializer.
The article say:
IXmlSerializable is covered in the official documentation, but the documentation states it's not intended for public use and provides no information beyond that. This indicates that the development team wanted to reserve the right to modify, disable, or even completely remove this extensibility hook down the road. However, as long as you're willing to accept this uncertainty and deal with possible changes in the future, there's no reason whatsoever you can't take advantage of it.
Because this, I suggest to implement you're own IXmlSerializable classes, in order to avoid too much complicated implementations.
...it could be straightforward to implements our custom XmlSerializer class using reflection.
I just got the same error and discovered that a property of type IEnumerable<SomeClass> was the problem. It appears that IEnumerable cannot be serialized directly.
Instead, one could use List<SomeClass>.
I've discovered that the Dictionary class in .Net 2.0 is not serializable using XML, but serializes well when binary serialization is used.
I found a work around here.
I recently got this in a web reference partial class when adding a new property. The auto generated class was adding the following attributes.
[System.Xml.Serialization.XmlElementAttribute(Order = XX)]
I needed to add a similar attribute with an order one higher than the last in the auto generated sequence and this fixed it for me.
I too thought that the Serializable attribute had to be on the object but unless I'm being a complete noob (I am in the middle of a late night coding session) the following works from the SnippetCompiler:
using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.Xml.Serialization;
public class Inner
{
private string _AnotherStringProperty;
public string AnotherStringProperty
{
get { return _AnotherStringProperty; }
set { _AnotherStringProperty = value; }
}
}
public class DataClass
{
private string _StringProperty;
public string StringProperty
{
get { return _StringProperty; }
set{ _StringProperty = value; }
}
private Inner _InnerObject;
public Inner InnerObject
{
get { return _InnerObject; }
set { _InnerObject = value; }
}
}
public class MyClass
{
public static void Main()
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
TextWriter writer = new StreamWriter(#"c:\tmp\dataClass.xml");
DataClass clazz = new DataClass();
Inner inner = new Inner();
inner.AnotherStringProperty = "Foo2";
clazz.InnerObject = inner;
clazz.StringProperty = "foo";
serializer.Serialize(writer, clazz);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
}
I would imagine that the XmlSerializer is using reflection over the public properties.
Sometime, this type of error is because you dont have constructur of class without argument
I had a situation where the Order was the same for two elements in a row
[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "SeriousInjuryFlag")]
.... some code ...
[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "AccidentFlag")]
When I changed the code to increment the order by one for each new Property in the class, the error went away.
I was getting the same error when I created a property having a datatype - Type. On this, I was getting an error - There was an error reflecting type. I kept checking the 'InnerException' of every exception from the debug dock and got the specific field name (which was Type) in my case. The solution is as follows:
[XmlIgnore]
public Type Type { get; set; }
Also note that you cannot serialize user interface controls and that any object you want to pass onto the clipboard must be serializable otherwise it cannot be passed across to other processes.
I have been using the NetDataSerialiser class to serialise
my domain classes. NetDataContractSerializer Class.
The domain classes are shared between client and server.
I had the same issue and in my case the object had a ReadOnlyCollection. A collection must implement Add method to be serializable.
I have a slightly different solution to all described here so far, so for any future civilisation here's mine!
I had declared a datatype of "time" as the original type was a TimeSpan and subsequently changed to a String:
[System.Xml.Serialization.XmlElementAttribute(DataType="time", Order=3)]
however the actual type was a string
public string TimeProperty {
get {
return this.timePropertyField;
}
set {
this.timePropertyField = value;
this.RaisePropertyChanged("TimeProperty");
}
}
by removing the DateType property the Xml can be serialized
[System.Xml.Serialization.XmlElementAttribute(Order=3)]
public string TimeProperty {
get {
return this.timePropertyField;
}
set {
this.timePropertyField = value;
this.RaisePropertyChanged("TimeProperty");
}
}
[System.Xml.Serialization.XmlElementAttribute("strFieldName", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
Or
[XmlIgnore]
string [] strFielsName {get;set;}

Categories