Hello there visitor from grumpydev.com, if you are new here, you may want to subscribe this site.
Skip to content


Self Hosting ADO.Net Data Services (Astoria) – Part II – A Basic WCF Service Example

Introduction

In this post we will extend our previous example to include a very basic “normal” WCF service, and also add a client that consumes both services.  Hopefully this article will also serve as a very basic introduction to WCF services in general. If you happen to have a customer that’s asking for a WinForms app that can display some random remote data and add two numbers together, then everything you need is right here! 🙂

If you have created “normal” WCF service projects in the past you will probably be used to being able to click “Discover” in the “Add Service Reference” dialog. Unfortunately, because we’re not using a standard project, we have to do a little bit of work ourselves to get the references added.

Please see the original article for information on how we setup the project initially, and some Vista specific settings.

Server

Creating the WCF Service

Other than renaming the namespace (remembering to change the App.Config system.ServiceModel section to point to the new namespace) our server project remains the same as before. We will add a very simple WCF service that adds 2 numbers together and returns the result to the client.

To add a WCF service we right click on the project, choose add new, and select WCF Service from the list:

Add WCF Service Dialog

This will add an interface to our project (IAddingService.cs), and a concrete class that implements it (AddingService.cs). It will also add a lot of configuration information into our app.config which we will talk about later.

If you open the interface file you will see the class and default method decorated with attributes to signify they are WCF “Contracts”. The ServiceContract attribute signifies that a particular class or interface defines a service contract for WCF, the OperationContract attribute is applied to a method to signify it’s an operation in the service (i.e. it’s a callable method), and the DataContract attribute is used to expose custom data types via the service. For this demonstration we will use a single ServiceContract containing a single OperationContract.

We’ll remove the default method that Visual Studio has added, and replace it with a method that takes 2 integers and returns an integer. Our interface definition now looks like this:

[ServiceContract]
public interface IAddingService
{
    [OperationContract]
    int AddNumbers(int a, int b);
}

If we now change our class to implement the new interface we end up with this:

public class AddingService : IAddingService { public int AddNumbers(int a, int b) { return a + b; } }

Service Configuration

If you now open our App.Config you’ll notice a whole raft of changes that Visual Studio has added for us. The majority of what is added is beyond the scope of this article, the only part we need to worry about for this quick demonstration is the newly added service tag. We will stick to wsHttpBinding for this demo, so we can remove the mex binding line. We will also change the default baseAddress to listen on the same port as our ADO.Net Data Servics service (but on a different url).

<service behaviorConfiguration="SelfHostingDemo2.Server.AddingServiceBehavior"
  name="SelfHostingDemo2.Server.AddingService">
  <endpoint address="" binding="wsHttpBinding" contract="SelfHostingDemo2.Server.IAddingService">
    <identity>
      <dns value="localhost" />
    </identity>
  </endpoint>
  <host>
    <baseAddresses>
      <add baseAddress="http://localhost:8751/WCFService/" />
    </baseAddresses>
  </host>
</service>

That’s it for our server – now we can move onto our client app

Client

Adding Service References

Ok, now the server is finished we will add another WinForms application to serve as our client. Once the new project is added we need to add the Service References to point to our two services.

