-1

Background:

  1. WCF service proxy not setting "FieldSpecified" property
  2. MSDN Forums: parameter-names-ending-with-specified-added-to-web-service-method-call?forum=wcf

I am fed up with having to manually set dozens of "_Specified" fields in my web-service client (for Struct datatypes like Long and DateTime), so I thought I'd try looping through all of the properties in my Soap Body and if it's a Boolean called Specified AND if the property (such as a Birthdate) has been set, then I could default that property to true.

So I wrote this code to loop through, and check if the property isn't null then if not, set the corresponding Specified property to true:

    Type type = wsSoapBody.GetType();

    PropertyInfo[] properties = type.GetProperties();

    foreach (PropertyInfo property in properties)
    {
        foreach (var pi in wsSoapBody.GetType().GetProperties().Where(o => o.Name == property.Name + "Specified"))
        {
            if (property != null)
            {
                pi.SetValue(wsSoapBody, true, BindingFlags.SetField | BindingFlags.SetProperty, null, null, null);
            }
        }            
    }

Unfortunately, even if some properties haven't been set, property != null is always true, so even when a field has not been set, this Boolean value is being set to true, and that's not what I want.

How could I do this properly?

EDIT:

to clarify, say I have a field in my soap body type called Birthdate (which is a datetime) then in WCF web-service client proxy there will also be a property called BirthDateSpecified and that is what I need to set to true if BirthDate has been set.

Community
  • 1
  • 1
Our Man in Bananas
  • 5,809
  • 21
  • 91
  • 148

1 Answers1

2

Because you are checking if property info is not null, not the value of property.You need to get property value using GetValue method then check whether it is null.

if (property.GetValue(wsSoapBody,null) != null))
{
    pi.SetValue(wsSoapBody, true, BindingFlags.SetField | BindingFlags.SetProperty, null, null, null);
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • so wouldn't that be `if (property.GetValue(wsSoapBody,null) != null)` as I need to check if the property is null, rather than *propertySpecified* ? – Our Man in Bananas Feb 13 '15 at 17:58
  • 1
    @OurManInBananas you wanna set the property if the value is null, right? then it should be `==` not `!=`. and you should get the value of `pi` not `property` if I'm not missing something. – Selman Genç Feb 13 '15 at 17:59
  • well, `pi` should be the *propertySpecified* Boolean value, I only want to set that if the property it is specifying is populated. So for example, if `BirthDate` is specified, then I need to set `BirthDateSpecified=true` ... – Our Man in Bananas Feb 13 '15 at 18:02
  • 1
    @OurManInBananas okey then it should be `if (property.GetValue(wsSoapBody,null) != null)` – Selman Genç Feb 13 '15 at 18:11