Wednesday, April 06, 2005 8:31 PM Olaf Conijn

Writing XmlSerializer support by rightclicking the VS2K5 IDE

I’m pretty sure I heard about partial serialization in a talk about ASMX & the XmlSerializer on DevDays this year. After digging through my CTP 2 release of VS 2K5 I wasn’t able to find a trace of this partial serializing thing by the XmlSerializer class.... :-/.

 

Back to the 'good old' method of writing XmlSerializer support on types the XmlSerializer doesn’t handle. For my particular needs this resulted in the following code fragments:

 

1.) Serializing a Dictionary<K, V> with the XmlSerializer (example only uses Dictionary<string, ContainerDefinition>:

[XmlIgnore()]

 

public Dictionary<string, ContainerDefinition> ContainerDefinitions

 

{

 

      get { return _containerDefinitions; }

 

      set { _containerDefinitions = value; }

 

}

 

 

#region XmlSerializer support

 

 

[XmlArray("ContainerDefinitions")]

 

[XmlArrayItem("Item")]

 

public KeyValuePair<string, ContainerDefinition>[] ContainerDefintionItems

 

{

 

      get

 

      {

 

            List<KeyValuePair<string, ContainerDefinition>> containerDefinitionItemList

 

                  = new List<KeyValuePair<string, ContainerDefinition>>(ContainerDefinitions);

 

 

            return containerDefinitionItemList.ToArray();

 

      }

 

      set

 

      {

 

            List<KeyValuePair<string, ContainerDefinition>> containerDefinitionItemList

 

                  = new List<KeyValuePair<string, ContainerDefinition>>(value);

 

 

            ContainerDefinitions = new Dictionary<string, ContainerDefinition>(containerDefinitionItemList.Count);

 

            foreach (KeyValuePair<string, ContainerDefinition> item in containerDefinitionItemList)

 

            {

 

                  ContainerDefinitions.Add(item.Key, item.Value);

 

            }

 

      }

 

}

 

 

#endregion

 


2.) Serializing a Type with the XmlSerializer

[XmlIgnore]

 

public Type ServiceActivatorType

 

{

 

      get { return _serviceActivatorType; }

 

      set { _serviceActivatorType = value; }

 

}

 

 

#region XmlSerializer support

 

 

[XmlElement("ServiceActivatorType")]

 

public string ServiceActivatorTypeName

 

{

 

      get { return (ServiceActivatorType != null) ? ServiceActivatorType.AssemblyQualifiedName : null; }

 

      set { ServiceActivatorType = Type.GetType(value, false); }

 

}

 

 

#endregion

 



One useful thing I did find in VS.NET 2K5 are ‘template expansions’ (or ‘snippets’). These snippets make writing the code above as right clicking the IDE and filling in the blanks.

 

I zipped the snippets I created out of both XmlSerializer support methods, you can find them here. The snippets in the file should be registered in the IDE’s ‘Code Snippet Manager’ under the ‘Tools’ menu.