Tuesday, 22 March 2011


Interesting times ahead for software development in the quest to harness the power of available CPU and GPU processing power.

With .NET 4.0 Microsoft introduced parallel programming with their new TPL offering (Task Parallel Library) to help developers make the most of all the CPUs now available to developers. You can think of this as the next generation of Threading development for .NET.

Now Hybrid DSP, a software consultancy from the Netherlands has introduced .NET's first entry into the GPGPU (General Purpose Programming on the GPU) space with CUDAfy. Using attributes on your C# methods, CUDAfy uses the add-in module by creating CUDAfy modules which are loaded via Xml by your .NET assemblies at runtime. These modules allow you to copy data to and from the GPU and launch your .NET methods on the GPU.

Overview of CUDAfy: http://tinyurl.com/cudadotnet

CUDAfy homepage: http://www.cudafy.com

It'll be interesting to see how long it'll be before Microsoft unveil their GPU offering for .NET.

As ever, times are certainly changing for .NET developers!

Monday, 21 March 2011

How to Enable Tracing for WCF Service Messages and Parameters

If you want to view the messages and parameters being sent to and from your Wcf Services you can follow these simple steps.

To demonstrate we will be creating a new “WCF Service Library” project:


Right click on your App.Config file and select “Edit Wcf Configuration”. 

Select the Diagnostics node (on the left hand side of the form), and then click “Enable Message Logging” (on the right hand side of the form).

Next click the setting for Log Level (set to “Malformed, Transport” by default and select “Service Messages” as shown below:


Finally, expand the Diagnostics node and select the Message Logging node and change the LogEntireMessage setting to True.


Close the Microsoft Service Configuration Editor, saving your changes.

By default the Editor sets the log file to an absolute file path.  You can change this in the App.Config to a relative path:



Press F5 to run your WCF Service Library, double click on the GetData() method within the IService1 contract.  Enter a request value for the operation on the right hand side, we’ll be using 1234 for this example, and click “Invoke”.


Now close your WCF Test Client window.

To view your Service Log file, open Windows Explorer and navigate to your Project output folder.  For this example that directory is C:\Projects\WcfTracingDemo\WcfTracingDemo\Bin\Debug. 

You will now be able to see your new log file:  app_messages.svclog

Double click on the file to open it within the Microsoft Service Trace Viewer application and select the activity line on the left hand side.

This will populate the Message Log Trace lines on the right hand side, to see your request scroll down to the second to last entry and select it.  To view the request scroll down on the “Formatted” tab to view the formatted request:


To view the response select the last entry in the Message Log Trace lines and again scroll down within the “Formatted” section to reveal your response.


I hope you find this brief tutorial on how to Trace messages in WCF comes in useful – happy coding!

Source code:  WcfTracingDemo.zip

C# and SQLite

This post will show how you can add SQLite to a C# project.

First up, you’ll need to download two components to help you send commands to your SQLite database:

1) The SQLite ADO.NET framework System.Data.SQLite (installer)


2) The SQLite Administrator tool (standalone tool)


Step 1: Create your Console application in Visual Studio


Step 2: Run the SQLite Administrator tool and select Database > New to create your database.  Create the file within the console project you have just created so you can easily add the file to your project in a moment.


Step 3: Right click on Tables and select Create Table.  Click Add Field to add the fields to the table, once you’ve finished click the Create button.


Step 4: On the right hand side on the SQLite Administrator screen you select the “Edit Data” tabe, choose your new table from the dropdown list and directly add new records to the table.  We’ll be reading these new records from our console application shortly.


Step 5: You’ll need to add the SQLite.dll reference to your project,  Right click on the project and select Add Reference then navigate to C:\Program Files\SQLite.Net\Bin directory and add the System.Data.SQLite.dll file.


Step 6: We’ll be storing the connection string in an App.Config so right click on your project and “Add > New item” then select App.Config from the General section.


Step 7: Paste the following code into the app.config file.

Step 8:  To read the Connection String from our App.Config file we’ll need to add the System.Configuration framework to our project.  Right click on the project and select “Add Reference”:


