Search code examples
c#castingnavisiondynamics-nav

Parsing a dynamic enumeration


We are using a Microsoft ERP which dynamically exposes web services. The services generated by the service is out of our control. We have no say so in how the objects, including the type definitions, are created and exposed. When a new method is added or removed from the web service, all of the type enumerations are renumbered and everything that uses the web service, after updating to the new definitions, is hosed up. So essentially,

enumeration Type1
  Item1
  Item2
  Item3

... could become

enumeration Type6
  Item1
  Item2
  Item3

...with the enumeration type name changing, but members of the type remaining static. The service outputs a service which looks exactly like the end result of using the XSD.exe to generate objects. So anytime someone exposes a new method on the service (via the ERP GUI), the objects are rebuilt, types are assigned to the service definitions in alphabetical order, reexposed, leaving the entire code base shot.

I attempted to use reflection to determine the type and then parse out the static member into the new business object, but it doesn't work because I can't type cast the enumeration without knowing the actual name of the type. The following won't work.

System.Type t = service.BusinessObjectEnumeration.GetType();
service.SomeField = Enum.Parse(t,"Item1");

...as the compiler throws an error because I'm not explicitly casting the enumeration.

Any ideas how I can overcome this issue while dynamically casting the type to the correct enumeration?

Again, I cannot modify the actual objects exposed by the service, only the code subscribing to the service.


Solution

  • Re the example code:

    System.Type t = service.BusinessObjectEnumeration.GetType();
    service.SomeField = Enum.Parse(t,"Item1");
    

    Maybe the way to do this is via reflection:

    var prop = service.GetType().GetProperty("SomeField");
    prop.SetValue(service, Enum.Parse(prop.PropertyType, "Item1"), null);