Using Spring.Net, SQLite and NHibernate

I was planning to put a quick spike together on putting single sign-on, using CardSpace, OpenID and Windows Live, into an application to test it out for a project at work. Maybe it was because of the weekend, but I was quite enthusiastic and added several technologies to the sample which I had never used before. Six hours later, there was still no single sign-on or even a fully working sample application to add the behaviour to. So instead of posting one post, I’ll have a mini series where SSO will actually be a side track.

Getting the database set up was one of the first things I wanted to do. I didn’t want to add a MS SQL database to the project since that would require anyone who downloaded this project to have the database engine running. On various other blogs and .Net sites I’ve read there was talk about a lightweight alternative in the form of Sqlite. The .net provider can be downloaded here and boy was I lucky, the day I wanted to try it out they released a new version. Their latest version includes designer support in Visual Studio. Halfway august the Spring.Net team had also released a new version (1.2 M1) so I grabbed that version and NHibernate went 2.0 GA as well.

Since the Spring.Net assemblies are strongly signed they expected SQLite 1.0.56 and not 1.0.58 which was the one I downloaded. To make use of the new dll’s I added this to my configuration.

<db:provider id="DbProvider" provider="SQLite-1.0.56" connectionString="${db.datasource}"/>

Spring.Net has several DbProviders already configured, one of them being for version 1.0.56. Normally you don’t want to configure the entire provider for a new version so I just reused the existing configuration and added an assembly redirect.

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="System.Data.SQLite" culture="neutral" publicKeyToken="db937bc2d44ff139"/>
    <bindingRedirect oldVersion="1.0.56.0" newVersion="1.0.58.0"/>
  </dependentAssembly>
</assemblyBinding>

This is all defined in the spring manual, but it actually took me quite some time to get it running. Only when adding the xml namespace the redirect was picked up when running the application. The NHibernate version I had was also newer so a redirect was necessary for those dll’s as well.

With this out of my way I still had to tell NHibernate to use SQLite. The official site gives this sample configuration:

<?xml version="1.0" encoding="utf-8"?>
  <hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
    <session-factory name="NHibernate.Test">
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      <property name="connection.driver_class">NHibernate.Driver.SQLiteDriver</property>
      <property name="connection.connection_string">
				Data Source=nhibernate.db;Version=3
      </property>
      <property name="dialect">NHibernate.Dialect.SQLiteDialect</property>
      <property name="query.substitutions">true=1;false=0</property>
    </session-factory>
  </hibernate-configuration>

Which is almost correct, but not quite. Below you find the complete correct springified configuration, so extract the pieces you need when using plain NHibernate. The difference is in the driver class.

<object id="NHibernateSessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate20">
  <property name="DbProvider" ref="DbProvider"/>
  <property name="MappingAssemblies">
    <list>
      <value>TodoCore</value>
    </list>
  </property>
  <property name="HibernateProperties">
    <dictionary>
      <entry key="connection.provider"
			 value="NHibernate.Connection.DriverConnectionProvider"/>
      <entry key="connection.driver_class" 
             value="NHibernate.Driver.SQLite20Driver"/>
      <entry key="dialect" 
             value="NHibernate.Dialect.SQLiteDialect"/>
      <entry key="query.substitutions" 
             value="true=1;false=0"/>
    </dictionary>
  </property>
  <property name="ExposeTransactionAwareSessionFactory" value="true" />
</object>

Great we’ve configured our data access! But the repository is giving me errors, it can’t find the database file. The project structure I have is illustrated below.

My first attempt was to use relative path names.

<add key="db.datasource" value="Data Source=~App_DataTodoDb.db;Version=3;"/>

But that just failed, to get this working I used the, for me, new |DataDirectory| variable which did cause the database to be found and used.

<add key="db.datasource" value="Data Source=|DataDirectory|TodoDb.db;Version=3;"/>

The data was now being retrieved, isn’t that wonderful, only took me maybe two or three hours. As front end I first added a WPF application, but if you see that Window1.xaml file for the first time you have a bit of a writer’s block. Even when you drag a button on it, you don’t get to see one and adding a grid to the window and then trying to add a column was quite overwhelming, there even seem more options available compared to the third party components I use at work. So for now just good old Winforms, but a WPF front end will definitely be added. I also played around with the bindinglist you can create when using a grid, I must admit I’ve never used it before. I’ve always used my own implementation, we’ll see where it goes when I add an edit mode to the application. So for now I can only give you a configured application which shows your todos, so basically the same setup as my last spring.net sample which illustrated the support for webservices.

SampleApplication.rar (2.74 mb)

And before anyone asks, yes tests should be added.

