views:

1575

answers:

3

I have created a web service via WCF. Then I exposed it as a web service to make it usable with a .NET 2.0 application. I created some DataContract with DataMember that could be used for by the exposed OperationContract.

I notice that when I try to create DataClass to be passed in the web service that each DataContract attribute now has a partner "Specified" attribute for each member.

For example: [DataContract] public class Sales {

[DataMember] public int InvoiceNo;

... }

When I create an instance of Sales in the web service client. I get attribute named InvoiceNo and InvoiceNoSpecified.

Now here is my question, when the attribute is of type string, I do not need to set the corresponding "Specified" attribute to true, but when the attribute type is a int or DateTime, if I do not set the corresponding "Specified" attribute to true, the value becomes null in the web service host. Is there a way to avoid setting the Specified attribute? Cause I need to call the web service functions in a lot of places in my code. It would really be difficult to keep track of them all.

+1  A: 

You could read the explanation here.

Quote from XmlSerializer:

If a schema includes an element that is optional (minOccurs = '0'), or if the schema includes a default value, you have two options. One option is to use System.ComponentModel.DefaultValueAttribute to specify the default value, as shown in the following code. Another option is to use a special pattern to create a Boolean field recognized by the XmlSerializer, and to apply the XmlIgnoreAttribute to the field. The pattern is created in the form of propertyNameSpecified. For example, if there is a field named "MyFirstName" you would also create a field named "MyFirstNameSpecified" that instructs the XmlSerializer whether to generate the XML element named "MyFirstName".

The only acceptable for me workaround I've come so far is to use XmlSerializer instead of DataContractSerializer by using XmlSerializerFormatAttribute.

Darin Dimitrov
I tried to use DefaultValueAttribute for this one. When I use a default value what happens is even if I set the value of the date parameter in the client. Since I did not set the dateSpecified = true anymore, the date value is always the default value.// code at clientprm.DepositDate = dtp_Deposit.Value.Date;// code at service[DefaultValue(typeof(DateTime), "1900/01/01")]public DepositDate;
Nassign
A: 

also u can use [DataMember(isRequired=True)]

Neil
+3  A: 

The default parameters for the DataMember attribute are:

bool EmitDefaultValue (default true)
bool IsRequired (default false)

If the property you are exposing is a non-nullable value type you should use:

[DataMember(IsRequired = true)]
public int InvoiceNo;
Damien McGivern