Step 9: On the Visual Studio main menu, select Project > Show All Files to see your new SQLiteDemoDb.s3db file.  To add it to your project just right click on the file and select Include In Project.  In the Properties for this file, set “Copy To Output Directory” to “Copy Always”.


Step 10: Our last step is to paste the following code into our Program.cs file:

Now you’re ready to run your Console application by pressing F5


I hope you found this post helpful, happy coding!

Source code:  SqliteDemo.zip 

System.Data.SQLite (installer):  http://sourceforge.net/projects/sqlite-dotnet2/

SQLite Administrator tool (standalone tool):  http://sqliteadmin.orbmu2k.de/

How to build a Dynamic Data website in 60 seconds

Do you want to be able to create a website to edit the records in your database without having to write any code?  Well with Dynamic Data and .Net it’s easy.

This step by step guide will automagically create your website so quickly that within a minute from now you’ll be able to create, read, update and delete the records in your database tables via your own web application.

For this demo I am going to use our old friend the Northwind database, a SQL Server sample database from Microsoft.


Step 1:  Open Visual Studio 2010 and create a New Project from the Web template “ASP.NET Dynamic Data Entities Web Application”


Step 2: Right click on your project and select Add > New item...  Within the Data category choose “ADO.NET Entity Data Model”


Step 3: Select Generate from database and click Next


Step 4: Click on the “New Connection…” button to add a new connection to your database, enter your server and database name, click Test Connection to make sure your user has access.  Assuming the connection is fine you can click OK.



Step 5: Click Next :)  That step was easy eh?!  Just notice the Entity Data Model name has defaulted to NorthwindEntities.  This is important because we’ll be referencing this object shortly,.

Step 6:  Choose the objects you want your website to interact with.  For this example I’m going to tick the tables box to select all tables.  I’ll manually remove the system table named sysdiagrams as we don’t need to be interacting with these tables.  Now click Finish.


You can now see your tables within the designer view of your Entity model.


Step 7: For the last step you need to update the Global.cs file to reference your new Entity Model.  You do this by scrolling down to the “public static void RegisterRoutes(RouteCollection routes)” method, uncomment out the line highlighted below and enter the name of your EntityModel.


Change the line from this:

To this:

And that’s it - all done!  Your new website is now ready for you to use.  Just press F5, (you’ll be asked if you want to enable debugging click Ok) and then your new web application will appear.


The home page displays all your tables, ready for you to interact with.


Click on one of the tables, I’ve selected Categories, and the site will display a page containig the data, links for insert, edit and deleting the records.  You’ll also get a link to “View” referenced data like in Products in the example below.


The “Insert” page for Categories:


The “Edit” page for Categories:


The “View” page for for our referenced Products table takes use to the Products page.


If you want to restrict which tables are displayed within the application go back to the line you edited within the Global.asax.cs file and set the ScaffoldAllTables = false;

Now create a new partial class for each table you want to edit and add the attribute [ScaffoldTable(True)] to the class, where the claasname matches the database table name.  For example, I’ve created one file called ScaffoldTables.cs and added two partial classes for the Category and Customer table in Northwind.


Now when you run your web application you’ll only be shown the tables you explicitly added partial classes for.


I hope you find this quick introduction to Dynamic Data useful - happy coding!

Source code:  DynamicDataDemo.zip

Friday, 18 March 2011

How to view the GAC using Windows Explorer

If you want a quick view of the GAC then navigate to C:\Windows\Assembly using Windows Explorer:


Through a bit of jiggery pokery Explorer conjures up a view of the GAC even though the files aren’t physically directly in this folder:


You may have noticed I’m running Windows XP (on a netbook for travel) but it works the same on Win7 machines.

Wednesday, 9 March 2011

How to create JSON WCF RESTful Service in 60 seconds

WCF makes it very easy to expose JSON data over a RESTful interface, as long as you are aware of a couple of “gotchas” in advance.

This article will explain those to you, so you can focus on your business logic rather than configuration of your WCF services.

We start this example by creating a WCF Service Library project:


Next we need to add a reference to the System.ServiceModel.Web framework.  Right click on your project file and select Add Reference…


