Serializing your javascript objects or collections to valid json to submit with an ajax-enabled WCF service

Recently, one of the things I found myself struggling a bit with, was submitting my javascript object collection to an ajax-enabled WCF service which was expecting a object or object collection of a certain type. At first I kept getting format errors because my self created JSON object collection was not formatted correctly and thus the object collection could not be parsed correctly by our ajax WCF service.

Suppose we have a very simple data contract:

Serializing javascript object collection to valid json for ajax WCF service

We have an AJAX-enabled WCF service, that has a method that accepts an ienumerable of our data contract:

Serializing javascript object collection to JSON for AJAX enabled WCF service

We can build our object in javascript with the available properties and serialize the array with JSON.stringify:

Serializing javascript objects to JSON with JSON.Stringify

The result of JSON.stringify on the javascript object array will be a JSON parsed collection of employee:


The other solution is to write your objects in the JSON format immediately, but that is not any fun thing to do. When you are starting to build complex collection with multiple object levels, writing the json format manually is almost impossible. JSON.stringify just does the work for you!



WCF REST service with ODATA and Entity Framework with client context, custom operations and operation interceptors

It has been a while since I’ve made a post. Real life needed some attention as well and I had to invest into some study into Entity Framework, which is one of the topics I have to master for the upcoming ADO.NET certification. During preparation I found some information on how to construct WCF REST services with ODATA exposing data directly from an entity framework datasource.

For some this might not be interesting, but I sure as hell find this an interesting topic, considering how interoperable and scalable REST services are. In this post I’ll run through the setup and configuration of a  Restfull WCF Data Service with Entity Framework.

I’ve written 2 post before on WCF REST Services, which could be interesting to browse through quickly to understand the basics:
WCF REST service with XML / JSON response format according to Content-Type header
WCF REST service operation with JSON and XML also supporting ATOM syndication feed format

If you are looking for building REST services, this can also be done by the ASP.NET Web API:
Building and consuming REST services with ASP.NET Web API and OData support

Quoted directly from the Open Data Protocol website:

The Open Data Protocol (OData) is a Web protocol for querying and updating data that provides a way to unlock your data and free it from silos that exist in applications today. OData does this by applying and building upon Web technologies such as HTTP, Atom Publishing Protocol(AtomPub) and JSON to provide access to information from a variety of applications, services, and stores. The protocol emerged from experiences implementing AtomPub clients and servers in a variety of products over the past several years.  OData is being used to expose and access information from a variety of sources including, but not limited to, relational databases, file systems, content management systems and traditional Web sites.

OData is consistent with the way the Web works – it makes a deep commitment to URIs for resource identification and commits to an HTTP-based, uniform interface for interacting with those resources (just like the Web).   This commitment to core Web principles allows OData to enable a new level of data integration and interoperability across a broad range of clients, servers, services, and tools.

For this post I used the AdventureWorks database that is provided by Microsoft. You can find it here: 

After attaching the database to your local IIS SQL server, you should have something as following:

Adventureworks Entity Framework

Continue reading

WCF message security with username authentication and authorization provided by a membership provider

In this blog, I’ll show how to set up message security with username authentication and authorization provided by a membership provider. I will not discuss the basics about message security or self-signed certificates as I’ve reviewed those topics already.

If you do not know what self signed-certificates are, how they work and why you need them, first read this:
WCF transport security and client certificate authentication with self-signed certificates

If you do not know how to use and configure message security, first read this:
WCF message security and client certificate authentication with self-signed certificates

If you do not know what a membership provider is or how to use it, then I’m sorry, but you might want to read this as well:
MSDN walk-through: Creating a Web Site with Membership and User Login

Now we know how to work with message security, self-signed certificates and membership provider, let’s get a working WCF username authentication and authorization working with a membership provider.

My solution looks as following:

WCF Authentication and authorization with message security username

Continue reading

WCF dynamic endpoint discovery with UdpDiscoveryEndpoint and DiscoveryClient with FindCriteria and scope

In my attempt to learn the basics of Windows Communication Foundation, the WCF support for WS-Discovery is one of the topics I had to attempt, to get a bit familiar with the topic.

There are 2 possible ways of discovery:

  • Ad-hoc : UDP multicast discovery over the network. This only works for services that are on the same network as the client.
  • Managed: A discovery proxy that works as an mediator to the local network and acts as a service repository for the clients outside of the network
We will go for the Ad-Hoc UDP multicast discovery to find the endpoints of our service dynamically, instead of harcoding the service endpoint in our client code or configuration. This means this way of discovery only works within the same network, ideal for intranet situations. When you want clients outside of the network to dynamically discover endpoints within your network, you will also need to add a DiscoveryProxy, which is another story on it’s own.

1. Finding a service endpoint dynamically with Ad-Hoc Discovery and UdpDiscoveryEndpoint

For the dynamic service endpoint discovery we will need an udpDiscoveryEndpoint and a DynamicEndpoint 

Our solution looks as following:

WCF Ad hoc discovery with udpDiscoveryEndpoint

Continue reading

WCF REST service operation with JSON and XML also supporting ATOM syndication feed format

I recently wrote a post about WCF REST services with JSON and XML:

WCF REST service with XML / JSON response format according to Content-Type header

Now I often see ATOM format appearing with REST services, next to JSON and XML (aka POX). However when creating my REST service, I didn’t easily get ATOM integrated. So I played a bit more with it till I got this solution to support ATOM next to JSON and XML on a single WCF REST operation.

