WCF IsRequired Attribute dilemma - wcf

For a customer we are developing some WCF webservices. Our message contracts are defined by using DataContract and DataMember attributes on top of our classes and their properties.
The DataMember attribute has some extra properties that allows us to add some extra rules. For example if a property should always be available, we use (IsRequired=true); to indicate this. These rules are checked when a message is received or send.
[DataContract]
public class TestClass
{
[DataMember(IsRequired = true)]
public int RequiredValue { get; set; }
}
However during our test we noticed that it doesn’t work, because at client side the RequiredValueField is initialized by null, so with some reading i found this property, EmitDefaultValue=false, so by using both, i get the desired result
[DataContract]
public class TestClass
{
[DataMember(IsRequired = true, EmitDefaultValue=false)]
public int RequiredValue { get; set; }
}
but suppose, if some client initialize RequiredValue = 0 and then call service method, it gives error again. So how do free my APIusers with an option that they can pass any thing in this member including zero, but when they omit then only it should give error ?

You have not mentioned what your "desired" result is. I mean what you are trying to achieve.
Do you know that MS does not recommend setting EmitDefaultValue to false unless it's absolutely necessary? Please read last section of this MSDN page to know the reason.
When you set EmitDefaultValue to false, the WSDL generated for your service has some annotations which are understood by WCF only. i.e. by doing so, you may restrict interoprability of your service. Is that your requirement?
Solution to your problem:
Make your DataMember "RequiredValue" a nullable int.
[DataMember(IsRequired = true,EmitDefaultValue=false)]
public int? RequiredValue { get; set; }
By doing so, the default value of the RequiredValue data member will be null and you will be able to set zero (0) without any problem.

Related

Passing an inherited "Data Contract" through WCF call?

One of my WCF endpoints has this method:
GetData(DataTable dt)
I tried to create a class on the client that inherits from the DataTable class
public class ExtendedDataTable : DataTable{
//...implementation
}
and pass it along with the endpoint call:
GetData(new ExtendedDataTable());
Then I got the SerializationException. Accordingly to the error, it suggests that I use either DataContractResolver or the KnownType attribute.
I don't want to use the KnownType, because I shouldn't have to update the endpoint every time someone decides to inherit my DataContract. I can't write any DataContractResolver, because I didn't extend the exact structure of the DataTable class. Is it possible to to extend a DataContract from the client?
If so, what's the best practice?
Thanks!
I don't recommend using the Datatable, which makes it easy for WCF to have problems with client and server serialization, such as the need to specify a table name. It is best to use a custom data type, we can use the inheritance type with the KnownType attribute.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/data-contract-known-types
On my side, I can't use the inherited Datatable, while I could use an arbitrary custom class by using Knowntype attribute.
Please refer to my code segments.
[DataContract]
[KnownType(typeof(Product))]
public class MyData
{
[DataMember]
public ProductBase Product { get; set; }
}
[DataContract]
public class ProductBase
{
[DataMember]
public int ID { get; set; }
}
[DataContract]
public class Product : ProductBase
{
[DataMember]
public string Name { get; set; }
}
You can try to inherit DataTable and explicitly use DataContract attribute to declare it's name as "DataTable".
But I'm not sure about purpose of this replacement. Server side will see only what is related to original data contract. Even when new properties gets serialized, deserializatin will only work for server side properties. Unless some custom deserialization will be provided.
In all scenarios, using DataTable is not good idea at all as Abraham Qian already pointed out.

how to serialize Microsoft.AspNet.Identity.UserLoginInfo class?

I am using Microsoft.AspNet.Identity.UserLoginInfo class in my WCF service.
However, I am getting following error -
Type 'Microsoft.AspNet.Identity.UserLoginInfo' cannot be serialized.
Consider marking it with the DataContractAttribute attribute, and
marking all of its members you want serialized with the
DataMemberAttribute attribute. If the type is a collection, consider
marking it with the CollectionDataContractAttribute. See the
Microsoft .NET Framework documentation for other supported types
As the class is in-build provided in Microsoft.Aspnet.Identity library, and also marked as Sealed, I am not getting much help on extending that to make it accessible within my WCF service.
Any help on this will be much appreciated.
Thanks
As it says... you can't. The "Consider marking it with the DataContractAttribute attribute..." is misleading since you CAN'T do this unless you have the source code. I'm assuming that your just want to send some serialized object with a couple properties back to your client. I'd try to just map the current identity to a serializable object and send it back.
[DataContract]
public class MyUserLoginInfo
{
[DataMember]
public string LoginProvider { get; set; }
[DataMember]
public string ProviderKey { get; set; }
}
The later on...
//Return me to client
var loginInfo = new MyUserLoginInfo { LoginProvider = myIdentity.LoginProvider, ProviderKey = myIdentity.ProviderKey };

WCF DataContract Attribute

