OdeToCode IC Logo

Configuration Free JSON with WCF and AJAX in Visual Studio 2008 Beta 2

Tuesday, July 31, 2007

With all the out-of-band technology releases we've had (ASP.NET AJAX, .NET 3.0), it's nice to reach a point where we can bring them all together.

As an example...

Create a new web site in Visual Studio 2008. This will have to be a website under IIS, unfortunately, for reasons I'll point out later. Once the web site is up, add a new item – a WCF service. The service contract can look like the following:

public interface IServerProcessInfo
IEnumerable<ProcessInfo> GetRunningProcesses();

The data contract can look like so:

public class ProcessInfo
public string Name { get; set; }

public long WorkingSet { get; set; }

Finally, the LINQish implementation:

public class ServerProcessInfo : IServerProcessInfo
public IEnumerable<ProcessInfo> GetRunningProcesses()
from p in Process.GetProcesses()
orderby p.WorkingSet64 descending
                 select new ProcessInfo
                     Name = p.ProcessName,
                     WorkingSet = p.WorkingSet64

We can entirely remove any WCF <system.serviceModel> configuration from web.config. Instead of all the XML configuration goo, we just need a Factory attribute in our .svc file:

<%@ ServiceHost Language="C#" Debug="true" Service="ServerProcessInfo"
="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>

What magic does this factory give us? Well, we can add a ServiceReference via a ScriptManager (it's nice that AJAX extensions are in the toolbox by default), and write some script:

<asp:ScriptManager ID="ScriptManager1" runat="server">
    <asp:ServiceReference Path="~/ServerProcessInfo.svc" />
<script type="text/javascript">

ws = new odetocode.com.ws.ServerProcessInfo();

function getRunningProcessesComplete(result)
for(var i = 0; i < result.length; i++)
" ", result[i].WorkingSet);
"<br />");


Voila! Zero configuration and we have JSON on the wire!

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.0
X-Powered-By: ASP.NET
Date: Tue, 31 Jul 2007 03:08:10 GMT
Content-Length: 662


Note: there is a problem in Beta 2 that prevents this magic from working with WebDev.exe. The error you'll see with WebDev (aka Cassini) is:

"IIS specified authentication schemes 'Ntlm, Anonymous', but the binding only supports specification of exactly one authentication scheme. Valid authentication schemes are Digest, Negotiate, NTLM, Basic, or Anonymous. Change the IIS settings so that only a single authentication scheme is used."

Unfortunately, twiddling with the NTLM checkbox for WebDev doesn't help. Thus, the current need for IIS.