I'm trying to use Microsoft's Serivce Bus Brokered Message APIs and I'm encountering deserialization issues when trying to use derived types. It seems like the code does not recognize the known types, and i have no issues when serializing these types and returning them between other services. Is there something I'm missing? I've gone through a ton of SO posts and nothing seemed to work.
Here is the message structure:
[DataContract]
[KnownType(typeof(ActivityBus))]
public class BaseBusType
{
[DataMember]
public int Id { get; set; }
}
[DataContract]
public class ActivityBus : BaseBusType { }
I've tried these options so far:
// In the sending function
var brokeredMessage = new BrokeredMessage(reader.ReadToEnd());
topicClient.Send(obj);
// In the receiving function
List<Type> knownTypes = new List<Type>() { typeof(ActivityBus) };
var serializer = new DataContractSerializer(typeof(BaseBusType), knownTypes); // listed knowntypes for brevity
var messageBody = message.GetBody<BaseBusType>(serializer);
Also:
// In the sending function
using (MemoryStream memoryStream = new MemoryStream())
using (StreamReader reader = new StreamReader(memoryStream))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(memoryStream, data);
memoryStream.Position = 0;
var brokeredMessage = new BrokeredMessage(reader.ReadToEnd());
topicClient.Send(brokeredMessage);
}
// In the receiving function
using (Stream stream = new MemoryStream())
{
var str = brokeredMessage.GetBody<string>();
byte[] data = System.Text.Encoding.UTF8.GetBytes(str);
stream.Write(data, 0, data.Length);
stream.Position = 0;
List<Type> knownTypes = new List<Type>() { typeof(Activitybus) };
var deserializer = new DataContractSerializer(typeof(BaseBusType), knownTypes);
var reader = XmlReader.Create(new StringReader(str));
var obj = deserializer.ReadObject(reader);
return (T)obj;
}