I have a question about the [DataContract] attribute.
I have written my code like below: here I am not using [DataContract] attribute for my test class.
class test
{
[Datamember]
public string Strproperty
{
get;
set;
}
[Datamemer]
public string Strproperty2
{
get;
set;
}
}
class checktotal:Iservice
{
public string testmethod(test obj)
{
return obj.Strproperty+Strproperty2;
}
}
For that I am sending data from client I am getting the values correctly.
Here is it necessary to use [DataContract] attribute for that test class?
If I removed [Datamember] for test class property is getting error while sending from client. But I am not getting any errors even if I am not using the [DataContract] attribute.
Please give me a brief explanation with example so that I can understand when to give that attribute and when do not give that attribute.
Thanks,
Satya Pratap.
The DataContractSerializer can deal with classes that do not have the DataContract attribute if they provide a default constructor. See the MSDN documentation for more details.
As of .NET 3.5 Service Pack 1, you can omit (not use) the [DataContract] and [DataMember] attributes. If you do that, then the DataContractSerializer in WCF will behave just like the XML serializer - it will serialize all public properties only.
I prefer to use [DataContract] and [DataMember] explicitly anyway - it gives me the opportunity to specify options (like the data contract's XML namespace, the order of the [DataMember]) and it lets me e.g. also exclude certain properties from serialization.
As soon as you start using [DataMember] on one property, then only those properties decorated with a [DataMember] will be looked at for the WCF serialization.

Can't serialize nested nHibernate entity for WCF web service

I'm trying to use nHibernate, Spring and WCF together. I've got an Order object, and that contains a Customer object.
I can call a WCF method findOrder on my service, and providing the Order's Customer field does not have a DataMember annotation, the Web Service returns the Order I wanted. It does not contain the Customer details though, as expected.
But when I try to include the Customer as well, the WebService fails, and looking in the WCF trace logs, I can see this error:
System.Runtime.Serialization.SerializationException:
Type 'DecoratorAopProxy_95d4cb390f7a48b28eb6d7404306a23d' with data contract name
'DecoratorAopProxy_95d4cb390f7a48b28eb6d7404306a23d:http://schemas.datacontract.org/2004/07/'
is not expected. Consider using a DataContractResolver or add any types not known statically to
the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the
list of known types passed to DataContractSerializer
Pretty sure this is because the Customer contains extra nHibernate details, but I don't understand why WCF would be happy to send the Order, but not the Customer.
Can anyone help me understand?
Order object
[DataContract]
[KnownType(typeof(Customer))]
public class Order
{
// Standard properties
[DataMember]
public virtual int Id { get; set; }
public virtual Enums.OrderStatus Status { get; set; }
[DataMember]
[StringLength(20, ErrorMessage = "Order name must not be more than 20 characters long")]
public virtual string Name { get; set; }
[DataMember]
public virtual Customer Customer { get; set; }
[DataContract]
...
}
Customer object
public class Customer
{
public virtual int CustomerId { get; set; }
[DataMember]
private string name = "";
...
}
You should use a data transfer objects (DTO) to get your data over the wire. This is good practice anyway as you do not want to let your domain model leak into (and out of) the boundaries of your application.
Think about things like every change in your domain model results in a change of your data contract, resulting in a new wsdl, resulting in a change on the client. In addition you are telling the consumer of your service too many insights of your aplication.
Despite all this architectural bla bla. NHibernate uses proxies to enable lazy loading, those proxies are of another type than you serializer expects. You can disable lazy loading for your domain to get the application working. This is imho a bad idea.
<class name="Customer" table="tzCustomer" lazy="false" >

WCF method that updates object passed in

Am I correct in thinking that if I have a WCF OperationContract takes in an object and needs to set a property on that object so the client gets the update, I need to declare it to return the object.
e.g. given a datacontract:
[DataContract]
public class CompositeType
{
[DataMember]
public int Key { get; set; }
[DataMember]
public string Something { get; set; }
}
this will not work with WCF:
public void GetDataUsingDataContract(CompositeType composite)
{
composite.Key = 42;
}
this will work:
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
composite.Key = 42;
return new CompositeType
{
Key = composite.Key,
Something = composite.Something
};
}
IMO, authoring methods that produce output via side-effects is a "bad" thing. Having said that however, are there circumstances that necessitate this model? Yes.
Certainly C# programming model permits this, is WCF broken? No. At a certain point, one must realise they are consuming WCF, and as a framework it attempts to satisfy a majority of use-cases [for instance, replicating all input parameters on all round trips to preserve implicit side effect semantics is, in a word, silly].
Of course, there are ways to work around this - C# also provides for explicit declaration of these scenarios and WCF supports these as well!
For instance
// use of "ref" indicates argument should be returned to
// caller, black-eye and all!
public void GetDataUsingDataContract (ref CompositeType composite)
{
composite.Key = 42;
}
Give it a go!
Hope this helps :)
If you use 'out of the box' WCF, you are actually using a form of webservices, that uses serialized versions of the objects that are sent from client to server.
This is the reason you cannot 'by reference' change properties on objects. You will always have to use a request / response pattern.