posted on Wednesday, January 21, 2004 8:42 PM by demiliani

Solve parameters ambiguity with Web Services

The most immediate solution is to have a lot of methods, each one for a special function (for example, for a Class Person you can have a method to print First Name and Last Name and another method to print the Corporate Name). But if you have 50 or more options? It's not a practicable choice.
An alternative way is to use a CHOICE element.
Let's see an example...

We have 2 Class:

public class PersonaFisica
{
 public string FirstName;
 public string LastName;
}

public class PersonaGiuridica
{
 public string CorporateName;
}

we can map the classes with a single property:

[XmlType(Namespace="urn:peway:datatypes")]
public class Contact
{
 public string CodiceFiscale;

 [XmlIgnore()]
 public TipoPersona Tipo;

 [XmlChoiceIdentifier("Tipo")]
 [XmlElement("PersonaFisica", typeof(PersonaFisica))]
 [XmlElement("PersonaGiuridica", typeof(PersonaGiuridica))]
 public object Persona;
}

where TipoPersona is an Enum Type:

public enum TipoPersona
{
 PersonaFisica,
 PersonaGiuridica
}

in this way we inform the XML serializer that the property Persona can be PersonaGiuridica and PersonaFisica.
The XmlChoiceIdentifierAttribute is used to identify which class we're using with the Enum. When a SOAP message arrives, the XML deserializer check the type of Persona and will map it on the correspondent type.

So you can print the names based on the Enum value:

[WebService(Namespace="urn:peway:services")]
public class Contacts
{
 [WebMethod]
 public string PrintName(Contact contact)
 {
  switch(contact.Tipo)
  {
   case TipoPersona.PersonaFisica:
    PersonaFisica pf = (PersonaFisica)contact.Persona;
    return string.Concat(pf.Nome, " ", pf.Cognome);
   case TipoPersona.PersonaGiuridica:
    PersonaGiuridica pg = (PersonaGiuridica)contact.Persona;
    return pg.RagioneSociale;
   default:
    return "Not recognized Person";
  }
 }
}

Comments