Custom Type within ArrayList inside of the user profile in C#
I'm getting the following error when trying to save a custom class within my ArrayList within my user profile:
There was an error generating the XML document. ---> System.InvalidOperationException: The type Com.xxx.MyDataClass was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
My web.config has something like:
<profile enabled="true" automaticSaveEnabled="false" defaultProvider="xxxxxxProvider">
<properties>
<add name="MyData" type="System.Collections.ArrayList"/>
</properties>
</profile>
I am trying to store my class called (something like) MyDataClass in an ArrayList into MyData. When I save I get the error above. The class MyDataClass has just two members for now, both set as 'string'.
I assume I have to tell the class has to serialize itself but I'm not sure how.
Here's the class:
namespace Com.xxxx.DataClasses
{
public class MyDataClass : ISerializable
{
public string elem1;
public string elem2;
public string Elem1
{
get { return elem1; }
set { elem1 = value; }
}
public string Elem2
{
get { return elem2; }
set { elem2 = value; }
}
....
UPDATE: FIXED
I was able to fix this issue via the following:
First of all here is a good resource: http://msdn.microsoft.com/en-us/library/d8b58y5d.aspx
I changed the profile entries to be:
<profile enabled="true" automaticSaveEnabled="false" defaultProvider="xxxxxxProvider">
<properties>
<add name="MyDat开发者_如何学Ca" type="mypackage.MyDataClass" serializeAs="binary"/>
</properties>
</profile>
and then I created MyDataClass to contain a List<> of MyDataClassInfo objects similar to:
namespace Com.xxxx.DataClasses
{
[Serializable]
public class MyDataClass
{
List<MyDataClassInfo> myDataClassInfo;
public MyDataClassInfo()
{
myDataClassInfo = new List<MyDataClassInfo>;
}
public List<MyDataClassInfo> MyDataClassInfo
{
get;
set;
}
}
[Serializable]
public class MyDataClassInfo
{
public string elem1;
public string elem2;
public string Elem1
{
get { return elem1; }
set { elem1 = value; }
}
public string Elem2
{
get { return elem2; }
set { elem2 = value; }
}
....
The key here was 1) using the serializeAt="binary" and 2) using a class which contained a list instead of a list within the profile.
You should never use the ArrayList
class. It is deprecated as of .NET 2.0.
Use List<MyDataClass>
instead. It may even solve this problem for you.
Try decorating MyDataClass with SerializableAttribute.
namespace Com.xxxx.DataClasses
{
[Serializable]
public class MyDataClass
{
public string elem1;
public string elem2;
public string Elem1
{
get { return elem1; }
set { elem1 = value; }
}
public string Elem2
{
get { return elem2; }
set { elem2 = value; }
}
....
精彩评论