Presenting at Brisbane Alt.Net December Meeting

Monday, November 30 2009         1 Comment

The final Brisbane Alt.Net meetup for the year is this Thursday, the 3rd of December. I’ll be presenting on bootstrapping NHibernate with MVC and IoC and whatever discussion follows on from there.

If you’d like to come along, it would be good to put some faces to names, you can RSVP at the eventbrite page.

NHibernate, MVC and Ninject

Monday, November 16 2009         4 Comments

A few weeks back I blogged about my lightning talk on bootstrapping NHibernate with StructureMap inside an ASP.NET MVC project.

Since then I finally made some time to play around with Ninject, which seems to be the most popular IoC container amongst my Readify peers these days. Ninject is very nice to use, and very simple to get started with and of course I thought about it in the context of my NHibernate sample and whether replacing StructureMap with Ninject would make for another good sample.

Note : The code here is based on the 1.0 release of Ninject, I’m sure some funkier stuff is coming in the 2.0 release.

StructureMap has a very powerful Fluent API for controlling the instancing and construction of requested types. It let me do some funky things for building an NHibernate SessionFactory and opening a new Session.

ForRequestedType<ISessionFactory>()
	.CacheBy(InstanceScope.Singleton)
	.TheDefault.Is.ConstructedBy(() => new NHibernateSessionFactory().GetSessionFactory());

ForRequestedType<ISession>()
	.CacheBy(InstanceScope.Hybrid)
	.TheDefault.Is.ConstructedBy(x => x.GetInstance<ISessionFactory>().OpenSession());



Ninject applies a different model to StructureMap by keeping the API simpler, but allowing you to plug in custom classes to control your activation.

To achieve the same task in Ninject, I’ve created a a Module for my NHibernate configuration.

I’ve specified that the ISessionFactory and ISession types be constructed by their own Providers.

public class NHibernateModule : StandardModule
{
	public override void Load()
	{
		Bind<ISessionFactory>().ToProvider(new SessionFactoryProvider()).Using<SingletonBehavior>();
		Bind<ISession>().ToProvider(new SessionProvider()).Using<OnePerRequestBehavior>();

	}
}

public class SessionProvider : SimpleProvider<ISession>
{
	protected override ISession CreateInstance(IContext context)
	{
		var sessionFactory = context.Kernel.Get<ISessionFactory>();
		return sessionFactory.OpenSession();
	}
}

public class SessionFactoryProvider : SimpleProvider<ISessionFactory>
{
	protected override ISessionFactory CreateInstance(IContext context)
	{
		var sessionFactory = new NHibernateSessionFactory();
		return sessionFactory.GetSessionFactory();
	}
}



And you’ll see I can specify that the SessionFactory has a SingletonBehavior as it’s expensive to set up, but threadsafe and designed to be a singleton.

In the sample I’ve also added a ServiceLocator. When using StructureMap if you don’t mind coupling your code to StructureMap (probably not the best idea) you can can configure your container in one place, then make calls to ObjectFactory anywhere you need to. The Ninject kernel doesn’t work this way, so we need to keep a reference to a configured kernel in a place that can be accessed by the code. Nate Kohari, the author on Ninject provides a good example of the Service Locator pattern with Ninject on his blog.

Other than those two changes, the Ninject sample is the same as the StructureMap one, you can download it here and see for yourself.

 

Migrating Graffiti CMS from VistaDB to SQL Server

Monday, October 26 2009         3 Comments

I’ve been running this site on Graffiti CMS for a while now. Graffiti seemed like such a good product, it’s a shame Telligent seem have to abandoned it without any communication.

Anyway, after a long hiatus I started to actually use it again, and found every second or third page view would hang or throw errors, comments didn’t get indexed properly and just weird behaviour was being exhibited. Inside the admin control panel, log viewers were showing totally empty as were viewing statistics.