As this framework is not part of the .Net Framework 4 Client Profile, Visual Studio kindly informs us that it will update our target Framework to the full version of .Net Framework 4.  Click Yes to accept this change:


We are now ready to update our code.

Copy and paste the following code into the App.Config file:

<?xml version="1.0"?>
<service name="WcfJsonRestService.Service1">
<endpoint address="http://localhost:8732/service1"
<webHttp />
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>

Notice the binding is set to webHttpBinding as opposed to the normal project template default of wsHttpBinding. 

The other important change is the addition of an endpointBehavior for WebHttp.

These two changes are required to enable JSON over REST for WCF.

Copy and paste the following code into the IService1 file:

using System.ServiceModel;

namespace WcfJsonRestService
public interface IService1
Person GetData(string id);

Notice we are accepting an “In” parameter for id of datatype string.  For this example we are returning a custom type of Person.

Copy and paste the following code into the Service1.cs file:

using System;
using System.ServiceModel.Web;

namespace WcfJsonRestService
public class Service1 : IService1
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "data/{id}")]
public Person GetData(string id)
// lookup person with the requested id
return new Person()
Id = Convert.ToInt32(id),
Name = "Leo Messi"

public class Person
public int Id { get; set; }
public string Name { get; set; }

The key elements here are the attributes applied to the method.  We are enabling the method to be called over HTTP GET, returning the data in Json format and setting the Uri template to ensure we are using a RESTful interface.

To test your brand new service we will pass in the id value of 10 simply by opening your favourite browser and pasting in the following URL: 



Source code:  WcfJsonRestService.zip

Example With Multiple Parameters

using System;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace WcfJsonRestService
public interface IService1
Person GetData(string id);

Person GetDataWithTwoParams(string id, string name);

public class Service1 : IService1
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "data/{id}")]
public Person GetData(string id)
// lookup person with the requested id
return new Person()
Id = Convert.ToInt32(id),
Name = "Leo Messi"

[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "data/{id}/{name}")]
public Person GetDataWithTwoParams(string id, string name)
// create person with the requested id and name
return new Person()
Id = Convert.ToInt32(id),
Name = name

public class Person
public int Id { get; set; }
public string Name { get; set; }

WCF Services with Zero Config (on both the Host and Client)

When dealing with your WCF services have you ever gotten so confused with all the settings in your App.Config that you just wanted to throw the file away? Well now you can, and I’ll show you how.

With .Net 4.0 WCF allows developers to take the convention over configuration approach to their services. This means that by omitting configuration settings, the .Net framework will create defaults in their place and make your services fully available and operational.

So lets check out how it’s done!

First, create a new WCF Service Library project and call it WcfZeroConfig:


Now, and this is good bit, delete the App.Config file. Just right click on the file, select Delete – feels good right?!

The WCF Service Library project template makes two methods available for us by default and for this artictle we’ll be using the GetData(int value) method for our example.

As our WCF library is now complete, we are going to add another project to our solution to host the service. In production you would usually use IIS or a Windows Service to host your WCF Service Library but for this simple example we are going to use a Console application.

From the Visual Studio main menu select File > Add > New Project > Windows > Console Application and name the project WcfHost:


As this project will be acting as the host we’ll need to add references to both the System.ServiceModel assembly and our WCF Service Library project. Right click on the WcfHost Project file, select Add Reference and select System.ServiceModel framework:


Now select Projects (in the top left hand corner) and double click the WcfZeroConfig and press the close button.


To complete the host, copy and paste the following code into the Program.cs file:

As you can see it takes one line of code to create the ServiceHost object, passing in an Endpoint address and a single method call to open the host channel to make the service available.

On startup of the host, under the covers WCF (in .Net 4.0) will detect that no Binding or Contract has been supplied, either in our App.Config file or from our code, and will provide default values. From the Endpoint address the framework can see we are using Http and will provide the default binding of basicHttpBinding. The contract type of IService1 will also be inferred from the Service1 concrete class.

To run the host, select the WcfHost project and press F5 to build and run the application.