Installing a Scythe Mini Ninja

After using my htpc for 4 months I sometimes became annoyed of the noise being produced by the system. It varied from day to day, so I decided to do something about it.

There were only 4 fans in the system, one on the cpu, two on the side of the case to get airflow going and one to cool down the psu. The loudest one was the stock cpu cooler, closely followed by the psu fan. The two 120mm fans are already quite good. After searching on the internet for a passive cpu cooler it seemed that the Scythe Mini Ninja was quite popular and ideal for the system that I have assembled. No computer parts shop in Belgium had it, or they were quite expensive, so I purchased one on eBay.

In the package you find: thermal paste, 3 mounting systems (meaning universal socket support), screws, one fan, clips to attach the fan and one big heatsink.

When removing the stock cpu cooler I noticed that there was not much of thermal paste on the standard heatsink, so removing any residue was quite easy. I also ignored all the advice of installing the Ninja outside the case, which would mean dismantling the htpc. In the end it didn’t save me that much time, since I had to remove the ram and some of the power cables to install the heatsink, also if you’ve got thicker fingers than me you probably won’t be able to reach all of the pins used to attach the Ninja to the motherboard. Make sure to apply an even layer of thermal paste on the cpu, you won’t need to use all of it since too much is as bad as too little.

I powered the system back on again, changed the bios to allow the absence of a cpu fan, and off it went. With the top of the case screwed back into place I first thought the upgrade didn’t change a lot, but I was sitting at 20cm from it. When I had placed the htpc back into it’s normal habitat and sat on a normal distance (2 meters) the psu fan was still audible but any ambient sound can overcome it. When I start a movie the system can’t be heard now.

To test the heatsink I started two instances of cpuburn and watched the result with speedfan. After 5-10 minutes the temperature reached around 50 degrees which is quite good, especially if you keep in mind that the two cores will never be under that amount of load under normal use.

So overall a great product.

Using appSettings in your Spring configuration

This seems to be an undocumented feature that someone asked about on the user forum of the Spring.Net framework, I don’t know where I picked it up so I’m writing it down here.

When using .Net you tend to put configuration values in the appSettings section of your app or web.config. Entries like filepaths or other constants fit here nicely. If you’ve written an application powered by Spring.Net you’ll also have several spring configuration files which define the objects in use by your system. Most of their dependencies (if not all) are quite static but sometimes there’s the need for a configurable value. These tend to change more than other object relations so instead of searching through all your definitions to change them wouldn’t it be better to have a central place where you can manage them? Of course it would, so let’s use the appSettings section!

In order to reference the appSettings in your Spring configuration file you need to add this object definition to your configuration:

<object name="appConfigPropertyHolder" type="Spring.Objects.Factory.Config.PropertyPlaceholderConfigurer, Spring.Core">
  <property name="configSections">
    <value>appSettings</value>
  </property>
</object>

Your appSettings typically looks like this:

<appSettings>
  <add key="LoggerOutputFile" value="c:MyOutputFile.txt"/>
</appSettings>

Now you can reference this value using ${“LoggerOutputFile”} as illustrated below.

<object name="MyLogger" type="SpringAppSettingsConsole.Infrastructure.FileLogger, SpringAppSettingsConsole">
  <constructor-arg  value="${LoggerOutputFile}"/>
</object>

Full sample with source code can be downloaded here: SpringAppSettings.zip (247.31 kb)

Updated to BlogEngine 1.4.5

A new BE version, means sql scripting time for MS SQL 2000 users. For a full upgrade guide you should go to Al Nyveldt’s blog.

If you are creating a new blog or are upgrading from 1.3.x, just use the correct script for you.

MSSQL2000_Setup1.4.5.0.sql (24.91 kb)

MSSQL2000_UpgradeTo1.4.5.0From1.3.x.sql (10.07 kb)

If you are currently using 1.4.0 there’s some more work you’ll need to do. In this new version the column ‘Settings’ in the table ‘DataStoreSettings’ has changed from binary datatype to varchar, the corresponding change on MS SQL 2000 means moving from the image datatype to ntext. This is not possible / allowed by the server. The easiest thing you can do is to take note of your settings under the extensions tab in the administration control panel and delete all rows from the table ‘DataStoreSettings’. Every extension will populate the table again with data the first time they get loaded with the new BE version, you can then configure the extensions again with the settings you want. It’s quite possible that you are still using the default settings of your extensions, like me, then you don’t need to worry about the old settings, just clear the table of its entries.