After some investigation it looked as if the VistaDB I was running with may have been the culprit, and looking around it seems like a few other people hit the same limits.

The instructions at Al Pascual’s blog were good. Create a new Graffiti DB inside SQL Server, then use the supplied migration tool to copy the data over. Unfortunately, it appeared that my VistaDB database was corrupt and had some duplicate primary key data in there, causing the whole thing to crash.

Next step was looking into a way to open up the VistaDB file, I went to their site and downloaded a trial. Of course, they are up to version 4 now which won’t play nice with my v3 file. There doesn’t seem to be a way to download older version from their site either. Thankfully I found a version 3 trial at download.com.

The VistaDB tools have a Repair Database function, which seemed to just time out or hang with this database.

I decided to delete the tables most likely to be the culprits, the log table which Graffiti is meant to prune automatically but somehow had over 4 million rows, and the pageview statistics page. Deleting all rows from those tables left the statistics table with 6 rows of all NULL values in it, and the log table still reporting over 4 million rows.

Thankfully though, after these two steps I could repair the database and bring it down to a nice small size.

Once the database was repaired I could run the Graffiti migration tool and move it into a fresh SQL Server database, and push that to my webhost.

So I’m all good now, hopefully I won’t have too many problems. I’ve lost some statistics, but I’m tracking those in Google Analytics anyway.

Lessons learned, don’t keep your data in a format you can’t work with, especially when the vendor is likely to upgrade to an incompatible format and pull their tools out of circulation.

It’s still a shame that Graffiti is abandoned, hopefully the people at Telligent will get it together soon and either follow through on their announcements of future development, or listen to their community forums and open source it. It could be a nice platform and a good developer ecosystem if it looked like it had a future.

NHibernate made easy with StructureMap and Fluent NHibernate

Sunday, October 25 2009         1 Comment

A while back I presented a 10 minute lightning talk at the Sydney Alt.Net group on making NHibernate easier with Fluent NHibernate and StructureMap in the context of an ASP.NET MVC app.

I set about putting this together as I've found a large interest in NHibernate from other developers, but there seems to be a bit of a barrier to entry when it comes to the configuration, mapping and patterns around session lifetime. None of these are really hard, but taken on at once can be a mental hurdle.

StructureMap is similar, for most scenarios a simple tool to use, but the number of options for configuring it can turn people away when looking at the documentation.

The premise of my short talk was that using Fluent NHibernate to configure and map NHibernate, and StructureMap to manage the SessionFactory and Session lifetimes makes it an easy stack to work with. Using this in the context of ASP.NET MVC allows you to inject your data access code very easily into your controllers, giving you a nice, loosely coupled architecture.