We are now ready to create the client application to consume our WCF Service. From the Visual Studio main menu select File > Add > New Project > Windows > Console Application and name the project WcfClient:


As before you’ll need to add the System.ServiceModel framework (right click on the project file > Add Reference…) along with the WcfZeroConfig project, this is so that the WcfClient project is aware of the WCF Service contract type “IService1”.

To complete our client, just paste in the following lines of code into the Program.cs file:

To complete our example:

1) You’ll first need to build the solution by right clicking on the solution file and selecting Build Solution

2) Run the C:\Projects\WcfZeroConfig\WcfHost\bin\Debug\WcfHost.exe file

3) And finally, run the C:\Projects\WcfZeroConfig\WcfClient\bin\Debug\WcfClient.exe file and enter a number

That number then gets passed to our WCF Service and our client receives the result.


The full source code is available here: WcfZeroConfig.zip

Tuesday, 8 March 2011

How to add PostSharp to your C# project in 60 seconds (a simple AOP introduction)

Here is a simple and brief introduction to PostSharp and AOP style logging and monitoring.

We are going to create a simple Console application with a single class containing three basic methods, one of which will deliberately throw an exception.  By doing this we’ll gain an insight into the some of the powerful abilities of AOP style programming.

As you’ve found this blog, I assume you know what PostSharp is but in case you don’t I’ll give you a very quick overview.  PostSharp is a static AOP library which means it applies your “Aspects” at Compile time, which alters the byte code of your assembly file.  Your Aspects are code classes written in C# which get code generated into behaviour based on the attributes you add to your code.  For this example our Aspects will be ouputting a message to the console on entry and exit of each method call.

And for more on PostSharp from the creators website visit:


For further information on AOP you can visit:


Wait up, what about the 60 seconds bit?  Yes you really can add PostSharp to your project in 60 seconds but before we start we are going to download and install the PostSharp library and create a simple C# console app.

So first up, visit the SharpCrafters website to download the PostSharp library.  At the time of writing this blog, the current version is v2.0 with a 45 day trial or community license.


Step two, let’s create our new console application and call it PostSharpIntro:

create console

Next up we are going to add the following code to your Program.cs file:

We have added a simple calculator class with methods to Add, Subtract and RunUnstableCode.  We’ll call all three method displaying each result to the console.

So you are now ready to press F5 and run your code.


So this is the interesting bit, adding PostSharp to your project.  There are 4 easy steps so if you are ready with your stopwatch, let’s GO!

Step 1: Open Windows Explorer and navigate to the following PostSharp Samples directory:

C:\Program Files\PostSharp 2.0\Samples\.NET Framework 3.5\CSharp\Trace

Note: Where Program Files is the default folder for programs on your machine.

2. Now add the aspects from the example project by dragging the Formatter.cs, QuickTraceAttribute.cs and FullTraceAttribute.cs files into your PortSharpIntro project.

3. Add a Reference to the PostSharp library (right click on your project > Add Reference… > Browse)

Navigate to the following file and double click on it then press the Add button:  C:\Program Files\PostSharp 2.0\Release\PostSharp.dll

4. The final part is to let our project know exactly what and where we should be logging.  To do this we need to add two new lines of code (highlighted below):

Line 3:  Log everything within our PortSharpIntro namespace.  Notice that the PostSharp aspect files are not within this namespace, this is deliberate so we don’t log the aspects.

Line 11:  Ensures that the log messages will be sent to the console window but you can alter this to output to a text file, database, the event viewer, have combinations of multiple outputs, just about anything you like.

And that’s it - pretty simple, eh!  Press F5 to run your application and you can see new messages appear.


The console window messages explained:


Pretty cool stuff!  Now you’re probably thinking it would be useful to see which variables were passed into our method that throw the exception.  Simply switch from QuickTrace to FullTrace:

And press F5 to see the values (.ToString()) for each of the parameter variables:


This example is using the Microsoft System.Diagnostics.Trace framework for its logging mechanism but this could easily be swapped out for NLog, Log4Net or any other logging framework.

I hope this brief introduction into PostSharp and Aspect Oriented Programming helps, enjoy your programming!

Source code:  PostSharpIntro.zip