First I tried to play a bit with ATOM format as Content-Type, but that thing does not seem to return ATOM results just by Content-Type header on itself. The WebOperationContext.Current.OutgoingResponse.Format only allows the possibility between JSON and XML as well. Somehow I managed to get ATOM results back on the GetEmployees() by the System.ServiceModel.Channels.Message result instead of a List<Employee>, which of course doesn’t allow us to use the exact same method as we used for the JSON or XML format:


We get an ATOM feed format back if we invoke this:

WCF REST Service ATOM Feed

Continue reading

WCF Routing and load balancing based on message content with RoutingService and an XPath message filter

Routing is one of the features added to WCF 4.0, which brings some quite nice features:

  • Content-based load balancing
  • Automatically use of fallback services
  • Protocol bridging
  • Masking of versioning issues

In an attempt to get familiar with Routing, I took the first scenario, where we will use content-based load balancing routing.


We have an OrderService which is accepting orders and processes these orders. From time to time we experience some peak loads, which somewhat worried our managers. They do not care all that much about latency and the speed of the order processing in general, except for our high stake clients (you know how some managers are). They value the orders of our high stake clients a lot higher then the general order and they want to make sure we can guarantee that the high stake orders do not experience anything if we would have some sort of peak in order submitting.

Obviously there are multiple ways to improve our scenario, like decent throttling, load balancing, queues and so forth.  But a possible solution could aswell be provided with the WCF 4.0 routing.

Instead of having 1 OrderService like we have now, we will bring up another OrderService, so we will be having 2 OrderService’s. We will not simply load balance the requests to these 2 services round robin, but we will load balance the order request based on the content.  We will route all orders with a total order price of $500 to the 2nd service we brought up. All the orders with a lower total price will still be routed to our current OrderService.

For pure load balancing purposes, you could also bring up multiple OrderServices and put a WCF Router in front of it, which distributes the requests round robin. You clients send the messages to the router, and the router just forwards to the processing services.

Continue reading

WCF REST service with XML / JSON response format according to Content-Type header

Recently I tried to grasp the basics for the WCF REST service and the differences compared to the normal web services versus REST.
I have only tried to basics of WCF REST and not gotten deeper then the shallow level, but this is what I found so far.

If you do not know what REST stands for and why it could be of any use, you can watch this 1h18m08s video on channel9 by Aaron Skonnard: 

My solution setup looks like this:

WCF Rest service with XML and JSON

I have a WCF Service Application called “WCF.Rest.Service”, which has a WCF Service called “RestService”.
Our REST WCF service contract looks as following:

WCF REST Service with WebGet and WebInvoke

Notice we added a reference to System.ServiceModel.Web and we are also using this namespace as it is holding the necessary stuff for the REST WCF services.
Instead of using OperationContract we are using WebGet and WebInvoke for REST WCF services.

WebGet stands for retrieval operations and is a HTTP GET operation.
WebInvoke stands for POST requests and stand for the HTTP PUT, HTTP DELETE and HTTP POST operation
Continue reading

By Robbin Cremers Posted in WCF Tagged ,

WCF custom username and password validation with a custom UserNamePasswordValidator

A few days ago I wrote an article about WCF message headers

WCF message headers with OperationContext and with MessageInspector and Custom Service Behavior

We used a scenario there that users who wanted to invoke the public service, had to pass their subscriptionid by message header. If the subscriptionid was not present, the user would not be allowed to invoke any service operation. To secure that scenario, we would have to use Transport or Message security, so that we are able of encrypting the subscriptionid message header, so that people with bad intentions would not be able to read your subscriptionid and use it for their own purposes.

Another possibility, maybe not such a good one, would be to work with a custom username and password validation. Let’s assume every company that is registered with us is registered with their company name and a private subscriptionid. Instead of using message headers to be granted access to the service, we will use a custom password validator against our store to validate against a username and password, in our case the company name and the subscriptionid which is their password.

In this case we will use message security with self-signed certificate. If you are not aware of what this is and how this works, please read up on this post:

WCF message security and client certificate authentication with self-signed certificate

Just as with the other blog posts, I’ll add the solution and service setup to be complete:

WCF Custom Username validation solution

Continue reading

WCF Custom Binding by configuration and by Binding, StandardBindingElement and StandardBindingCollectionElement

In the attempt to master the basic topics and extensibility points of WCF, we are going to look to WCF Custom Bindings and their possibilities.

For certain scenario’s, our company would like to use a netHttpBinding, which is not a default binding. Thus our netHttpBinding will be a custom binding which uses BinaryEncoding and HttpTransport, in contrast to the default http bindings which use TextMessageEncoding and HttpTransport. Binary encoding is a proprietary .NET protocol, but in our cases this is not an issue as we don’t have to be interopable. We know the clients are .NET clients, somewhere around the globe and to gain performance at the encoding, we want to use a custom httpbinding that uses binary encoding.

This might not be a ideal scenario, but it is good enough to run past the basic principles.

1. Custom binding by configuration:

Our solutions look as following:

WCF Custom binding solution overview

We have 2 projects in our solution:
“WCF.Binding.Custom.client”: Client console application, used to mimic a client
“WCF.Binding.Custom.Service”: WCF Service Application, with 1 WCF service called “SaasService”

Continue reading

WCF asynchronous client proxy and asynchronous service operations

In this post, we will cover asynchronous operations with our WCF proxy and our WCF service.
All by all, this is not any rocket science, but in my attempt to master WCF basics it is one of the topics I will cover.

As usual, we start with a basic solution setup:

WCF Asynchrony solution overview

WCF.Asynchrony.Client: Console application used as client
WCF.Asynchrony.Service: WCF Service application with 1 WCF service named “Public”

Continue reading