If we were using a “normal” WCF Service project, or an ADO.Net Data Services project then Visual Studio allows us to click “Discover” in the Add Service Reference Dialog and it will automatically fire up the services and enumerate them for us. As we’re not using those project types we have to do a bit of extra work ourselves. Firstly, fire up the server application either with CTRL+F5 (start without debugging) or by double clicking the exe; we don’t want to be running in debug mode or Visual Studio may not let us add references. Once the server is running we can right click on our client project, choose Add Service Reference and point it at each of our service URLs in turn (http://localhost:8751/selfhosted/ for our data service and http://localhost:8751/WCFService/ for our WCF service):

AddWCFService

Once that’s done we can close down our server app for now. It’s worth noting that if you alter the service and want to update the client reference then you need to go through the same process of firing up the server app before you choose Update Service Reference.

Note: These steps create “proxy” classes in our project for accessing our services. You can also create these classes using SvcUtil.exe (for WCF services) and DataSvcUtil.exe (for Data Services

Adding Some Functionality

To demonstrate the application we will data bind a control to some data from our data service, and provide some controls for using our shiny new adding service. Our final interface will look like this:

ClientUI

Now we need to add some code :-)  Firstly we will add two variables for our two services, and instantiate them in our form’s constructor:

private DataService.DemoEntities dataService;
private WCFService.AddingServiceClient wcfService;

public Form1()
{
    InitializeComponent();

    dataService = new DataService.DemoEntities(new Uri(@"http://localhost:8751/selfhosted/"));
    wcfService = new WCFService.AddingServiceClient();
}

Creating our Data Services service requires us to pass in a Uri to locate the service. We would normally store this in a configuration file somewhere, but for ease of reading it is just hard coded in this demo.

Next up we bind our ListBox to some data (customers in our case). In a real world app we would probably do potentially time consuming tasks like talking to web services in a background thread, then use the Dispatcher to update the UI, but for this demonstration we will just block the UI thread 🙂

private void Form1_Load(object sender, EventArgs e)
{
    DataListBox.DataSource = dataService.Customers.ToList();
    DataListBox.DisplayMember = "CompanyName";
}

That should look very familiar to anyone that had data bound a WinForms control before 🙂 We could use LINQ to filter the list and do other fancy things, but we’ll stick to the full list for this demo.

The code for our Equals Button is equally as simple. The proxy class that Visual Studio has generated for us has done all the hard work, so we can just call Add as we would any other method:

private void EqualsButton_Click(object sender, EventArgs e)
{
    int number1;
    int number2;

    if ((!int.TryParse(Number1.Text, out number1)) || (!int.TryParse(Number2.Text, out number2)))
    {
        MessageBox.Show("Please enter valid integers");
    } 
    else
    {
        AnswerLabel.Text = wcfService.AddNumbers(number1, number2).ToString();
    }
}

Again, in a real world app we would probably put the call to the web service in a background thread and update the UI with a Dispatcher.

And that’s it! If you fire up the Server app, then fire up the client, you should end up with something that looks like this:

ClientUIRunning

You can grab the source code for the whole thing below:

selfhostingdemo2.zip

Posted in ADO.Net.

Tagged with , , , , .


Surface at BETT – Finguistics

The Project

As I’ve mentioned a few times previously, in December last year I was lucky enough to be involved in a project at Microsoft in Reading involving Microsoft Surface. The remit for the project was to create an education specific application as a proof of concept for the BETT Show in London.  BETT is the world’s largest educational technology event, with tens of thousands of visitors, and it was hoped that our application would show how the Surface could be used in an educational context. The development team consisted of guys from Lightbox Education, RM, Microsoft and Infusion and the whole project was put together in a very agile manner in just 3 weeks.

The application itself attempted to promote the collaborative nature of the Surface with a spelling/word/maths game where the users had to work together to pull together the correct spelling/sentence/answer. We had a physics engine to allow the various “tiles” to interact with each other, and using Surface’s object recognition we enabled users to throw down their “id cards” to see their Avatar appear and their scores to be saved. We also created a “Teacher Console” WPF client app that would enable a teacher to view a “live” image of the current game, see scores, view and manage the upcoming game queue and add new content. Unfortunately I don’t currently have any decent videos of it, but here’s some screen shots:

0 menu 1 welcome avatars 2 gameplay spelling 3 gameplay spelling wrong 4 teacher interaction 5 spanish sentence 6 win points 7 wordplay

The Technologies

It was decided early on that the project would use lots of the latest “Microsoft stack”, with plenty of use of the new .net 3.5 SP1 features. Some of the technology I’d used before and some I hadn’t touched – I’ve briefly put some opinions down on the whole stack:

  • Surface Hardware.  The first thing so say is that it works! Although I’d seen the various videos from PDC and other places, I was still rather sceptical as to whether it would actually work in practice. To say I was pleasantly surprised would be an understatement, it works and it works well! The only negative I would bring up is that it could do with a bit more graphical horsepower; it doesn’t take too many graphical effects and animations to make it start to chug.
  • Surface SDK.  The developer SDK for the Surface is basically a thin layer of controls that sit on top of WPF.  From a technical standpoint, if you know WPF then the leap to Surface is a very small one. The hardest part to grasp is the change in mindset to take into account the natural and 360 degree nature of the Surface. The SDK itself comes with a Simulator that enables you to perform basic testing of your application and enables you to plug in several mice to simulate multi-touch. It’s a very useful tool, but it’s certainly no substitute for a Surface unit itself, and I don’t believe you can do any serious Surface development without the hardware to hand.
  • Entity Framework.  Consuming an EF model and working with it seemed pretty solid, and I had no real complaints there, but I found the design surface to be confusing and unreliable. We had a few times where the design surface corrupted the XML file, and I felt at times that I was randomly clicking on things in an attempt to get it to display what I wanted it to display.
  • ADO.Net Data Services. Very simple to implement and the functionality you get for virtually no code is very impressive. Unfortunately it’s currently lacking a lot of functionality you may take for granted if you’ve worked with EF or LINQ to SQL before, and you might be forgiven for thinking it’s entire LINQ implementation consists of just NotImplementedExceptions 🙂

All in all in was an excellent experience, and I believe the application was well received at BETT. Hopefully someone will stump up large amounts of cash for us to put together more Surface apps in the future 🙂

Edit: Marc Gravell, of unfeasibly large Stack Overflow reputation fame, has blogged about his experience on the project too.

Edit: There’s a very brief video of Jim Knight (the UK Schools Minister) playing Finguistics on Teacher.Tv

More Links: Finguistics got a mention on the MSDN Surface Blog, and there’s also a nice write up of kids playing the game at BETT, along with a photo of the game in action on Shakeout’s Blog.

Finguistics in a School! A Surface unit with Finguistics installed (amongst other apps), has recently been showcased at Churchend Primary School in Reading. More details on the Reading Borough Council website.

Another Writeup! There’s a nice write up of the Surface in education, and Finguistics, on Merlin John Online.

Posted in Rambling, Surface.

Tagged with , , .


More on Self Hosting

I’ve had a few requests to extend the example in the previous post to include the WCF functionality I mentioned at the start of the post.

I thought the WCF side was already documented to death, but I will put together an updated demo that includes ADO.Net Data Services, WCF and a demo client app in my next post.

Posted in Rambling.


Self Hosting ADO.Net Data Services (Astoria)

Overview

As part of the recent Surface application there was a requirement to host both a “normal” WCF service, and an ADO.Net Data Services service inside the main application (rather than a service running under a website).  The former is very straightforward and well documented, but I was a bit short of information on the latter and the information I did have hadn’t been updated for the various RTM changes.

Luckily it’s very easy to do, so I thought I’d throw together a quick example.

Example Data

For this example I’ve used Entity Framework and the Northwind database. It’s dependant on SQL Server Express running as the SQLEXPRESS instance on the local machine, but ADO.Net Data Services can expose all kinds of data, take a look at MSDN or your friendly neighbourhood search engine for more information :-) 

