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
Related
I have the following relevant C# code:
json = File.ReadAllText(path);
isStudentObject= JsonConvert.DeserializeObject<List<XXStudentCode>>(json).Any(sv => sv.SCODE.Equals(code));
My security software (static code analysis) scans our apps and it does not like the above code, namely ReadAllText part. It says that this is a "high risk deserialization of untrusted data."
So my question is this: how can I refactor this code to make the data "trusted?" I tried different validation methods and it did not work. Any help is appreciated.
Basically search for a way of turn off the warning (through annotation or configuration file). But, before you do this, consider the implications: you should make sure that the data that you read is treated as unsecure. In other words: if, in your "XXStudentCode" object, exists some kind of flag or attribute/property that unlock things like give permission to execute some critical code or access to private things you should make sure that you do not trust the object after serialization.
Ex:
class Person
{
public bool IsAdmin { get; set; }
public string Name { get; set ; }
}
In the example above if the input comes with the attribute 'IsAdmin' with value true and your system treat all "Person's" with this attribute as a admin so you will have a security flaw. To overcome this you should create classes that only contains attributes and properties that you really need to read.
Fixed Ex:
class PersonModel
{
public string Name { get; set ; }
public Person ToPerson()
{
new Person { Name = Name };
}
}
class Person
{
public bool IsAdmin { get; set; }
public string Name { get; set ; }
}
Now, using the PersonModel in the deserialization, the only properties that you really want will be loaded, the rest you be ignored by the serialization library. But, this will not make you free to security flaws. If the deserialization library have some kind of security issue you will be affected too.
Hope this help.
I was wondering if there was a more elegant way in managing contact details for an individual. Forget the SQL side of things for a moment, I am intrigued in how one would perhaps attempt to drive this via a DDD approach.
I was fooling around with some code in an effort to get comfortable with DDD as a whole and came up with the following which seems awful.
Firstly, I have an object called Person (simplified for the purpose of this post) where I envision methods to add and essentially manage different methods of communicating an individual.
public class Person
{
public Person()
{
this.ContactDetails = new List<ContactDetails>();
}
public void AssociateContactDetails(ContactDetails contactDetails)
{
var existingContactDetails = this.ContactDetails.FirstOrDefault(x => x.ContactType == contactDetails.ContactType);
if (existingContactDetails != null)
{
this.ContactDetails.Remove(existingContactDetails);
}
this.ContactDetails.Add(contactDetails);
}
public IList<ContactDetails> ContactDetails { get; private set; }
}
Two approaches spring to mind. One where I have a fairly simple object like the one below which is quite generic (using the term loosely).
public enum ContactType
{
Email, Telephone, Mobile, Post
}
public class ContactDetails
{
private readonly ContactType contactType;
private readonly string value;
public ContactDetails(ContactType contactType, string value)
{
this.contactType = contactType;
this.value = value;
}
public ContactType ContactType
{
get { return this.contactType; }
}
public string Value
{
get { return this.value; }
}
}
But then I put myself into a corner with this approach as although it works well for trivial items such as email and telephone, when it comes to something like postal a string doesn't quite cut it. Therefore, after this I am heading towards the approach of having each mechanism of communication to represented by its own type, i.e.:
public class Post
{
public Address PostalAddress { get; set; }
}
public class Mobile
{
public string MobileNo { get; set; }
}
public class Telephone
{
public string AreaCode { get; set; }
public string TelephoneNo { get; set; }
}
public class Email
{
public string EmailAddress { get; set; }
}
Each type can then represented as a collection or single instance in the Person class? Seems long winded however is perhaps more readable and maintainable.
The question I guess is if there is a more elegant way in implementing such a feature and whether someone can point me in the direction of a good example similar to this. I imagine this is a common thing / problem to overcome.
Cheers, DS.
We know for sure what are the contact methods "email, "phone" and "address", so having identified those what we have to do first is to model those concepts taking into account what they really are. Let's take "email" as example and see what it really is in order to model it properly. It is a value object (an immutable object) that once created it will never change just as an integer number is an immutable object as well. The difference is that for modelling an integer number we can use the int type provided by any programming language, but the question is what class do we use for modelling en Email? Most of people would use a String instance to model an Email, but is this OK? In order to answer it let's see what is the protocol (the set of messages) a String object knows to response: "charAt(anIndex), replace(aString, anotherString), etc... ". Imagine that if we model an email by using a String class we could ask the email "replace(aString, anotherString)". That sounds weird, that message should not be part of the behavior an email should expose to other objects. Also so so important we said an email is immutable to it cannot expose behavior that at the end change it state. So it makes visible that we need to create a whole new abstraction to model an email and what is it? The Email class finally comes in!!! I know you suggested it but I just wanted to let you see why we need an Email class created.
First of all this is DDD (object oriented) so FORGET avoid setters and getters. In the email class you created you expose a setter method meaning that you can change the email and it contradicts with the nature of what an email is (immutable). An email is immutable from the momento it is created:
Email.fromString("monicalewinsky#gmail.com");
that is the same as doing
new Email("monicalewinsky#gmail.com");
The fromString method is a factory method that adds semantic to our domain model. This is very common in smalltalk instead of calling the constructor directly. Are we done??? Not at all. An email instance should be created as long as it is valid so the email class should assert the string from which is created is valid:
Email(String anEmailStringRepresentation) {
assertIsValid(anEmailStringRepresentation);
}
assert is valid should verify it is actually an email string representation. This is that is has only one # character, its local part is valid and then its domain part is valid. You can check the wikipedia for email address to understand better how it is composed.
Remember always that programming is a learning process, as long as we understand a domain better and better we reflect that domain in the code and it always must be consistent with the real world! Our Email class should look like more or less like:
class Email {
String value;
Email(aString) {
value = aString;
}
public String getLocalPart()
public String getDomainPart()
public String asString()
public boolean equals(anObject)
public static Email fromString(aString)
}
That's it. It happens the same with PhoneNumber. It is also an inmmutable object and you should create a class with its own protocol. Remember never use set/get as you showed up if we are doing DDD. I don't think you need two value objects Telephone and Mobile since those are polymorphic objects and you could model a mobile phone number or a home phone number with the TelephoneNumber abstraction. It's like modelling a credit card. At the end you will end up and understand that the class CreditCard is enough and a better design than having several class such as Visa, MasterCard, and so on.
Let's skip the Address class and let's go back to your problem now.
So far we have identified and created properly all the value objects we need. Now we need to create an abstraction for representing an email, phonenumber, address as contact methods and if we keep loyal to the domain language we could say:
ContactMethod.for(Email.fromString("monica#gmail.com"));
or
ContactMethod.for(PhoneNumber("34234234234"));
etc
so our ContactMethod would look like:
class ContactMethod {
static EMAIL = 1;
static PHONE_TYPE = 2;
static ADDRESS_TYPE = 3;
String type;
String value;
ContactMethod(int aType, String aValue) {
type = aType;
value = aValue;
}
String getType()
String getValue()
public static ContactMethod at(Email anEmail) {
return new ContactMethod(EMAIL, anEmail.asString());
}
public static ContactMethod at(PhoneNumber aPhoneNumber) {
return new ContactMethod(PHONE_TYPE, aPhoneNumber.asString());
}
public static ContactMethod at(Address anAddress) {
return new ContactMethod(ADDRESS_TYPE, anAddress.asString());
}
}
See that ContactMethod is also an immutable class, actually a rule of thumb is that an Aggregate root should have ideally only an aggregation of value objects.
This is finally how your Person class would look like:
class Person {
List<ContactMethod> contactMethods;
contactedAt(Email anEmail) {
contactMethods.add(ContactMethod.at(anEmail));
}
contactedAt(PhoneNumber aPhoneNumber) {
contactMethods.add(ContactMethod.at(aPhoneNumber));
}
contactedAt(Address anAddress) {
contactMethods.add(ContactMethod.at(anAddress));
}
}
On my journey of learning DDD sometimes I see patterns instead of problems... an interesting example Everything seems to be an Aggregate Root is another answer I had provided regarding a menu, which had different categories such as starter, main, desert etc.
I had modeled this implicitly as a category string. After i posted there was a second answer where someone suggested modeling these as explicit lists of:
Menu {
List<Food> starters;
List<Food> entrees;
List<Food> desserts;
List<Food> drinks;
}
In this way, the entire concept of the category for a food was removed, this was enlightening for me and saw a different way of modeling and in this case reducing complexity.
My view is to try and model the code so that if I sat down with the business expert (who is not a developer) and showed them the use case code from a high level person.SetMobileNumber("078321411", Countries.UK) they would be able to understand it:
public void HandleUpdateMobileCommand(UpdateMobileNumber command)
{
// repositories, services etc are provided in this handler class constructor
var user = this.UserRepository.GetById(command.UserId);
user.SetMobile(command.number, command.country);
this.UserRepository.Save(user);
// send an SMS, this would get the number from user.Mobile
this.SmsService.SendThankYouMessage(user);
}
Or even better, you could have a MobileUpdated event get fired when you update the user mobile, to which some code somewhere else (which is an expert on sending SMS messages, and nothing else) is listening to these events - for me this is the real power of DDD of breaking down code in to expert systems.
So in summary, I think your second suggestion of explicitly modeling with Post, Mobile, Landline and Email makes most sense.
I wouldn't say this a DDD domain or not as there isn't enough information on any complex logic (or multi-user race conditions) that you require, just to mention don't forget that you may be better writing a CRUD app if that makes more sense in this situation.
There's this central idea in DDD that domain modelling must take shape through discussion with domain experts. If you're making up these class names out of thin air, chances are they won't exactly match your real domain. Trivial ones such as Email or Telephone should be correct, but maybe for others you want feedback from an expert first.
Generally speaking, it's a good idea indeed to favor semantically rich modelling with dedicated value objects over primitive types. In C# it comes at a cost though since the amount of boilerplate code needed is huge (unlike F# for instance). This is why I usually prefer to do it only when the type has more than a single property or when there are specific construction rules or invariants to it.
One good thing you can do is model your types as immutable Value Objects. So something like:
public class Telephone
{
public string AreaCode { get; set; }
public string TelephoneNo { get; set; }
}
Might become:
public class TelephoneNumber
{
private string areaCode;
private string subscriberNumber;
private TelephoneNumber()
{
}
public TelephoneNumber(string areaCode, string subscriberNumber)
{
this.AreaCode = areaCode;
this.SubscriberNumber = subscriberNumber;
}
public string AreaCode
{
get
{
return this.areaCode;
}
private set
{
if (value == null)
{
throw new ArgumentNullException("AreaCode");
}
if ((value.Length <= 0) || (value.Length > 5))
{
throw new ArgumentOutOfRangeException("AreaCode");
}
this.areaCode = value;
}
}
// Etc.
}
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.
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.
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.