I’ve been sitting on this post for a little while (so long in fact, that I'm not the first person to blog about it) because I wasn't sure of the best way to document it. In the end I decided that posting the solution, and adding lots of comments was probably the easiest, because you can step through the code inside VS.NET.

So download it here and have a look. Start at the Global.asax.cs and navigate your way through the code from there. If you’d like to run it, there’s a database creation script there, you’ll need to change the connection string inside Web.config.

Bear in mind, this is NOT thorough documentation for NHibernate or Fluent NHibernate. There are a few best practice type things I’ve left out for the sake of simplicity. For starters there’s no error handling or transaction management, and if you want to use NHibernate seriously you need to understand why you map things the way you do, and what N+1 means. What I did try to achieve was demonstrate that the “ugly” initial parts of NHibernate can be made very simple with a little bit of help from a good IoC container and Fluent NHibernate.

Any feedback would be welcome, I am interested in building this out into a bigger sample so I’m open to ideas.

The Pomodoro Technique - Staying focussed

Saturday, October 24 2009         6 Comments

I’ve been working at home by myself for a few weeks, it’s mostly going well but some days I’m really easily distracted and not as productive as I want to be. As a result, I get unhappy about my days output, which makes me more easily distracted the next day... it’s a vicious cycle. 

Anyway, recently while on another engagement, a colleague told me about the Pomodoro technique. Essentially you use a timer to do 25 minute blocks of work where you turn off all interruptions like IM / Email / Twitter, when the timer goes off you give yourself a 5 minute break. Every 4 “pomodoros” you give yourself a longer break. The idea is that 25 minutes gives you enough of that sense of urgency your mind has when under a deadline while giving you a reprieve from it. 

Done properly it’s a lot like a mini Scrum. You commit to what you want to do in your 25 minutes, at the end of that look back at the work and decide what you need to move to the next one.

Then you keep track of how long standard tasks take you, what your interruptions are and how you can work with them. 

My first day I spent most of today working with the basics, 25 minutes head down and focussed, then 5 minutes to check email, get a drink etc and I got a lot more achieved that day than I did week.

I fell off the wagon with it after a couple of disrupted days with meetings in them, but came back to it this week, and once again found it to be a massive productivity boost. 

I found it very helpful to write down a list of all the things I could think of that needed doing, and adding to that list when I thought of something I wanted to do. Once again, this seemed a lot like a Scrum product backlog, and I found that some of the things I’d usually drop what I was doing to look into never really got important enough to include into one of my blocks of work. 

There’s a web site and free ebook at the official site, and a nice timer app called Focus Booster that I’ve been using.

Hope it’s helpful to someone else, as someone who often struggles maintaining focus on some of the less interesting tasks I’m finding it to be a great technique.

Alt.NET and the culture of negativity

Sunday, May 10 2009         4 Comments

An interesting lesson I've learnt over the last year is when you find yourself violently disagreeing with someone, or worse still, going along with an angry mob who violently disagree with someone, instead of ignoring that person, or trying to find fault, pay extra close attention to what they have to say.

It's an interesting experiment. You might still come away violently disagreeing, you'll probably come away still disagreeing with most of what they have to say, but I'll bet you that if you truly try to understand where they are coming from, you'll find yourself challenging your assumptions and just possibly learning something.

Every community needs a bad guy, for most of the Alt.NET folks, that bad guy is Scott Bellware. He's an easy target if you want to stand in the crowd and throw stones. But if you pay attention to the things he has to say, a recurring theme is that people have stopped using the Alt.NET label to learn, to teach and to help, and use it more as a platform of self promotion.

I'm finding this to be depressingly more true every day at the moment.

Alt.NET on one hand has given an umbrella with which to talk about a number of topics that didn't really have a good home not so long ago. These discussions have brought us a number of open source products and some fantastic resources for learning, not to mention brought local, face to face community to a group of developers that really didn't feel at home inside the usual run of the mill Microsoft developer user groups.

On the other side, there is an ever increasing group of vocal people in blogs, lists and Twitter who seem to be using the Alt.NET as a means for gaining notoriety by being openly negative about, well, pretty much everything that falls directly outside of the Alt.NET "stack".

There are examples all over the place, such as blog post attacks on Oxite and other MVC guidance attempts by Microsoft (not saying there wasn't justification for a lot of these comments, but there is a constructive way to act and there being childish), the latest blog storm on whether ASP.NET MVC is "worth learning" or not and daily twitter pursefights and general cliched sniping at anything that isn't deemed acceptable to Alt.NET dogma.

At this point it’s not really about Alt.NET and more about “look at me and how alternative I am”.

Some classic examples can be found in the comments to Rob Conery's recent blog post on what Microsoft should "do" for open source.

By the way, there is a fascinating comment there from James Peckham.

“I work in a financial institution. We have a great deal of heterogenous systems and database platforms. From c#, VB, MSSQL to oracle, vsamm files, and DB2. We have java, websphere, asp.net webservices, wcf, and a host of many different types of technologies all working together.

I've seen consistently that our microsoft technology based teams have more secure code, easier to maintain code, and put together more complexity on higher visibility applications more quickly than other teams.

We do have more outages than anyone else but usually they're caused by one of our java or mainframe dependencies. Rarely is our MSSQL a problem or any windows server have any problems. They're easy to update, patch, maintain and have considerable uptime. Our java apps have memory leaks, have considerable IO problems and security vulnerabilities that are constantly being unearthed.”

I've seen a lot in various companies to back this up too. Some of these companies even have *gasp* Enterprise Architects making decisions about how best to get this stuff to work together too.

This is Microsoft's bread and butter, in this world, open source anything is a hard sell, mainly due to legal paranoia. Microsoft releasing their own ORM, Testing framework, build platform, IoC container etc means that companies feel safe using them, and everyone wins. They would be foolish to ignore this market to pander to the desires of some random operator, who bought Eric Evans's book, applied a smattering of the repository pattern to one project and calls him self a DDD purist while cranking out content management sites for small websites.

Back to the Alt.NET thing though, if people really want to make a change in the developer world, then we must lead the way, teach and inspire. Remember that it's easier to catch flies with honey than vinegar. If your goal is to get some weird "respect" from a small group of insiders, then I'd suggest either re-evaluate that desire, or enjoy it while it lasts, because when the next new thing comes along all the bandwagon jumpers will all be there, probably sneering at Alt.NET.

Three wireless broadband and Windows 7

Monday, March 30 2009         5 Comments

Having just moved house I find myself in a position of having no reliable internet connection. Not my favourite place to be.

Last time I moved I had a prepay Optus 3G USB kit, the experience was unbelievably frustrating. I won’t elaborate here, but a #badoptus Twitter search will tell you in real time what people think about it.

Anyway, when the dust settled here today I pulled that modem out and it wouldn’t even think about connecting. Perhaps the SIM gets deactivated if you don’t connect for six months, I’m not sure. I certainly didn’t feel like spending any more money with them to find out.

I did notice the other day that Three are now doing a prepaid 3G offering with a BYO modem package as well. Looked like a good option so I picked one of those up. I have one of the ExpressCard modems from a few years ago so it should have been easy.

Should! Turns out my driver CD was damaged. 

I managed to get the Three SIM working with the Optus modem and connection client though. It worked OK but the USB modem is so easy to bump and I’m not sure it wasn’t half the problem while on Optus, so next step was to download drivers for the Express Card.

Note to Three here… your website sucks, and your search sucks. Your MobiLink download page is here, maybe someone could tell your search “engine”.

Downloaded those, do you think they would install for me on Windows 7 ? Of couse not. That’s alright, I didn’t want the silly connection manager anyway.

Next step, go to the source. The Three modem was actually a Novatel XU870, and the drivers can be downloaded by themselves here.

If you do this, you can actually set up your wireless connection like a dial up connection, and do away with any extra connection client.

It’s worth grabbing the documentation PDF from the Novatel page as it walks you through this process and you’ll need to configure the initialization string for the modem to make it connect. Once you can figure out the APN that is!

The APN is an access point name that informs the modem where to connect, much like a Wifi SSID. If you get this wrong, you’ll be trying to talk to the wrong access point and won’t get anywhere. Or something like that.

As usual, Google and Whirlpool to the rescue for things like this. It turns out that Three use a different APN for their prepay (“3services”) and their normal network (“3netaccess”). So the final init string for this is

AT+CGDCONT=1,"IP","3services"

So with the instructions followed, and the correct APN. I now can connect to the Three network, and I have internets once again while I wait for the ADSL to get connected.

Hopefully this combination of technolgies will seed the Google and help someone else in need.

UPDATE : Sept 09

It seems that on the RC (and I’m assuming RTM) of Windows 7, this configuration step is no longer needed. Just install the drivers, create a connection and away you go!

Tip : Speed up Firefox for ASP.NET development

Monday, February 16 2009         No Comments

Here's a tip for the ASP.NET developers out there using Firefox. Ever noticed how painfully slow FireFox is when you're using the ASP.NET development webserver that comes with Visual Studio ? Sometime last year I found a fix for this after a bunch of googling, then promptly forgot about it. I recently started developing on a new machine and was finding myself annoyed at the speed of Firefox and remembered this was something I'd dealt with in the past.

Take a look here for all the gory details, or if you're in a hurry, go into about:config in firefox, and set network.dns.ipv4OnlyDomains to localhost.

Now back to your (much faster) code.
 

Programmer job interviews

Thursday, January 22 2009         6 Comments

I’ve been working with a company for a few weeks now helping with some .NET capability and planning, one of their immediate needs though has been to hire a new Cold Fusion developer. Since I’m new to the place and I’m not flat out on existing projects, I’ve been running this process.

This has been an interesting experience, and I’ve been amazed at how little interest people pay to the industry they work in, and the tools they work with.

Some examples.

  • I asked a senior developer what they knew about SQL injection. The answer was “We used parameterised queries and the database is managed by the DBAs”. So they knew SQL Injection was a problem, but never took the time, in 8 years, to learn what it was or how it worked.
  • Another developer was doing some AJAX and javascript work, but had never heard of any javascript libraries like jQuery or Prototype.
  • There seems to be a particular issue with Flex / CF developers who build CF services for a Flex client to consume, who have no idea what the underlying transport looks like. I don’t know if people doing SOAP in .NET suffer from the same thing or not.
  • None of them seemed to have any interest in people doing technical blogging, something that I knew about when interviewing people at Massive, but I thought that three or four years later people would have caught on. When Jeff Atwood wrote the now notorious post about the FizzBuzz coding test, it became a common discussion piece amongst people I discuss software with, but two years on, I can use the question in an interview and the answer to “have you heard of fizzbuzz” is always no.

Maybe I’m out of place here, but I feel that part of my job as a technology professional is to pay attention to what is happening in the world, and even if I don’t have the time on my hands to try out different things in depth, I should know about things like Rails and Django (even though I’m primarily a .NET person), jQuery (even though I’m primarily a server side person). Maybe it’s the Alt.Netter(*) in me, but I think that people should just know what’s out there. Can you imagine an advertising account director not paying attention to Pepsi campaigns because they only worked on the Coke account ? They’d be instantly fired!

Some other tips if you’re being interviewed, well I have one really.

I’ll make it simple.

Don’t bullshit!

Don’t tell me you have advanced SQL Server skills if the hardest thing you’ve done is a query with a UNION in it and you don’t know what an index is. Because I’m gonna find that out.

Don’t tell me you’re a good CSS person if you have never heard of the box model.

Don’t say on your resume you’re an ADO.NET expert if you can’t tell me how you’d open a connection to a database and execute a stored proc.

Most (good) interviewers aren’t trying to catch you out or try to make themselves feel superior. They (well, I can only speak for myself but I’d hope) are trying to find out how much you know, and where that knowledge ends. This is so they can make an accurate judgment of where you will fit in with the team. Most good companies will hire promising people that are keen even if they don’t have all the advertised requirements. If you lie, you’ll most likely be found out, and you won’t do yourself ANY favours at all.

Lastly. If you’re a junior developer looking to break into the industry, or take the next step, or you want to make a jump to a new technology. Do something with it. Get involved in an open source project, build something and put it online somewhere, show some initiative, it will count for a lot. I used to spend a bit of time giving advice on various programming forums, and was always amazed at the recent grads whining about nobody willing to give them a chance. Around the same time I saw people that just started building stuff and putting it out there, and they never had any problems when it came to looking for that first job.

I know this is ranty, but I’m actually trying to be very constructive. It really doesn’t take much effort to be aware of your surroundings, the world wide internets makes it pretty easy really, so if you’re looking for a job and want to rise above the others you can do it with a little bit of work. Then again, one of the candidates I called out for his embellishments was offered another gig a few hours later….sigh.

* ( there Richard, I’m working towards my quota!!!)

Building a REST client with WCF

Wednesday, November 12 2008         3 Comments

Microsoft recently released a WCF and REST starter kit on Codeplex. The kit provides a library of helper classes and extension methods for building a REST service, as well as several project templates which will take a lot of the work out of setting up the plumbing. They've enlisted the help of Pluralsight's Aaron Skonnard to provide some guidance which he does in a blog post, whitepaper and series of screencasts. There's some great info there, and it's well worth a look.

What I haven't seen is a lot of coverage is how to consume REST services using WCF. If you watch the screencasts, Aaron uses Fiddler to POST and PUT the resources on the service side. This is great as it shows you what is happening over the wire, but it doesn't help you if you're trying to call a service from your code.

So I've put together a very basic REST service and client as an example to build from.

The service is based on the WCF REST Collection Service template which is added to your Visual Studio templates when you install the starter kit.

resttemplates

 

To make this compile, you'll also need to compile the Microsoft.ServiceModel.Web component source which should be in Program Files\WCF REST Starter Kit\Microsoft.ServiceModel.Web. To do this, you'll also need SP1 of .NET 3.5 and Visual Studio 2008 installed.

I didn't change much from the sample template implementation, I replaced their "SampleItem" class and replaced it with my own "Stock" class and added a few sample values to the initial collection via a constructor.

The end result is a simple REST service that lists some "Stock" data (Name, Symbol, Price) and lets you GET a collection or individual item, POST a new stock ticker and values, and update (PUT) any of the existing ones.

The collection results are wrapped in a StockInfo XML node containing the item as well as an EditLink node with the URI for the resource.

servicexml

I won't dwell to much more on the server side of this as the screencasts do a great job, but I will talk through building a client to consume this service.

Building a simple WCF REST Client

The first thing you need to do is reference the System.ServiceModel and System.ServiceModel.Web assemblies. The System.ServiceModel assembly is the heart of all WCF applications, the Web assembly is new to .NET 3.5 and provides classes for what they call the "web programming model".

Next we create an interface for our client, this defines the Service Contract we will be working with. The interface looks like this :

 

    
[ServiceContract]
    public interface IStockClient
    {
        [OperationContract]
        [WebGet(
            BodyStyle = WebMessageBodyStyle.Bare, 
            ResponseFormat = WebMessageFormat.Xml,
            UriTemplate = ""
            )]
        StockList GetAllStocks();

        [OperationContract]
        [WebGet(
            BodyStyle = WebMessageBodyStyle.Bare,
            ResponseFormat = WebMessageFormat.Xml,
            UriTemplate = "{symbol}"
            )]
        Stock GetStock(string symbol);

        [OperationContract]
        [WebInvoke(
            Method = "PUT",
            BodyStyle = WebMessageBodyStyle.Bare,
            ResponseFormat = WebMessageFormat.Xml,
            UriTemplate = "{symbol}"
            )]
        Stock UpdateStock(string symbol, Stock stock);

        [OperationContract]
        [WebInvoke(
            Method = "POST",
            BodyStyle = WebMessageBodyStyle.Bare,
            ResponseFormat = WebMessageFormat.Xml,
            UriTemplate = ""
            )]
        StockInfo AddStock(Stock stock); 

    }

Most of this will look familiar if you've done any WCF, but to walk through it :

  • The methods we will be inplementing in our local client are GetAllStocks, GetStock, UpdateStock and AddStock. These method names bear no resemblance to any naming convention on the server side, they are just local methods.
  • The ServiceContract attribute tells WCF that this is what the service implementation is going to look like, and the OperationContract tells WCF this is what methods we can call over the wire.
  • The WebGet and WebInvoke attributes tell WCF how we are going to call these on the service side.

To look a little closer at the last point.

[WebGet(
    BodyStyle = WebMessageBodyStyle.Bare, 
    ResponseFormat = WebMessageFormat.Xml,
    UriTemplate = ""
    )]
  • This attribute says we are going to perform a GET request against the service.
  • The WebMessageBodyStyle.Bare means that the response is going to be just the resource data, and not wrapped in any extraneous metadata.
  • ResponseFormat looks pretty self explanatory, we are going to get our data back as XML. Another option here is JSON.
  • UrITemplate defines the location of the resource. As it's blank, we will be performing a GET against the base URI of the service (defined in the configuration, in this case it's http://127.0.0.1:16353/Service.svc/). In the GetStock and UpdateStock methods you'll see that the template is marked up with the name of one of the method parameters, i.e. {symbol}. This means that the call will be made to a URI such as http://127.0.0.1:16353/Service.svc/MSFT.

In some of the other methods, you'll see this decoration as a WebInvoke instead of WebGet. This attribute means that instead of a GET, we are going to perform an HTTP PUT or POST against the service.

That's a big part of the work done there, next we have to provide the implementation of this interface, which in this case is very simple. The WCF libraries do most of the work.

    
public class StockClient : ClientBase<istockclient>, IStockClient     
{         
	public StockList GetAllStocks()         
	{             
		return this.Channel.GetAllStocks();         
	}         
	public Stock GetStock(string symbol)         
	{             
		return this.Channel.GetStock(symbol);         
	}         
	public Stock UpdateStock(string symbol, Stock stock)         
	{             
		return this.Channel.UpdateStock(symbol, stock);         
	}         
	public StockInfo AddStock(Stock stock)         
	{             
		return this.Channel.AddStock(stock);         
	}     
}

 

You'll see this inherits from a ClientBase<T> class, and from IStockClient.

We have a few missing pieces here, I have methods returning StockInfo, Stock and StockList. These are some classes I defined to deserialize the XML into, the classes are defined to match the XML returned from the service as showing in the screenshot above.

 

    
    [CollectionDataContract(Namespace = "")]
    public class StockList : List<stockinfo>
    {
    }

    [DataContract(Namespace = "")]
    public class StockInfo
    {
        [DataMember]
        public Stock Stock { get; set; }
        [DataMember]
        public string EditLink { get; set; }
    }

    [DataContract(Namespace = "")]
    public class Stock
    {
        [DataMember]
        public string Symbol { get; set; }
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public double Price { get; set; }
    }

You can see that the classes are decorated as DataContracts, and the members are DataMembers. In this case, I've built the classes to match the XML that is being returned from my service. If I wanted to use a different naming convention in my client, I can use the Name property in the DataContract constructor to match the XML.

The final piece of the puzzle is the configuration. Configuration of WCF is the part that scares most people, this is in part because Visual Studio's generated code adds all of the possible options. The configuration for this is quite simple though.

wcf_config

  • We've defined an endpoint, which is the base address for the service.  It is sitting on an ASP.NET Development Server at http://127.0.0.1:16353/Service.svc/.
  • We're using the webHttpBinding.
  • We have defined a contract in IStockClient and provided a qualified configuration value for that.
  • Finally we've specified a behavior, called "stocks". Below the endpoint configuration we have defined this and placed the webHttp tag.

That's really all there is to it, I haven't implemented any authentication and security in either the service or the client, that might be a topic for a future article. You can download the source here and run it if you like. You'll see I've implemented this inside a simple Console app, so as to not confuse the issue with multiple assemblies, you can run it and see the various methods being called.

WCF is very flexible and powerful, and this comes with the tradeoff of having a vast array of options and configuration choices. I think this seems to scare a lot of people away from adopting WCF or even finding the time to look at it. WCF isn't going away any time soon though, and REST (or REST like) APIs are in vouge at the moment and the two are a very powerful combination so I hope this demystifies a few things for people.