Custom Web Part Property Restrictions

After a nice call to Microsoft Developer Support, I learned the root of some of my web part development troubles and thought I'd share the [undocumented] wealth with the community.

Web part properties can only be:
  • string
  • bool
  • int
  • float
  • enum
  • System.DateTime
  • System.Drawing.KnownColor
The reason for this is that they use their own custom XML Serializer, not the standard one that .NET Framework ships with. (That's why I keep getting errors when I try to save custom classes as properties. Even if they're marked Serializable and have all the XML Serialization info attached to them, you can't do it. This is all you get.)

So I guess my way around that's going to have to be to XML Serialize my custom class, then save that as a string in the web part. What a pain.

Print | posted @ Thursday, December 11, 2003 5:50 PM

Comments on this entry:

Gravatar # Re: Custom Web Part Property Restrictions
by Travis at 2/11/2004 6:09 PM

Actually, what I ended up doing was creating a strongly-typed dataset that would essentially hold only one row of values. Each column in the dataset represented a custom setting or property the user can set up, and the value in the column ended up being the property value.

Once you create your strongly-typed Dataset, you can do something like:

<pre>string serializedSettings = myStrongTypeSet.GetDataSet().GetXml();</pre>

That'll get your data from your dataset into an XML node. Note that if you have more than one row in there, you may end up with an XML document fragment instead of an a valid XML document, so you may want to do a little massaging to make that work to your satisfaction.

To get your DataSet back out of the XML (and I'm sure I'm going about this the hard way), you have to read the XML back from a stream - you can't just read it from a string. That makes it tougher. So you'll do something like:

<pre>MemoryStream stream = null;
StreamWriter writer = null;
MyDataSet ds = null;

try{
// Create a stream and writer to put the XML into
stream = new MemoryStream();
writer = new StreamWriter(stream);

// Put the XML for the dataset into the stream
writer.Write(serializedSettings);
writer.Flush();

// Create the new typed dataset
ds = new MyDataSet();
stream.Seek(0, SeekOrigin.Begin);
ds.ReadXml(stream);
}
finally{
// Stream cleanup
if(writer != null){
writer.Close();
writer = null;
}
if(stream != null){
stream.Close();
stream = null;
}
}</pre>

Obviously you'll have to adapt that to your own purposes, but that's generally how I ended up solving the problem.

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 7 and 2 and type the answer here: