IExtensibleDataObject vs IExtensibleObject? - c#

I am trying to figure out what is the difference between IExtensibleDataObject and IExtensibleObject.
MSDN say that the first one (IExtensibleDataObject) is to let the deserialization of object that may have added attribute and the second one (IExtensibleObject) look very similar, it does let the object add attribute too.
I am confused.

IExtensibleDataObject is about serialization, and it can be used outside of WCF's service stack. Its main purpose is round-tripping different versions of a data contract without losing information. For example, on the first version of your contract, you have this type:
[DataContract(Name = "Person")]
public class Person : IExtensibleDataObject {
ExtensionDataObject IExtensibleDataObject.ExtensionData { get; set; }
[DataMember(Order = 0)] public string Name;
[DataMember(Order = 1)] public int Age;
}
You deploy your services with this data type, and you have some clients using this type. Some service operations return a Person to the client, and the client can send those objects back to the service, as in the example below.
[ServiceContract]
public interface ITest {
[OperationContract] Person[] GetAllPeople();
[OperationContract] void DoSomething(Person person);
}
It all works great, until a change in the business logic requires that a new member to be added to Person, and a backing database requires that field to be present (not null).
[DataContract(Name = "Person")]
public class Person_V2 : IExtensibleDataObject {
ExtensionDataObject IExtensibleDataObject.ExtensionData { get; set; }
[DataMember(Order = 0)] public string Name;
[DataMember(Order = 1)] public int Age;
[DataMember(Order = 2)] public string Address;
}
Without IExtensibleDataObject, the existing clients would receive the Person object, fill its Name / Age property and promptly discard the Address element passed to it. And when it called the DoSomething method with that object, it would pass an instance which would be invalid at the server (Address would be null).
What IEDO does is enable this scenario, where existing (legacy) clients can continue receiving new versions of data contracts from the service - the client will fill the fields it understands with the data from the service, and those elements which it doesn't understand will be stored in the ExtensionDataObject so that they can be reserialized later. In the example above, the legacy clients will only be able to read the Name and Age properties of the Person, but when it sends the object back to the server, the serialized data will contain all three properties.
That was a long story about IEDO. IExtensibleObject does not have anything to do with serialization - is about hooking up extensions to some pre-defined objects in the WCF service stack (the host, the operation context, the instance context and the context channel). Not as interesting as IEDO, so I'll stop for here :)
Edited: for completeness sake, if you want more information about IExtensibleObject, you can check the post at http://blogs.msdn.com/b/carlosfigueira/archive/2012/01/31/wcf-extensibility-iextension-and-iextensibleobject.aspx.

IExtensibleDataObject is for accommodating extra data in a service message (perhaps data that wasn't specified by the contract when proxies were generated).
IExtensibleObject is used to extend certain aspects of the WCF engine (Such as ServiceHostBase and InstanceContext).
The names sound similar, but they are simply different interfaces for different purposes.

Related

Pass single complex type parameter to wcf operation issue

I am trying to send one parameter of Complex type to a WCF operation, but when I try to consume it, the signature of the operation become different and be converted to multiple parameters of simple types.
How can I keep the signature at client side as declared in server ?
For Example, My WCF looks like:
[MessageContract]
public class Foo
{
[MessageBodyMember]
public int ID {get; set;}
[MessageBodyMember]
public DateTiem Birthdate {get; set;}
[MessageBodyMember]
public string Name {get; set;}
}
[ServiceContract]
public interface IMyService
{
[OperationContract]
string Get(Foo request);
}
public class MyService
{
public string Get(Foo request)
{
// My Code
}
}
and the Clint side looks like:
MySvc.MyServiceClient c = new MySvc.MyServiceClient();
// The following code does not work
MySvc.Foo req = new MySvc.Foo();
req.Id = 5;
req.Birthdate = DateTiem.Now;
req.Name = "John";
c.Get(req);
//I should pass the parameters like the following since the signature here be different
c.Get(5, DateTime.Now, "John");
There are multiple solutions.
The best would be to compile your contract (data and service) objects into a common client assembly and use that same assembly on both the client and server side (so there's no need to create a service reference at all).
It would also be good to not use message contracts at all, only simple data contracts. Those usually look just like the server side when adding a service reference on the client side.
Finally, if you insist on message contracts (you shouldn't, IMHO), you can ask Visual Studio to generate message contracts on the client side when adding a service reference (there should be a checkbox for that).

Conditional JSON Deserialization using C#

I'm writing a C# test automation to validate web services that return JSON strings. I created a DataContract that mapped to what was being returned. Assume this is what was being returned:
{"DataModule" : {"required":"false", "location":"toolbar"}}
My test automation was working fine, but then I started getting this error:
"The data contract type 'DataModule' cannot be deserialized because
the required data members 'required, location' were not found."
I checked the JSON and the data module was now
{"DataModule" : {"width":"400", "height":"320"}}
I discovered that the dev implementation is that if the first type of data module is encountered, the client parses that and creates a button on a toolbar. If the second type of data module is returned, the button appears on the toolbar AND a panel appears in another location with those measurements.
Is there a way to either create optional members in a data contract OR implement conditional deserialization to account for JSON objects that may have multiple implementations?
If you declare the model with all of the likely properties, only the ones found in the JSON string will be populated:
public class DataModule
{
public bool Required { get; set; }
public string Location { get; set; }
public string Width { get; set; }
public string Height { get; set; }
}
#dave-s
I had already tried adding all of the properties, but since I knew I was on the right track, your suggestion keyed me into something else. The properties were all decorated with
[System.Runtime.Serialization.DataMemberAttribute(IsRequired = false)]
But the class itself, was decorated with only [Serializable]. When I changed [Serializable] to
[System.Runtime.Serialization.DataContractAttribute()]
it started working.

How to support different clients with single WCF service

I need to return Employee class as a response to my clientA as follows.
[OperationContract]
public Employee GetEmployee(String id)
{
..
..
return emp;
}
public class Employee
{
public string Name;
public string phoneNo;
}
But the problem here is clientB is going to consume my service but the need a SSN of employee. If i add it into Employee class, I will be sending to clientA as well which wont need it. How to overcome this situation. If i have to do anything with custom deserialization, would not it be a problem if i about to handle 1000s of properties?
Which is the better solution? Any wcf architectural help would also be more helpful.
If different clients have different needs, the proper thing is to create different services as well.
You put the business logic in a shared business class (or distributed over multiple shared business classes), and expose a different service per different type of client. That keeps things nice, abstracted and secure, and nobody gets data they don't need or want.
There has been a quite similar discussion on this link. Basically, it refers to conditional hiding the value of a data member.
You could decide if you want to expose a data member based on the client id or credentials (which should be passed as a parameter to the service method call).
[OperationContract]
public Employee GetEmployee(int clientId, String id)
{
var employee = new Employee();
//here you might use a mapping table between the clients and the exposed data members
if (clientId == 1)
{
employee.IsSSNSerializable = true;
}
return employee;
}
The Employee class will expose the SSN based on the value of the IsSSNSerializable property:
[DataContract]
public class Employee
{
public bool IsSSNSerializable = false;
[DataMember]
public string Name;
[DataMember]
public string phoneNo;
public string SSN;
[DataMember(Name = "SSN", EmitDefaultValue = false)]
public string SSNSerializable
{
get
{
if (!IsSSNSerializable)
return null;
return SSN;
}
set
{
SSN = value;
}
}
}
I would suggest you take a read of the versioning strategies of the WCF that might be matches with your scenarios.
for my case, i implemented IExtensibleDataObject on the data contracts and manage in this layer instead of service contracts layer.
the downside would be difficulties to track different versions of contracts, however I'm practicing the semi-strict versioning and works well for me.
I second Roy, but however if this is the only difference between client A and B. It would not hurt to expose a GetEmployee method with parameter IsSSNRequired which can have a default false value.

Understanding WCF Client to Server

I'm having difficulty fully grasping a particular function of Windows Communication Foundation. I've read tutorial after tutorial, book after book. So the entire conceptual nature I feel confident on.
Except for one part; this is the part that is almost like magic. Which actually made the learning slightly difficult.
I'll use the most common example on the web.
I'll start with the DataContract:
[DataContract]
public class Customer
{
// Declerations:
private Guid id;
private string firstName;
private string lastName;
private string emailAddress;
[DataMembers]
public Guid Id
{
get { return id; }
set { id = value; }
}
[DataMember]
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
[DataMember]
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
[DataMember]
public string EmailAddress
{
get { return emailAddress; }
set { emailAddress = value; }
}
}
Now I've created an object; that I'd like to be exposed to my Client.
So I then create my ServiceContract.
[ServiceContract]
public interface ICustomer
{
[OperationContract]
Customer AddCustomer(Customer info);
}
So this where I keep confusing myself; lets say you have a Client-Side Application. You've consumed the service. You have three textboxes in a separate Assembly / Namespace. The Client puts in the criteria:
First Name
Last Name
Email Address
If you set those text boxes to the date; they will transfer over in Metadata. But on the server; how can I pull that information variable out? Do I just reference the private Guid and private string variables?
I saw a tutorial on how to add it to a database; but I don't fully comprehend what WCF is actually doing. Which is similar to what I'd like. I'd like to get the Client interface input and write it to a database and a separate log file.
I could just follow the tutorial; but I want to know how the Customer object data and it's variables are being assembled for use on the server.
Any assistance would be amazing, some clarification.
Sorry if my question is stupid; I'm not trying to start a debate. Just want to understand how to pull those variables and use them on the server.
Thanks in advance. If I didn't format the question correctly please let me know. I'd really like to understand what it is conceptually doing.
Update:
My true intention is to understand how the Client interface references that object; so when the call is made the server has a valid object that isn't null.
Client types in text box ---> Proxy Sends ---> De-serialized ---> Service ---> Serializes ---> Makes Property available for usage.
The actual types, such as your Customer class are not really transmitted across the wire. However, the public information within those types is sent across through a process called serialization. Serialization allows a type to be represented in a way that allows it to be transmitted over a network. This is often expressed using a format such as SOAP, JSON or XML. WCF even allows you to control exactly how objects are serialized, allowing you to write your own formatter if you want. Basically, when AddCustomer is called, WCF is constructing a Customer object on the server, serializing it, and sending those bits across the wire.
Now, on the client you would have a matching Customer object called a proxy. It might look something like:
public class Customer
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
}
Basically, a scaled down version with just the data members of the server version, with no code or logic. On the client, the serialized representation of Customer is deserialized back into an instance of this local proxy class, where it can be used for various client purposes, including being bound to local UI elements.
Web services can expose this type information using WSDL (which is an XML format for describing a web service contract). Visual Studio (using the wsdl.exe tool) can automatically write these proxy classes for you, which makes everything just work magically.
I am not sure but may be this is what you are looking for
Data Transfer and Serialization
In particular you can check DataContractSerializer
You can check this article too : Serialization in Windows Communication Foundation

How can I create 'smarter' (ie typed checked/readonly properties) Client DataContract objects?

I'm quite stuck on one part of using WCF for a client/server messaging system, and would very much appreciate some help.
On the server, I've got a Message DataContract object where one of the properties points to a typed collection of MessageBody DataContracts. A stripped down version of the class looks like this:
[DataContract]
class Message {
[DataMember]
string From;
[DataMember]
string To;
[DataMember]
string Subject{get;set;}
[DataMember]
MessageBodies {get;}
}
[DataContract]
class MessageBodies : CollectionBase<MessageBody>{}
[DataContract]
class MessageBody {
[DataMember]
BodyType Type get {get;set;}
[DataMember]
string Body {get;set;}
}
From the App.Client.dll, I create a WCF Proxy of the a ServiceContract and DataContracts (btw: no referencing to a common 'App.Contracts.dll' where I could have put the above defined DataContracts), For transporting data from client to server, I'm now all set...
But from user functionality side on the client side, there's still a ways to go.
I want to ensure that users can work with the above properties, but with some type checking happening as they instantiate the client objects.
For example, I wish the actual class that users work with to look more like:
class MessageBody {
//ReadOnly only:
public BodyType Type get {get {return _Type;}}
private BodyType _Type;
//Validated property:
public string Body {
get{ return _Body;}
set{
if (value == null){throw new ArgumentNullException();}
_Body = value;
}
}
private string _Body;
//Set via Constructor only:
public MessageBody (BodyType type, string body){
//validate type and body first...
_Type = type;
_Body = body;
}
}
One direction I tried to use to solve this was as follows:
If I renamed the DataContract from Message to CommMessage, I could then wrap the POCO/WCF object with a smarter object... But although this would work for most of the properties, except for the collection properties:
public Message {
CommMessage _InnerMessage;
public string Subject {get {_InnerMessage.Subject;}}
//Option 1: give direct access to inner object...but they are just poco's...
public CommMessageBodies MessageBodies { get {_InnerMessage.Addresses;}}
//Option 2...don't have one yet...what I would like is something like
//this (returning MessageBody rather than CommMessageBody):
//public MessageBodies MessageBodies {get {_InnerMessage.Bodies;}}
}
Thanks very much for any and all suggestions!
I think it is very important to note that messages/datacontracts have a very specific purpose in a service-oriented environment. A message is a packet of information that needs to be transferred between a client and a server (or vice versa.) If your client needs specific behavior, then you should have client-specific types that provide for the specific needs of the client. Those types should be populated by some kind of adapter or facade that wraps your service references, abstracting your client application from the service as much as possible, and providing the necessary behavior, rules, and restrictions as appropriate.
using WCF.ServiceClientReference; // Contains WCF service reference and related data contracts
class ServiceFacade
{
private ServiceClient m_client;
void SendMessage(ClientMessage message)
{
Message serviceMessage = new Message
{
Subject = message.Subject,
MessageBodies = new CommMessageBodies(message.MessageBodies.Select(b => new CommMessageBody(b))
}
m_client.SendMessage(serviceMessage);
}
}
class ClientMessage
{
public ClientMessage()
{
MessageBodies = new List<ClientMessageBody>();
}
public string Subject {get; }
public IList<ClientMessageBody> MessageBodies { get; private set; }
}
// etc.
You're looking for something that's not meant to be there. The types on the client will not, in general, be the same as the types on the server, and, in general, they should not be. In the general case, the client won't even be running .NET.
Remember that these Data Contracts are meant to become the XML Schema definitions of some XML messags that will flow from the client to the service. XML Schema does not describe programming-language concepts such as Read-only.
If you feel you need the clients to have an API like that, then you do need them to use an assembly that you will have to provide. This assembly could contain the exact same data contract types that the server is using, but could potentially contain a set of types intended solely for the use of the clients. Of course, you'll have to keep the two sets of types compatible (same name, order, type and namsspace for each data member).
Lost my editing points/anon profile...but just wanted to say thanks to both of you for the clear answers. Got me moving on to the following solution:
ClientMessage on Server, creating a proxy of that on Client, with no direct dependency.
create Message on client that has properties that mirror names of poco/wcf ClientMessage, but with added arg checking, etc.
created Extension method to VisualStudio generated ClientMessage, with static Extension method MapFrom(this ClientMessage thisClientMessage, Message message){...} to map from Client facing message, to transport message object.
off it goes.
ClientMessage on server could have logic so that webpages would use that as the backing object. Costs a bit more to map those back and forth, even though on same server, but I gain from being able to cut/paste/use the same client logic for both scenarios (web and distance client). (Unless anybody sees an error with this logic as well :-) ...)
Again, thank you.

Categories

Resources