If you’ve used the script from my earlier post, when I upgraded from 1.3 to 1.4, there was one insert statement missing from the script. The insert statement added the widget bar with its default configuration. Since it was missing then and we are deleting all entries from the ‘DataStoreSettings’ I’ve included the insert statement, the default script that ships with BE 1.4.5 has an update statement in place for that entry in the DB.

MSSQL2000_UpgradeTo1.4.5.0From1.4.0.0.sql (3.20 kb)

Finally, if you are running SQL Membership and Role provider and are upgrading from an earlier version don’t forget to check the applicationName of the providers, in 1.4 this changed from BlogEngine.Net to BlogEngine. What you need to change is described in my earlier post.

Building webservices with Spring.Net

Building and consuming anything but a trivial web service with Visual Studio can be quite an error prone task. The service itself is difficult to test outside of the web environment, the proxy class generated by Visual Studio will, most of the time, be in a conflicted state in your code repository as multiple developers add and change methods. It’s also quite cumbersome if you want to map those proxy classes back to your own classes. The list goes on and while Windows Communication Foundation does solve some of these issues I’d like to introduce you to the service infrastructure of Spring.Net which can help you to expose your services and is available on .net 2.0.

Let’s first look at the server side. Instead of decorating your service with webservice and webmethod attributes you can write a plain old c# object (poco) which can be tested like any other class and be hosted in multiple environments, exposing the service via remoting is just a configuration change. Nothing even prevents you from making a fat client, just keep the service itself behind an interface.

public class ProductService
: IProductService
{
	private List<ProductDto> products;
 
	public ProductService()
	{
		products = new List<ProductDto>();
		products.Add(new ProductDto("Pizza Margherita",9.75));
		products.Add(new ProductDto("Pizza Pepperoni Lovers",10.95));
		products.Add(new ProductDto("Pizza Cheesam ",10.95));
	}
 
	#region IProductService Members
 
	public RetrieveProductsResponse RetrieveProducts(RetrieveProductsRequest request)
	{
		return new RetrieveProductsResponse(products);
	}
 
	public SearchProductsResponse SearchProducts(SearchProductsRequest request)
	{
		List<ProductDto> productMatches = new List<ProductDto>();
		foreach (ProductDto product in products)
		{
			if (product.Name.ToUpper().Contains(request.Name.ToUpper()))
			{
				productMatches.Add(product);
			}
		}
		return new SearchProductsResponse(productMatches);
	}
 
	#endregion
}

As you can see, nothing fancy here. The ProductDto, requests, responses and the service interface are all located in an assembly which will be shared between the client and the server.

Whenever you build a service layer around your application, the best way to look upon it is like a GUI. You expose the behaviour of your domain, just not with web or winforms.

Since the service is just a poco, putting it into your spring configuration is just like you would add any other class. You can perform DI, AOP, … upon it like you’d normally do.

<object name="ProductService" type="Service.ProductService, Service"/>

To make it available as a webservice you use the Webservice exporter which can be found in the Spring.Web assembly as illustrated below.

<object id="ProductWebService" type="Spring.Web.Services.WebServiceExporter, Spring.Web">
  <property name="TargetName" value="ProductService"/>
  <property name="Namespace" value="http://www.bennymichielsen.be/services"/>
  <property name="Description" value="Defines operations upon products"/>
  <property name="MemberAttributes">
    <dictionary>
      <entry key="RetrieveProducts">
        <object type="System.Web.Services.WebMethodAttribute, System.Web.Services">
          <property name="Description" value="Retrieves all products"/>
          <property name="MessageName" value="RetrieveProducts"/>
        </object>
      </entry>
      <entry key="SearchProducts">
        <object type="System.Web.Services.WebMethodAttribute, System.Web.Services">
          <property name="Description" value="Searches for products which have a name like the one supplied."/>
          <property name="MessageName" value="SearchProducts"/>
        </object>
      </entry>
    </dictionary>
  </property>
</object>

Using the Webservice exporter you can export any object in your configuration as a webservice, just point it to the appropriate object definition using the TargetName property. I’ve populated some more properties just to show how you can use this class. It is however necessary to have an interface(s) on your service, but since this is a best practice anyhow I don’t see this as a shortcoming.

On the client side a similar approach can be used to consume the webservice using the WebserviceProxy factory in the Spring.Services assembly. Using this class your code can depend upon the service interface instead of the proxy class itself. If you want to use the proxy class, this is still supported. In this case Spring will create a proxy which will implement the service interface and map to the Visual Studio proxy. Note that the original service does not have to implement this interface, the methods supplied in the interface are mapped using a kind of duck typing. This is very useful if you don’t control the service but are consuming it and don’t want to tightly couple your code.

If you do control both sides, it is much easier to let the proxy be generated at runtime.

