I have a WCF DataContract called RecipientDto defined as:
[DataContract]
public class RecipientDto
{
[DataMember]
public string Name
{
get;
private set;
}
[DataMember]
public string EmailAddress
{
get;
private set;
}
public RecipientDto(string name, string emailAddress)
{
Name = name;
EmailAddress = emailAddress;
//Initialize other property here
}
}
I want to have constructor of RecipientDto being exposed to the client as it involve some basic initialization of other properties (not shown here).
Please guide how can I achieve this.
Thank you!
You cannot achieve that unless you share assembly with your DTOs between client and server. Metadata (WSDL + XSD) can describe only data transferred by DTO. They cannot describe any logic defined in DTO on service side.
What you could do is the create a second source file for the RecipientDto class, that contains a second declaration of the class with the "partial" keyword. Add your constructor to it and include that file in your client project using Visual Studio's "Add Link" functionality available on the "Add existing item" dialog. If you only need that constructor on the client then just define that second source file directly in the client project.
Related
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.
I have a domain service running smooth, some expose functions that return generic lists of defined entity, but for some reason, I had add some common information so I created a generic object to wrap the collection with the extra information that I need return.
but when after made the change and try use the service in the client, the function don't show up in the context, I already search about it and what I found was attributes for generic IQueryable
my wrap class
public class Wrap<T>
{
public String commonProperty { get; set; }
public String anotherCommonProperty { get; set; }
public List<T> items { get; set; }
}
in my service domain
public Wrap<SomeClass> GetAll()
{
Wrap<SomeClass> myObject = new Wrap<SomeClass>();
myObject.items = new List<SomeClass>();
myObject.commonProperty = "some info";
myObject.anotherCommonProperty = "some info";
return myObject;
}
Maybe adding the [KnownType(typeof(SomeClass))] attribute in the Wrap<T> class, the problem is that you need to include one KnowType attribute for every class in your domain (this is because you are making a polymorphic service).
And adding the [ServiceKnownType(typeof(SomeClass))] in the GetAll method in the service (this is for wcf services I don't know if is valid for domain services).
WCF RIA domain services does not support generic entity types. IEnumerable<T> and IQueryable<T> are special cases.
Your method was ignored because it did not match supported method type.
Before changes GetAll was recognized as Query method. You can force that by adding attribute.
[Query]
public Wrap<SomeClass> GetAll()
Now it does not dissapear silently. But generates compile time error instead:
Type 'Wrap`1' is not a valid entity type. Entity types cannot be
generic.
I have two classes as below:
[DataContract]
public class Address
{
[DataMember]
public string Line1
[DataMember]
public string Line2
[DataMember]
public string City
[DataMember]
public string State
[DataMember]
public string Zip
}
[DataContract]
public class Customer
{
public Customer()
{
CustomerAddress = new Address();
}
[DataMember]
public string FirstName
[DataMember]
public string LastName
[DataMember]
public Address CustomerAddress
}
What will happen if i generate proxy of my service that uses Customer class? If i understand the concept correctly then i think the constructor in the Customer class will not be called at the client side and it may give different behavior.
How do i get rid of that constructor in the Customer class and still have the CustomerAddress property of type Address so that it behaves as a dumb DTO object?
What is the general guideline or best practices that people use to avoid this situation?
If you use the default DataContractSerializer to serialize your objects, then, yes, your constructor is not serialized, and any logic you may have in it will not be called by your client when the object is deserialized.
Regarding your question about removing the constructor logic and having the nested Address class be populated, that will be taken care of by the DataContractSerializer. If I have code like this:
Customer c = new Customer() {
FirstName = "David",
LastName = "Hoerster",
CustomerAddress = new Address() {
Line1 = "1 Main Street",
City = "Smallville",
State = "AA",
Zip = "12345"
}
};
and then return that from a service method, that Customer object will be serialized properly along with the Address information. The proxy on the client that's generated will know about Address and will be able to deserialize the stream coming from the service method to properly construct your Customer object. Your Customer will be a dummy DTO -- no logic, just properties.
Check out Aaron Skonnard's MSDN article on WCF Serialization where he talks about the DataContractSerializer.
If you generate the client (using svcutil or "add service reference"), then the generated DataContract will look like:
[DataContract]
public class Customer
{
// empty default constructor
public Customer()
{
}
[DataMember]
public string FirstName
[DataMember]
public string LastName
[DataMember]
public Address CustomerAddress
}
Your implementation details are not carried over. All that is generated is what goes into the WSDL, which is just the [DataMember] properties in this case.
I mention this because your original question asks: "What will happen if i generate proxy".
If this is an object being sent from the server to the client, then you can just always initialize CustomerAddress before sending it to the client. Infact, if your original code is on the server, then that constructor will be run, and WCF will serialize the CustomerAddress and basically never send a null (unless you set it back to null after the constructor).
If you want to make it so that the client always sends you a CustomerAddress, then you could:
have the server check for null, like if(x.CustomerAddress == null) x.CustomerAddress = new Address();
mark the DataMember as required, then the server will return an error if the client did not pass anything: [DataMember(IsRequired=true)] public Address CustomerAddress;
Otherwise, I don't think there is any way to force the generated WCF client to initialize that field for you.
You'd better define all the data contract classes in a assembly and have both server project and client project reference to the assembly so the initialization behaviour can be shared. When generating service reference, you can instruct the code generator to use existing data contract classes.
When creating a wcf class I used to do
[DataContract]
Public class Customer
{
[DataMember]
public string Name {get;set}
}
I have been told that is better to do
[DataContract]
Public class Customer
{
[DataMember]
public string Name ;
}
basically removing the get and set as will be lighter
Is this the case?
any suggestions
When you use auto-properties (using only get; set; and no backing variable), a member variable is generated randomly (you can use Reflector or ILDASM to see it). This variable, depending on the serialization scheme could be serialized.
If you rebuild, member variable name could be re-generated which can cause error in de-serialising objects serialised using old DLL. In the same way, a DLL shipped to the customer could have the OLD generated member variable so WCF communication could throw exceptions.
Can I have a data contract of this shape??
[DataContract]
public class YearlyStatistic{
[DataMember]
public string Year{get;set;}
[DataMember]
public string StatisticName {get;set;}
[DataMember]
public List<MonthlyStatistic> MonthlyStats {get;set}
};
I am assuming here that class MonthlyStatistic will also need to be a DataContract. Can you do this in a web service?
To use the same model for web services, mark your class as Serializable use the XmlRoot and XmlElement in the System.Xml.Serialization namespace. Here is a sample using your example:
[Serializable]
[XmlRoot("YearlyStatistic")]
public class YearlyStatistic
{
[XmlElement("Year")]
public string Year { get; set; }
[XmlElement("StatisticName")]
public string StatisticName { get; set; }
[XmlElement("MonthlyStats")]
public List<MonthlyStatistic> MonthlyStats { get; set; }
}
You will have to do the same thing for your complex object properties of the parent object.
Yep, thats standard WCF serialization right there. Are you trying to say the MonthlyStats collection has a property called WeeklyStats, or that each individual MonthlyStatistic has a WeeklyStat collection? If its the former, that doesnt work in WCF natively. You will have to do some fiddling in order to get it to work. If its the latter, its perfectly fine.
Yes, you can send the data contract you mentioned above back and forth from a WCF service. Like you said, MonthlyStatistic and all its members will have to be defined as data contracts themselves or be built in types (like strings).
You can even send and receive more complex types like when you have a base class but want to send or receive an object of a derived class (you would do that using the KnownType attribute). While receiving (de-serialization), from Javascript, there's a trick using which you have to specify the type for WCF. If you are interested, feel free to ask.