2
votes

I'm trying to move an existing code to use ProtoBuf-Net. Some classes have DataContract but DataMembers has no order, this results with ignoring these properties instead of serializing them.

Is there a way to tell ProtoBuf-Net to serialize only classes that are marked with [ProtoContract] and throw exception when trying to serialize classes with [XmlType] or [DataContract]? If it's possible, will the other system classes (for example System.String) be serialized correctly using GPB?

Thanks.

1
Can you add more context? What is doing the serializing here? If the aim is to throw exceptions for those types, then that suggests you shouldn't be serializing those types. If that is the case, just don't give it those types ? So: what is calling Serialize here?Marc Gravell♦
I can check whether the type has ProtoContractAttribute and based on that decide whether to serialize or not. It get's complicated when I have a collection (that can be serialized correctly) but it contains an item that has DataContractAttribute but missing ProtoContractAttribute. I'd like to throw an exception in that case and not serialize the list.Oron Nadiv
Collection is just an example. It can come in the form of class A that has Property that returns class B, while A has ProtoContractAttribute and B has DataContractAttribute. I'd like not to serialize A and instead throw an exception.Oron Nadiv

1 Answers

2
votes

Fair question; it isn't a scenario that has come up before, but it is a fair-enough scenario, and is pretty easily solved, thankfully... I've added AutoAddProtoContractTypesOnly to RuntimeTypeModel in r567. If you are using the v1-style Serializer.Serialize(...) methods, then you can apply this via:

RuntimeTypeModel.Default.AutoAddProtoContractTypesOnly = true;

(all the Serializer.* methods are mapped to the RuntimeTypeModel.Default model instance)

Here's my now-passing test:

[Test]
public void ExecuteWithoutAutoAddProtoContractTypesOnlyShouldWork()
{
    var model = TypeModel.Create();
    Assert.IsInstanceOfType(typeof(Foo), model.DeepClone(new Foo()));
}
[Test, ExpectedException(typeof(InvalidOperationException),
    ExpectedMessage = "Type is not expected, and no contract can be inferred: Examples.Issues.SO11871726+Foo")]
public void ExecuteWithAutoAddProtoContractTypesOnlyShouldFail()
{
    var model = TypeModel.Create();
    model.AutoAddProtoContractTypesOnly = true;
    Assert.IsInstanceOfType(typeof(Foo), model.DeepClone(new Foo()));
}

[DataContract]
public class Foo { }