I am working on Sharing DataContracts between WCF Services using the svcutil.exe
tool
I have defined [DataMembar]
in library. For sharing data contract I am converting DataContract.dll
to DataContract.xsd
files.
Command is
svcutil /dconly <my DataContractDLL path>
After generating .xsd, I am generating class file from DataContract.xsd
using the command
svcutil /dconly /language:CS DataContract.xsd /out:ClientDataContracts.cs
Every thing went fine and worked in above steps.
Issue faced:
I added Dictionary
* type in one of the entities of my DataContract.dll
library as follows (ie I added TimeLogs
DataMember
of Dictionary
type.)
public partial class RecordDto
{
/// <summary>
/// Gets or sets the Comment.
/// </summary>
/// <value>Insurance Company.</value>
[WcfSerialization::DataMember(Name = "InsuranceCompany", IsRequired = false, Order = 25)]
public InsuranceCompanyDto InsuranceCompany { get; set; }
[WcfSerialization::DataMember(Name = "TimeLogs", IsRequired = false, Order = 26)]
public Dictionary<String, DateTime> TimeLogs
{
get;
set;
}
}
After adding the Dictionary
type I started getting errors while converting .xsd
to .cs
:
After adding Dictionary
type why I am getting the error?
How do I resolve it?
the interface IDictionary is not serializable, you should implement your own dictionary like this
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue>
: Dictionary<TKey, TValue>, IXmlSerializable
{
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement("value");
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
}
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.