johnny 5
johnny 5

Reputation: 20987

WCF ensure that the necessary enum values are present

I'm trying to serialize enum values which potentially do not exist yet. I have an existing project which has several enums in our datacontract for simplicity reason I display one like so:

public partial class TestDTO : ITestDTO
{
    public DeleteMe DeleteMeEnum { get; set; }
}

[DataContract]
public enum DeleteMe 
{
    [EnumMember]
    Deleted = 0,
}

Our application has a hidden internal wcf layer which our public web api accesses. A sample Service contract looks like so:

[ServiceContract]
public interface ITestService
{
    [OperationContract]
    TestDTO GetTestDTO();
}

public class TestService : ITestService
{
    public TestDTO GetTestDTO()
    {
        return new TestDTO() { DeleteMeEnum = (DeleteMe)2 };
    }
}

When I call this method from WebApi obviously I get the classic error:

Enum value '2' is invalid for type 'DeleteMe' and cannot be serialized. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute.

I can't go and change all of the enums now because we have a massive project, and replacing them would be too much, Also replacing all of our Service Contracts with a new Attibute would be too much.

Does anyone know of a way I can fix this globally, such as replacing the default XMLSerializer with a custom XMLSerializer?

Upvotes: 1

Views: 2980

Answers (1)

BJury
BJury

Reputation: 2604

There isn't a nice way to handle this once your application is released. However if you plan for the situation ahead of time, it can be handled.

So for the example above, you can do this:

public partial class TestDTO : ITestDTO
{
    [DataMember(Name = "DeleteMeEnum")]
    private string DeleteMeEnumString 
    {
         get { return DeleteMeEnum.ToString(); }
         set {
              DeleteMe _enum;
              if (!Enum.TryParse(value, out _enum))
              {
                  _enum = <default value>;
              }
              DeleteMeEnum = _enum;
         }
    }   

    [IgnoreDataMember]
    public DeleteMe DeleteMeEnum { get; set; }
}

Upvotes: 1

Related Questions