Setup

To get things going we need two particular namespaces:

Service Definition

To define our service we simply create a new class, inherited from DataService<T>, and implement a single method InitializeService to define what entities to expose, and what permissions to give.  In this example DemoEntites is the name I gave to our Entity Framwork Model and we will just expose everything with full access.  For more information on this method, take a look at the MSDN documentation.

namespace SelfHostingDemo
{
    public class SelfHostedService : DataService<DemoEntities>
    {
        public static void InitializeService(IDataServiceConfiguration config)
        {
            config.UseVerboseErrors = true;
            config.SetEntitySetAccessRule("*", EntitySetRights.All);
            config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
        }
    }
}

The second part of defining the service is in the app.config, so add one if you haven’t already got one, and we need to add a system.serviceModel section and add the definition for our service:

<system.serviceModel>
  <services>
    <service name="SelfHostingDemo.SelfHostedService">
      <endpoint address="http://localhost:8751/selfhosted/" binding="webHttpBinding" contract="System.Data.Services.IRequestHandler" />
    </service>
  </services>
</system.serviceModel>

If you are running on Vista, and aren’t running with Administrator privileges, you will need to use netsh (as an Administrator) to allow us to bind to that endpoint address.  In this example we will just give the Users group access to listen on anything on port 8751:

netsh http add urlacl url=http://+:8751/ user=Users listen=yes

Firing It Up

To fire up our service we create a new WebServiceHost.  In this example I start it up inside Main():

try
{
    System.ServiceModel.Web.WebServiceHost aHost = new System.ServiceModel.Web.WebServiceHost(typeof(SelfHostedService));
    aHost.Open();
}
catch (Exception ex)
{
    Trace.WriteLine(ex, "Failed to start CRUD host");
}

And that’s all we need to do.  If you launch the example application you will be presented with a single button that opens the address of our service in your browser.  From there you should be able to navigate round the various entities and relationships.

SelfHostingDemo.zip

Posted in ADO.Net.

Tagged with , , , .


Stack Overflow WordPress Widget

If you haven’t already, you should really check out Stack Overflow; it’s a community driven programming questions/answers site where people earn reputation and badges for contributing.

I wanted to put an XBox Live style "gamertag" on my blog with a link to my Stack Overflow profile and my current "reputation". I couldn’t find anything out there so I thought I’d dig up some Widget sample code and steal adapt it to display what I wanted.

There doesn’t seem to be any API for getting the information I wanted, so it uses a basic screen scrape, which may well stop working if they tweak the pages and may well not work for everyone’s profile page, but it works for mine and that’s all I care about 😉 Seriously though, if anyone else wants to use it and has problems, feel free to drop me a line and I’ll take a look at it. I’m no PHP expert either, so if anyone wants to tell me if my code sucks horribly, feel free 😀

You should be able to see the widget over on the right, and you can grab the widget itself below. Once it’s installed you need to configure it to give it your user number (26507 in my case) and your email address (so it can pull out your Gravatar). The email address isn’t used for anything other than hashing for the Gravatar, but you can read the source if you don’t believe me 🙂

Update: I’ve made a few changes in response to a few comments, and also removed the little place holder and badges in there.  It takes into account badges that have been awarded multiple times, so it *should* be the same as your SO page 🙂

Update2: Thanks to Ólafur Waage for providing an update to add a clear div after the widget and to run the name through htmlentities to handle names with “funky characters” 🙂

Update3: Version 2.0.0 is now available on the WordPress plugin page. It has a simple cachine system and also now pulls its data from the Stack Overflow JSON feed, rather than using screen scraping. More info in the new post: Updated: Stack Overflow WordPress Widget.

New screenshot and download below:

Stack Overflow Widget

sowidget.zip

Posted in Misc.

Tagged with , , .