<object name="ProductService" type="Spring.Web.Services.WebServiceProxyFactory, Spring.Services">
  <property name="ServiceUri" value="http://localhost:1871/ProductWebService.asmx"/>
  <property name="ServiceInterface" value="ServiceContract.Interface.IProductService, ServiceContract"/>
</object>

This allows you to use the service interface, the concrete implementation is of no concern. What’s also very useful is that you can reuse all the classes which are already in the service contract assembly, thus preventing your solution from being polluted with any additional code.

For more information please take a look at the documentation.

SpringWebservicesSample.zip (1.22 mb)

Blogging tools

Since there’s no code highlighter that works for me in Blogengine.Net I use this site. It pretty much supports any language, paste your code, select some options and you get your html to use.

To check my spelling I use this site, I’ve been using it for years now. Though I don’t need it when I’m using my Mac since it checks everything you write, regardless the application you are using.

Initializing an array with arrayWithObjects

If you’re creating an array and adding objects to it at initialization, in Cocoa, don’t forget that the last element of the list needs to be nil, it’ll save you debugging time ;).

NSMutableArray *array = [NSMutableArray arrayWithObjects: @"one", @"two", @"three", @"four", nil];

Developer reference.

Cocoa Programming for Mac OS X (Ch 19-21)

After a little Cocoa break I’m back, while continuing through the book I seemed to have forgotten some stuff already, not good.

So, next up, Keyboard Events.

This chapter explains how the events are used for handling keystrokes as well as the first responder concept. The first responder being the active view element (button, text area,…) and there’s a whole mechanism working in the background when the first responder changes. Not a lot of ground breaking material here, probably the most important piece of code here is an example of how to code the fuzzy blue box around an active custom view.

Chapter 20, Drawing text with attributes.

Here we are taught how to show strings in various formats, not that interesting. One nice feature however is that all the drawing commands you write can be converted into PDF by the AppKit framework.

Chapter 21, Pasteboards and Nil-Targeted actions.

The clipboard in Windows, pasteboard in OS X. Different name, same concept, although I’ve never read about it in any .Net book I’ve seen but you know what it does :). What you need to remember from this chapter is that you can do a lazy paste. Meaning that you don’t have to put it in the clip errr pasteboard when the user presses the copy command. You can wait until he presses paste, very valuable if you’re working with large quantities of data.

Nil targeted actions are best explained with an example. You can set the selector (method signature for .net people) of a menu item to anything you want, say removeEmployee:, when the menu item’s target is nil and the menu item is invoked, it will traverse the responder tree until someone acts upon it.

Nothing fancy was covered in these past chapters, but you need to know about these things. I did spend quite some time on the applications, probably because there was a two week pause. For those interested I’ve attached all the source code.

As always, you can get the book here .

TypingTutor – Chapter 19.zip (46.44 kb)

TypingTutor – Chapter 20.zip (53.47 kb)

TypingTutor – Chapter 20 Challenge 1.zip (53.73 kb)

TypingTutor – Chapter 20 Challenge 2.zip (57.89 kb)

TypingTutor – Chapter 21.zip (53.58 kb)

TypingTutor – Chapter 21 Challenge 1.zip (53.75 kb)

RaiseMan – Chapter 21 Challenge 2.zip (111.20 kb)

Developing .NET Software on a Mac

Followed some links and found this podcast on deep fried bytes. It’s interesting to hear, although the title is a bit misleading. They talk about .net development 25% of the time using virualization tools like VM Ware, the rest of the podcast is filled with general switchers info and some recommended applications.

Nothing about Mono though, too bad.

Adding object definitions from non-local classes

On the Spring forum someone asked if it was possible to add object definitions to the application context of classes which were beyond the searchable range of the application. I was a little bit sceptic at first but one debugging session later, I found out that it is possible to do this. Though I really don't support the whole idea of doing this.

When you are not using fully qualified assembly names in your definition Spring will look at the current loaded assemblies to resolve the type, so with this trick you can make it work. The topic can be found here and the source code can be found here, don't forget to change the path of the “ClassLibrary1” assembly to make it work.

class Program
{
	static void Main(string[] args)
	{
		Assembly.LoadFile(@"C:MyPathToSomeDllClassLibrary1.dll");
		object o = ContextRegistry.GetContext().GetObject("MyObject");
		Console.WriteLine("Retrieved object from context");
		Console.ReadLine();
	}
}

<objects xmlns="http://www.springframework.net" >
  <object id="MyObject"
          type="ClassLibrary1.Class1">
    <property name="Test" value="MyTestValue"/>
  </object>
</objects>