Category Archives: WCF

Streaming results to web page using MSMQ/WCF/SignalR/JQuery

Where I work is a Fx (Foreign Exchange) company and we trade Fx for clients all over the world, and the other day my boss came up to me and stated that he would like to be able to visualise where trades where they were happening in real time, but he wanted it too look cool, a kind of shiny showcase type of thing (I am sure you know what I mean). He categorically stated no grids. I was pleased.

My team mate Richard and I were tasked with this, so we thought about this and looked at what sort of information we had available, and wondered if we could make some sort of generic real time event watcher that would also produce some sparkly interface for us to show off.

We did NOT have much information to work with, we pretty much ONLY had the following

  1. Tcpip address
  2. An arbitrary string that described the real time event type, for example "ClientDeal", "ExchangeFund" etc etc
  3. The name of the client

So we thought about it a bit more, and what we came up with was something along the lines of this scenario.

  1. We could extend our logging framework (we use Log4Net), where we could create a custom MessageQueue(MSMQ) appender, which would log certain events and some extra data (such as Tcpip address) to aMessageQueue. Obviously we could not share our entire application so we have provider a test message publisher that simply writes test messages to a MessageQueue. This part should be pretty easy to figure out should you want to come up with your own stuff to generate the real time events.
  2. We could have a WCF service read these MessageQueue entries in real time. This service could take in subscribers, where each subscriber could subscribe for a single event using the event name, or multiple events, by passing an array of event names on subscription
  3. We could make the WCF service use callbacks to the subscribers to push notifications back to the subscribers in real time
  4. We could also use Google Earth to show these events (if we could obtain GeoLocation data for the event) in real time

Most of this is fairly standard stuff, the actual interesting part is pushing notifications from some server side web code back to the browser in real time. I don’t know how many of you have seen that before, but it is like what Google do when you open a Google search page and search for something that is quite populaar (say some news worthy item), and Google will actual stream live results at you straight into your open search page.

It’s very cool, and is usually accomplished using long polling or various other techniques using Ajax/Comet techniques, all of which are very hard to set up and get working (at least in our opinion).

What we ended up doing was using a rather new library called SignalR, which I have say is pretty darned cool.

Here is an overview of what we came up with

overallArch

And here is a screen shot of the working demo code

vid

If you want to know more, you can read all about it using this article link :

http://www.codeproject.com/Articles/324841/EventBroker

Enjoy

Advertisements

Restful WCF / EF POCO / UnitOfWork / Repository / MEF article

Numerous people have asked me to create a LOB (line of business) app that showed how I would typically structure my layers between a front end and a database (this was mainly asked for by users of my Cinch MVVM framework)

Whilst I have limited time, I am working on a rather large open source project where I kind of do a lot of this already, and I wanted to write some of that up, so I thought I could take some time out to create a rather dumbed down article which shows some of the stuff I do in my larger OSS project.

As such I published a new article which uses the following elements:

  • Inversion of control (I am using the new MEF drop)
  • Log4Net
  • Unit Of Work pattern
  • Repository pattern
  • Restful WCF using the new WCF WebApis

I have provided a simple console app demo client, for the moment. I plan on coming back and making a better front end when I have more time.

If this is of interest to you, you should pop over and read the full article over at this link : http://www.codeproject.com/KB/miscctrl/EntArch1.aspx

New Enterprise Level Messaging Article Out

Where I work we have a number of disparate systems, which were all written at different times by different people, luckily all use the same technologies, that being .NET.

Though they are all written in differing versions of .NET, for example my team is lucky enough to be able to work in .NET3.5 SP1 / .NET 4.0, but we must also interface to older systems, and some other new’ish systems.

For the newish systems it’s a no brainer we use WCF, and as we want all messages to be reliable we use MSMQ binding for that.

But for the older systems it is a problem, do you write some custom MSMQ code, or do you look around for some sort of generic messaging solution.

I decided that I would look around and see what was freely available generic messaging solutions are out there, and I decided to write up my findings in a new article which goes into my findings in quite a lot of detail.

The particular framework that I picked up was called NServiceBus which seems to be pretty mature, and has been around for a while and works well with:

  • Winforms
  • ASP . NET
  • WPF
  • WCF

It also offers Pub/Sub, FullDuplex Client Server types of topology, and inbuilt message persistence using NHibernate, and allows the users to pick their own IOC container of choice.

It seemed to more than fill our requirements. I should mention that it did take me a while to get my head around how NServiceBus does things, all of which I present in the article.

I am really pleased with how the article turned out, and would urge you all to have a read, and if you like what you see please leave me a vote/comment I would appreciate that. These articles do take a while to write/investigate, and it is always nice to know ones hard work is appreciated, so as I say if you like the article please DO leave a vote/comment on the articles forum.

The full article can be obtained here :

http://www.codeproject.com/KB/dotnet/nserviceBusDemo.aspx

Who Wants Me To Write A Book

Recently someone left me the following message on my new article (http://www.codeproject.com/KB/smart/GeoPlaces.aspx)

Hi Sacha,
I’m sure this has been said before but you really should write a book imho.
I’d buy it …
I’m not going to vote a 5 because I’d rather vote with my cash frankly!!
Oh, alright then … Wink
<stick>
Gold Star
</stick>
Seriously, write a book, but don’t do the predictable thing of picking a single technology. I like your whole approach and passion. This article would make a killer chapter in said book for instance …
Best Regards,

Jammer : 05/04/2009

Now this is not the 1st time someone has suggested that I write a book, I was just wondering how many people would actually like me to write a book. If you would could you leave a comment here, so that I can tell who would buy the book, and how many folk think it would be a good idea.

The sort of thing that I would try and cover is what I normally cover, which would be how to work with a mixture of technologies all used together, So this may include WCF/WPF/WF/LINQ/Custom controls/ASP .NET Silverlight all working together. Typically this would be to solve some problem that I make up, where the problem show cases how to use the technology really.

Let me know thanks

PS : I am running out of time to say thanks to all of you that have encouraged me to do this. I am going to look into it. I just wanted to say a big thanks to you all.

RESTful WCF Part 2 of n

A while back (can’t remember exactly when) I started saying I was going to write a bit about RESTFul WCF, you can see my 1st post at http://sachabarber.net/?p=460. In that post I mentioned that I would probably do the following:

The schedule of posts is probably going to be something like this

  1. The new RESTful WCF attributes
  2. Serialization options (this article)
  3. Hosting
  4. CRUD operations using RESTful WCF

 

Well this is basically part2. Your options for serialization when working with RESTful WCF

In this blog entry we will be covered the following serialization options.

Message

  • DataContract
  • XML
  • Hybrid
  • JSON

This blog entry says nothing about how to deal with the resources once they are made available from the RESTful WCF service, is is assumed that the reader will know what to do with the exposed resources.

Here is a hint, have a look at XLINQ or any of the numerous XML APIs.

 

Helper Methods

Before we start I would just like to point out that the attached service looks like this

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Runtime.Serialization;
   5:  using System.ServiceModel;
   6:  using System.ServiceModel.Channels;
   7:  using System.Text;
   8:  using System.ServiceModel.Web;
   9:   
  10:  namespace DataService
  11:  {
  12:      [ServiceContract(SessionMode = 
  13:          SessionMode.NotAllowed)]
  14:      public interface ISomeService
  15:      {
  16:   
  17:          /// <summary>
  18:          /// The OperationContracts below show how to use different 
  19:          /// Serialization techniques such as 
  20:          /// <list type="Bullet">
  21:          /// <item>Message (the most customizable/flexability)</item>
  22:          /// <item>DataContract</item>
  23:          /// <item>XML</item>
  24:          /// <item>Hybrid approach</item>
  25:          /// </list>
  26:          /// </summary>
  27:   
  28:          [OperationContract]
  29:          [WebGet(UriTemplate = "/")]
  30:          Message GetRoot();
  31:   
  32:          [OperationContract]
  33:          [WebGet(UriTemplate = "/DC/{firstName}/{lastName}")]
  34:          Person GetRootPersonUsingDataContract(String firstName, 
  35:              String lastName);
  36:   
  37:          [OperationContract]
  38:          [WebGet(UriTemplate = "/DC/PeopleList")]
  39:          PersonList GetRootPersonListUsingDataContract();
  40:   
  41:          [OperationContract]
  42:          [XmlSerializerFormat()]
  43:          [WebGet(UriTemplate = "/XMLSer/{animalBreed}")]
  44:          Animal GetRootAnimalUsingXmlSerialization(String animalBreed);
  45:   
  46:          [OperationContract]
  47:          [XmlSerializerFormat()]
  48:          [WebGet(UriTemplate = "/XMLSer/AnimalList")]
  49:          AnimalList GetRootAnimalListUsingXmlSerialization();
  50:   
  51:   
  52:          [OperationContract]
  53:          [WebGet(UriTemplate = "/HYBRID/{firstName}/{lastName}")]
  54:          Message GetRootPersonUsingHybridStylee(String firstName,
  55:              String lastName);
  56:   
  57:          [OperationContract]
  58:          [WebGet(UriTemplate = "/HYBRID/PeopleList")]
  59:          Message GetRootPersonListUsingHybridStylee();
  60:   
  61:   
  62:          /// <summary>
  63:          /// The OperationContracts below show how to use different 
  64:          /// ResponseFormats such as XML/JSON
  65:          /// </summary>
  66:   
  67:          [OperationContract]
  68:          [WebGet(UriTemplate = "/DC/XML/{firstName}/{lastName}", 
  69:              ResponseFormat=WebMessageFormat.Xml)]
  70:          Person GetRootPersonUsingDataContractXML(String firstName, 
  71:              String lastName);
  72:   
  73:          [OperationContract]
  74:          [WebGet(UriTemplate = "/DC/XML/PeopleList", 
  75:              ResponseFormat = WebMessageFormat.Xml)]
  76:          PersonList GetRootPersonListUsingDataContractXML();
  77:   
  78:   
  79:   
  80:          [OperationContract]
  81:          [WebGet(UriTemplate = "/DC/JSON/PeopleList",
  82:              ResponseFormat = WebMessageFormat.Json)]
  83:          PersonList GetRootPersonListUsingDataContractJSON();
  84:   
  85:      }
  86:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

That the service implementation makes use of several helper methods that look like this

   1:  private Person GetPerson(
   2:      String firstName, String lastName)
   3:  {
   4:      return new Person { FirstName = firstName, LastName = lastName };
   5:  }
   6:   
   7:  private PersonList PersonList()
   8:  {
   9:      return new PersonList {
  10:          new Person { FirstName = "firstName1", LastName = "lastName1" },
  11:          new Person { FirstName = "firstName2", LastName = "lastName2" },
  12:          new Person { FirstName = "firstName3", LastName = "lastName3" },
  13:          new Person { FirstName = "firstName4", LastName = "lastName4" }
  14:      };
  15:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

 

Message

Message is the most flexable of all the different Serialization techniques offered my WCF, as its the closest to the actual Channel that is used to transmit the Message, and it also offers the most freedom to customise the serialization process. As a side effect it also requires the most work.

For example when we have a service method like this

 

   1:  [OperationContract]
   2:  [WebGet(UriTemplate = "/")]
   3:  Message GetRoot();

 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

And the actual service implementation looks like this.

 

   1:  //Matches [WebGet(UriTemplate = "/")]
   2:  public Message GetRoot()
   3:  {
   4:   
   5:      var stream = new MemoryStream();
   6:      XmlDictionaryWriter writer =
   7:          XmlDictionaryWriter.CreateTextWriter(stream);
   8:      writer.WriteStartDocument();
   9:      writer.WriteStartElement("Root");
  10:      writer.WriteStartElement("Hello");
  11:      writer.WriteElementString("Name", "sacha");
  12:      writer.WriteEndElement();
  13:      writer.WriteEndElement();
  14:      writer.WriteEndDocument();
  15:      writer.Flush();
  16:      stream.Position = 0;
  17:   
  18:      XmlDictionaryReader reader =
  19:          XmlDictionaryReader.CreateTextReader(
  20:          stream, XmlDictionaryReaderQuotas.Max);
  21:      return Message.CreateMessage(
  22:          MessageVersion.None, "", reader);
  23:  }

 

We would get the following

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

image

Which is cool, but this is a lot of work to get these resources, which we could get in other ways. Lets consider some of the other options.

 

DataContract

Is by far the easiest approach as we simply rely on the existing WCF DataContractSerializer, which does all the heavy work for us. The issue with this approach is that the XML we end up with may not always be what we are after, and we don’t have that much control over it. So if this is an issue, you could always go for Message type Serialization or one of the other options here.

In order to demonstrate DataContract Serialization we start with an actual DataContract class/DataContract collection, which for the attached demo code look like this

   1:  [DataContract()]
   2:  public class Person
   3:  {
   4:      [DataMember]
   5:      public String FirstName;
   6:   
   7:      [DataMember]
   8:      public String LastName;
   9:   
  10:  }
  11:   
  12:   
  13:  [CollectionDataContract(Name = "People", Namespace = "")]
  14:  public class PersonList : List<Person>
  15:  {
  16:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

So we can then have some service methods that are defined like this.

 

   1:  [OperationContract]
   2:  [WebGet(UriTemplate = "/DC/{firstName}/{lastName}")]
   3:  Person GetRootPersonUsingDataContract(String firstName, 
   4:      String lastName);
   5:   
   6:  [OperationContract]
   7:  [WebGet(UriTemplate = "/DC/PeopleList")]
   8:  PersonList GetRootPersonListUsingDataContract();

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

And the actual service implementation looks like this.

 

   1:  //Matches [WebGet(UriTemplate = "/DC/{firstName}/{lastName}")]
   2:  public Person GetRootPersonUsingDataContract(
   3:      String firstName, String lastName)
   4:  {
   5:      return GetPerson(firstName, lastName);
   6:  }
   7:   
   8:   
   9:  //Matches [WebGet(UriTemplate = "/DC/PeopleList")]
  10:  public PersonList GetRootPersonListUsingDataContract()
  11:  {
  12:      return PersonList();
  13:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

Here is an example of this running through the browser.

image

 

XML

XML Serialization has been around a while and to make use of it we need to adorn our classes with special attributes to aid the serialization process. In the example code we use the following class.

   1:  [XmlRoot(Namespace = "", ElementName = "Animal")]
   2:  public class Animal
   3:  {
   4:      [XmlAttribute(AttributeName="breed")]
   5:      public String Breed;
   6:  }
   7:   
   8:   
   9:  [XmlRoot(Namespace = "", ElementName="Animals")]
  10:  public class AnimalList : List<Animal>
  11:  {
  12:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

So we can then have some service methods that are defined like this.

   1:  [OperationContract]
   2:  [XmlSerializerFormat()]
   3:  [WebGet(UriTemplate = "/XMLSer/{animalBreed}")]
   4:  Animal GetRootAnimalUsingXmlSerialization(String animalBreed);
   5:   
   6:  [OperationContract]
   7:  [XmlSerializerFormat()]
   8:  [WebGet(UriTemplate = "/XMLSer/AnimalList")]
   9:  AnimalList GetRootAnimalListUsingXmlSerialization();

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

And the actual service implementation looks like this.

   1:  //Matches[WebGet(UriTemplate = "/XMLSer/{animalBreed}")]
   2:  public Animal GetRootAnimalUsingXmlSerialization(String animalBreed)
   3:  {
   4:      return new Animal { Breed = animalBreed};
   5:  }
   6:   
   7:   
   8:  //Matches[WebGet(UriTemplate = "/XMLSer/AnimalList")]
   9:  public AnimalList GetRootAnimalListUsingXmlSerialization()
  10:  {
  11:      return new AnimalList {
  12:          new Animal { Breed = "breed1"},
  13:          new Animal { Breed = "breed2"},
  14:          new Animal { Breed = "breed3"},
  15:          new Animal { Breed = "breed4"}
  16:      };
  17:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

Here is an example of this running through the browser.

 

image

 

Hybrid Approach

If you want to work with strongly typed object but also want to use Messages where you have more control over the serialization process you can go for a hybrid approach which works something like this. We could have some service methods that are defined like this.

   1:  [OperationContract]
   2:  [WebGet(UriTemplate = "/HYBRID/{firstName}/{lastName}")]
   3:  Message GetRootPersonUsingHybridStylee(String firstName,
   4:      String lastName);
   5:   
   6:  [OperationContract]
   7:  [WebGet(UriTemplate = "/HYBRID/PeopleList")]
   8:  Message GetRootPersonListUsingHybridStylee();

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

And the actual service implementation looks like this.

   1:  //Matches [WebGet(UriTemplate = "/HYBRID/{firstName}/{lastName}")]
   2:  public Message GetRootPersonUsingHybridStylee(String firstName,
   3:      String lastName)
   4:  {
   5:      Person p = GetPerson(firstName, lastName);
   6:      return Message.CreateMessage(MessageVersion.None, "*", p);
   7:  }
   8:   
   9:   
  10:  //Matches [WebGet(UriTemplate = "/HYBRID/PeopleList")]
  11:  public Message GetRootPersonListUsingHybridStylee()
  12:  {
  13:      PersonList pl = PersonList();
  14:      return Message.CreateMessage(MessageVersion.None, "*", pl);
  15:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Using the same helper methods as before.

This approach allows us to use strongly typed DataContract objects but use Messages, which allow us to have more control over the serialization process, as it is in the developer control rather than the actual DataContractSerializers.

 

Here is an example of this running through the browser.

 

image

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

JSON

Some of you out there may actually be used to web development and are well used to (and even into, just for the record I am not a web guy) working with Javascript/manual Ajax calls. As I say I am most certainly not a web chap, but for completeness let’s look at how we might serialize some RESTful resource results to JSON.

As before most of the heavy lifting is done by way of the some WCF attributes.

Lets firstly look at the service interface method which looks like this, it can be seen that we simply use the WebMessageFormat.Json enum to specify that we want the resources serialized as JSON

   1:  [OperationContract]
   2:  [WebGet(UriTemplate = "/DC/JSON/PeopleList",
   3:      ResponseFormat = WebMessageFormat.Json)]
   4:  PersonList GetRootPersonListUsingDataContractJSON();

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

And then  for the actual service implementation we have this

   1:  //Matches [WebGet(UriTemplate = "/DC/JSON/PeopleList", 
   2:  //          ResponseFormat = WebMessageFormat.Json)]
   3:  public PersonList GetRootPersonListUsingDataContractJSON()
   4:  {
   5:      return PersonList();
   6:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

 

Using the same helper methods as before.

And to ensure this works we could use a small sample HTML page (included with the demo code), which I have only tested and got working with IE7. It should work with FF but I didn’t spend too much time on it, as that is not the point I am trying to make, I am merely showing you how the RESTful JSON stuff works.

   1:  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
   2:  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
   3:  <html>
   4:  <head>
   5:  <title>JSON Test</title>
   6:  <script type="text/javascript">
   7:   
   8:  function getXmlHttp()
   9:  {
  10:      var xmlHttp;
  11:      try {
  12:          xmlHttp = new XMLHttpRequest();
  13:      }
  14:      catch(e) {
  15:          try {
  16:              xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
  17:          }
  18:          catch (e) {
  19:              try {
  20:                  xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  21:              }
  22:              catch (e) {
  23:                  alert("the sample only works in browsers with Ajax support");
  24:                  return false;
  25:              }
  26:          }
  27:      }
  28:   
  29:      return xmlHttp;
  30:  }
  31:   
  32:   
  33:  var serviceURI = "http://localhost:8085/SomeService/DC/JSON/PeopleList";
  34:   
  35:  function getStuff()
  36:  {
  37:   
  38:      var xmlHttp=getXmlHttp();
  39:      xmlHttp.onreadystatechange = function() {
  40:          if (xmlHttp.readyState == 4) {
  41:              alert("xmlHttp.readyState");
  42:              var result = (eval(xmlHttp.responseText));
  43:              var person = null;
  44:              alert(result);
  45:              for (var i = 0; i < result.length; i++) {
  46:                  person = result[i];
  47:                  alert("Person found, Firstaname : " + 
  48:                  person.FirstName + " LastName : " + person.LastName);
  49:              }
  50:          }
  51:   
  52:      }
  53:      xmlHttp.open("GET", serviceURI, true);
  54:      xmlHttp.setRequestHeader("Accept","application/json");
  55:      xmlHttp.send(null);
  56:      
  57:  }
  58:   
  59:  </script>
  60:   
  61:  </head>
  62:   
  63:  <body >
  64:  <form name="form1" action="javascript:getStuff()">
  65:  <input type="submit" value="Enter"> </form>
  66:  </body>
  67:  </html>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

And here is a demo of it running (again against the simple WCF service console host app, that is included with the attached demo code)

image

As I say I am NOT a web man, but again for completeness I WILL be showing you how to host RESTFul WCF services inside ASP .NET/IIS and how to work with a ASP .NET AJAX ScriptManager object in the subsequent post. Which to my mind if I was into the web, would be how you would want to go about things, as you would then get away with not having to write all this crappy javascript AJAX code. Ouch. That simply can not be cool. I know ASP .NET  AJAX is heavy but come on, that xmlHttp.onreadystatechange YUUUUUCKKKK

 

 

Here is a small demo project for this blog entry : simplerestful_serializationexamples.zip

Enjoy

RESTful WCF Part 1 of n

Lately I have been neglecting my  coding duties a bit in order to go out and get drunk actually. Which I have become a bit tired of now, so I am back onto the code, which is a good place.

Now I am in the process of creating another article, and though I can not reveal what I am working on, as there is a competition involved, which I would like to have a pop at, I thought I may share bits of information about parts of it along the way.

I can say that I am using some new WCF stuff that came with .NET 3.5, namely the System.ServiceModel.Web namespace which allows us to create RESTful WCF services.

 

For those that do not know what REST is, here is what Wikipedia has to say about it.

 

"Representational state transfer (REST) is a style of software architecture for distributed hypermedia systems such as the World Wide Web. As such, it is not strictly a method for building "web services." The terms "representational state transfer" and "REST" were introduced in 2000 in the doctoral dissertation of Roy Fielding,[1] one of the principal authors of the Hypertext Transfer Protocol (HTTP) specification.

REST strictly refers to a collection of network architecture principles which outline how resources are defined and addressed. The term is often used in a looser sense to describe any simple interface which transmits domain-specific data over HTTP without an additional messaging layer such as SOAP or session tracking via HTTP cookies. These two meanings can conflict as well as overlap. It is possible to design a software system in accordance with Fielding’s REST architectural style without using HTTP and without interacting with the World Wide Web.[2] It is also possible to design simple XML+HTTP interfaces which do not conform to REST principles, and instead follow a model of remote procedure call. The difference between the uses of the term "REST" therefore causes some confusion in technical discussions.

Systems which follow Fielding’s REST principles are often referred to as "RESTful"."

http://en.wikipedia.org/wiki/Representational_State_Transfer

 

Basically what it means as a WCF developer is that you will expose resources which are accessible via Urls, which means all a client needs to use your service is a browser.

 

The schedule of posts is probably going to be something like this

  1. The new RESTful WCF attributes (this article)
  2. Serialization options
  3. Hosting
  4. CRUD operations using RESTful WCF

 

Ok so lets get on to some code.

This blog post will simply cover the new attributes that enable RESTful WCF.

In fact there is really only 2 attributes that in my mind are the lynchpins for the whole RESTful way of doing things using WCF. These attributes are 

WebGetAttribute

"The WebGetAttribute attribute is applied to a service operation in addition to the OperationContractAttribute and associates the operation with a UriTemplate as well as the HTTP protocol Get verb. The association with HTTP Get verb means that the operation is used to retrieve information from the service. The WebGetAttribute attribute is a passive operation behavior (the IOperationBehavior methods do nothing) that adds metadata to the operation description. Applying the WebGetAttribute attribute to a service operation has no effect unless a behavior that is looking for this metadata in the operation description (such as WebHttpBehavior) is added to the service’s behavior collection."

MSDN

 

WebInvokeAttribute

"The WebInvokeAttribute attribute is applied to a service operation in addition to the OperationContractAttribute and associates the operation with a UriTemplate as well as an underlying transport verb that represents an invocation (for example, HTTP POST, PUT, or DELETE). The WebInvokeAttribute attribute is a passive operation behavior (the IOperationBehavior methods do nothing) that adds metadata to the operation description. Applying the WebInvokeAttribute attribute to a service operation has no effect unless a behavior that looks for this metadata in the operation description (such as WebHttpBehavior) is added to the service’s behavior collection. The WebInvokeAttribute determines what HTTP method that a service operation responds to. By default, all methods that have the WebInvokeAttribute applied respond to POST requests. The Method property allows you to specify a different HTTP method. If you want a service operation to respond to GET, use the WebGetAttribute instead."

MSDN

Let us now see some WCF code that uses one of these attributes. I am going to only discuss the usage of the WebGetAttribute in this post as I do not want to talk about all the CRUD operations that can be done with RESTful WCF just yet.

 

So in order to expose resources over a Url, we can use the WebGetAttribute  to adorn our WCF service operations, here is an example

   1:  [ServiceContract(SessionMode = 
   2:      SessionMode.NotAllowed)]
   3:  public interface ISomeService
   4:  {
   5:   
   6:      [OperationContract]
   7:      [WebGet(UriTemplate = "/")]
   8:      Message GetRoot();
   9:   
  10:      [OperationContract]
  11:      [WebGet(UriTemplate = "/{userName}/")]
  12:      Message GetFavouriteBarsForUser(
  13:          String userName);
  14:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Notice that I have used the WebGetAttribute to adorn the WCF OperationContract methods. Also notice that there is a UriTemplate property which is set to either a root terminator "/" or has some more parts to the Url, where the extra parts of the Url are treated as method parameters, which allow more specific resources to be exposed.

In essence that is all there is to allowing a service to expose resources. Now we need to test this. In order to do that we need to implement this example service, so lets have a look at a small demo app I knocked up.

 

   1:  [ServiceBehavior(IncludeExceptionDetailInFaults = false, 
   2:      InstanceContextMode = InstanceContextMode.Single, 
   3:      ConcurrencyMode = ConcurrencyMode.Single)]
   4:  public class SomeService : ISomeService
   5:  {
   6:   
   7:      #region ISomeService Members
   8:   
   9:      public Message GetRoot()
  10:      {
  11:   
  12:          Message message = GetRootMessage();
  13:          return message;
  14:      }
  15:   
  16:   
  17:   
  18:      public Message 
  19:          GetFavouriteBarsForUser(string userName)
  20:      {
  21:          Message message = 
  22:              GetFavouriteBarsForUserMessage(userName);
  23:          return message;
  24:      }
  25:   
  26:      #endregion
  27:   
  28:      #region Private Methods
  29:   
  30:      /// <summary>
  31:      /// Create bars for User message
  32:      /// </summary>
  33:      private Message 
  34:          GetFavouriteBarsForUserMessage(String userName)
  35:      {
  36:          var stream = new MemoryStream();
  37:          XmlDictionaryWriter writer = 
  38:              XmlDictionaryWriter.CreateTextWriter(stream);
  39:          writer.WriteStartDocument();
  40:          writer.WriteStartElement("Root");
  41:          writer.WriteStartElement("Bar");
  42:          writer.WriteElementString("user", userName);
  43:          writer.WriteEndElement();
  44:          writer.WriteEndElement();
  45:          writer.WriteEndDocument();
  46:          writer.Flush();
  47:          stream.Position = 0;
  48:   
  49:          XmlDictionaryReader reader = 
  50:              XmlDictionaryReader.CreateTextReader(stream, 
  51:              XmlDictionaryReaderQuotas.Max);
  52:          return Message.CreateMessage(
  53:              MessageVersion.None, "", reader);
  54:      }
  55:   
  56:   
  57:      /// <summary>
  58:      /// Create root message
  59:      /// </summary>
  60:      private Message GetRootMessage()
  61:      {
  62:          var stream = new MemoryStream();
  63:          XmlDictionaryWriter writer = 
  64:              XmlDictionaryWriter.CreateTextWriter(stream);
  65:          writer.WriteStartDocument();
  66:          writer.WriteStartElement("Root");
  67:          writer.WriteStartElement("Hello");
  68:          writer.WriteElementString("Name", "sacha");
  69:          writer.WriteEndElement();
  70:          writer.WriteEndElement();
  71:          writer.WriteEndDocument();
  72:          writer.Flush();
  73:          stream.Position = 0;
  74:   
  75:          XmlDictionaryReader reader = 
  76:              XmlDictionaryReader.CreateTextReader(
  77:              stream, XmlDictionaryReaderQuotas.Max);
  78:          return Message.CreateMessage(
  79:              MessageVersion.None, "", reader);
  80:      }
  81:      #endregion
  82:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

So you can see for each of the WebGetAttribute adorned WCF OperationContract methods, we will return a Message, which is really just some XML, which browsers will know how to display. If you don’t know what a Message Type is, do not worry we will be covering that in a subsequent post.

For now the important thing to note is that the service is exposing resources over REST using Urls.

The attached demo code includes a simply host, which when run will allow you to test various REST calls.

Here is what you need to do

  1. Run the simple host (SomeServiceTestConsole.exe)
  2. Open a browser and try the following Urls
    1. http://localhost:8085/SomeService
    2. http://localhost:8085/SomeService/sacha
    3. http://localhost:8085/SomeService/peter

 

And here is what you should see

http://localhost:8085/SomeService

image

 

http://localhost:8085/SomeService/sacha

 

image

 

I hope you can see that by using these new RESTful attributes we can expose resources via Urls, which is accessable simply using a Browser. Of course to parse the XML there are many options.

 

Here is a small demo app that has a very simple RESTful service and a very simple Console host.

simplerestful_getexample.zip

 

We will continue the journey next time

Dynamic LINQ To Entities Queries Using WCF/WPF demo code

I have been working on an article for Codeproject for a while now, and I have just finished it. You can read more about this article at the codeproject link :Dynamic LINQ To Entities Queries Using WCF/WPF demo code

Those of you that have used LINQ to SQL may know that you can use variables and Func<T,TResult> against a LINQ DataContex, but may not realise that you can not serialise a Func<T,TResult> and that the “var” keyword is only method level scope.

This article talks about one possible approach of how to create dynamic queries against the LINQ to Entities framework, that are able to be sent across a WCF service domain boundary. The article uses a WPC Client that creates a dynamic query based on some reflection, which is then sent to a WCF service. The actual WCF service is hosted within a Windows service, and the WCF service will call the LINQ to Entities framework that in turn is setup to look at the SQL Server Northwind sample database.

I have gone through a fair ammount of extra WCF stuff/Windows service hosting in the article, so you may find some other information too.

Anyway hope its useful to someone.

How To Create A WCF Client Proxy Without Having a Deployed WCF Service

At work we are currently using a very very Agile process, which involves 1/4 hourly builds, which was all going brilliantly with a WPF solution and some Mocks and some NUnit test projects. Then we got to the point where we had to start building our WCF service and have the WPF project obtain a new service reference client proxy based on the newly built WCF service project. This is easily achieved using NANT and wiring up dependencies in a NANT script, but we were not in a position where we could actual deploy the WCF Service with every build, due to the fact that we are hosting the WCF service inside a Windows service.

We could have also automated this using InstallUtil.exe to install the service, but this would have added more complexity to an already complex build arrangement within our CI build server AKA “Cruise Control”. We could have done it, but we simply wanted to be able to create a new service reference client proxy. Normally what one would do would be to add a service reference within Visual Studio, something like the figure shown below:

ServiceReference

When you add a service reference using Visual Studio, you typically have to have, the service both deployed and running, and you then point the wizard at the deployed and running service address, which exposes some metadata which allows the wizard to be able to see information about the service. This will then create a bunch of items in Visual Studio, such as the following :

ref

One of the these generated files is the service reference client proxy. In this case it is called “Reference.cs”, which if we examine a small section of it, contains all the DataContract / ServiceContract class definitions.

dc

Which is fine, but as I stated above, what was needed for a continuous build environment (Cruise Control) was the ability to create this service reference client proxy class “Reference.cs” without a deployed service. Mmmm, how could we do that.

Well luckily there is a command line tool which can be run as part of a NANT script. This utility is called “svcutil.exe”, and has many options, which you can find using the svcutil.exe /? switch.

But to help you out here is what we had to do in order to duplicate the functionality provided by the Visual Studio wizard using just svcutil.exe.

It was a 2 phase operation, the phases are as follows:

Create WSDL from Dlls

You can create a WSDL by using the Dlls themselves, and then you can use the WSDL to create a service reference client proxy class. Here is how we did this.

Switch Description
/d: /d:<directory> Directory to create files in (default: current directory)
/reference: /reference:<file path> : Add the specified assembly to the set of assemblies used for resolving type references.

svcutil /directory:c:SOMEDIRECTORY “<SERVICE CONTRACT DLL PATH>”
/reference:”<DATACONTRACT DLL PATH>”

NOTE : You may have all your ServiceContract and DataContract classes all in one Dll, so in this case you would not need the /reference: switch, this is only need to link in additional Dlls.

Use WSDL to create WPF client service reference proxy class

Once we had a WSDL we could the use this to create the create a service reference client proxy class. We did this as follows:

Switch Description
/d: /d:<directory> Directory to create files in (default: current directory)
/l: Language C# or VB
/out: Name of output file
/noconfig Do not generate a client layer App.Config file
/s /serializable : Generate classes marked with the Serializable Attribute
/ct /collectionType: <type> : A fully-qualified or assembly-qualified name of the type to use as a collection data type when code is generated from schemas.
/ser: /serializer: Auto – Automatically select the serializer. This tries to use the Data Contract serializer and uses the XmlSerializer if that fails.
/tcv: /targetClientVersion:Version35 : Generate code that references functionality in .NET Framework assemblies 3.5 and before.
/n: /namespace:<string,string> : A mapping from a WSDL or XML Schema targetNamespace to a CLR namespace.
/edb /enableDataBinding : Implement the System.ComponentModel.INotifyPropertyChanged interface on all Data Contract types to enable data binding.

svcutil
/d:c:SOMEDIRECTORY
c:SOMEDIRECTORY*.wsdl c:SOMEDIRECTORY*.xsd
/l:C#
/out:Reference.cs
/noconfig
/s
/ct:System.Collections.Generic.List`1
/ser:Auto
/tcv:Version35
/n:*,<THE NAMESPACE TO USE>
/edb

And that was enough for us to generate a new WPF client service reference proxy class in an automated manner, without the need to have the WCF service deployed and running.

Hope this helps someone out there

WCF Tips

As a result of messing around with WCF lately, I have just compiled a list of a few tips which I am bundled into an article which you can find over at codeproject using the following link

http://www.codeproject.com/KB/WCF/WCFTips.aspx

WCF / WPF Chat Application

I have been using WPF for a bit, written about LINQ, but decided I should explore some of the other .NET 3.0 stuff.

To this end I have create a WPF / WCF chat application using all the good WCF stuff like callbacks etc etc.

You can see the application at codeproject or just follow this link.

Anyway it looks like this, oh I got a prize for this. People liked it.

wcfwpf.png