Dutch alt.net

If you’re into alt.net and speak dutch, though it’s not really required, you might be interested in the dutch alt.net group. The plan is to have regular meetings “with like minded people to discuss and demonstrate the merits and drawbacks of different approaches in .net development”. For the next meeting we’re trying not to have an agenda, let’s see where that goes.

Adding transactions and exploring the BindingList

I stopped working on my todo sample after all the frameworks were playing nicely together and my todo list was displayed. Next up was adding edit capabilities.

At work I normally use Spring.Aop to inject an INotifyPropertyChanged implementation into the objects I pass to the view, but since I’m trying out new stuff here I turned to the default .Net BindingList to support change notification. I’m actually quite happy with the capabilities that are provided, for now at least. The BindingList has a ListChanged event which gets fired if either a property of an object in the list gets changed or the list itself is modified. For my basic sample here this is more then enough. Something I struggled with however, was how to turn off notifications while the list is being populated with data which improves responsiveness of the UI. After some googling I found that you had to call ResetBindings, strange that I didn’t find anything on MSDN that told me how to work in this scenario. I might need to pick up a book on Windows Forms development though, professionally I work with WinForms 99% of the time when I need to create a UI, who knows what other ‘goodies’ I’m missing out on.

public void SetDatasource(List<TodoDto> todos)
    todoDtoBindingSource.RaiseListChangedEvents = false;
    todoDtoBindingSource.DataSource = todos;
    todoDtoBindingSource.RaiseListChangedEvents = true;

With the UI now raising events when the user makes changes, the presenter that is listening had to keep track of the changes and forward them to the webservice when the user wants to save his work. The code I’ve written for that isn’t rocket science or hard to grasp. It boils down to what is transferred between the client and the server.

public enum ChangeType
    Added = 0,
public class TodoEditDto
    public virtual Guid EditId { get; set; }
    public virtual TodoDto EditedTodo { get; set; }
    public virtual ChangeType ChangeType { get; set; }

The ChangeType indicates what has happened, the item was added, changed or deleted. The TodoEditDto wraps the edited dto, adds a ChangeType and EditId property. The EditId is generated on the client and used to identify newly saved objects when the server sends back the Id’s that were generated when the todo was persisted. That way a new created todo can be edited right away after saving it.

// saved data to server
foreach (var persistedEdit in response.PersistedEdits)
    var foundEdit = (from edt in editedTodos
                     where edt.Value.EditId.Equals(persistedEdit.EditId)
                     select edt.Value).First();
    foundEdit.EditedTodo.Id = persistedEdit.EditedTodo.Id;

With some basic editing now in place, some work is still needed in the UI, let’s now add transactional support to our save method. Spring.Net allows you to add this capability declarative or programmatic and even within these two approaches there are several ways to achieve your result. At work I’ve always used the declarative way using AutoProxy and the [Transaction()] attribute. To make that work you need to add a reference to Spring.Data, add the attribute to the methods that need to be transactional and add the following object definitions to your configuration.

<object id="AutoProxyCreator" 
		type="Spring.Aop.Framework.AutoProxy.DefaultAdvisorAutoProxyCreator, Spring.Aop"/>
<object id="TransactionAdvisor"
		type="Spring.Transaction.Interceptor.TransactionAttributeSourceAdvisor, Spring.Data">
		<property name="TransactionInterceptor" ref="TransactionInterceptor"/>
<!-- Transaction Interceptor -->
<object id="TransactionInterceptor"
		type="Spring.Transaction.Interceptor.TransactionInterceptor, Spring.Data">
		<property name="TransactionManager" ref="TransactionManager"/>
		<property name="TransactionAttributeSource" ref="AttributeTransactionAttributeSource"/>
<object id="AttributeTransactionAttributeSource"
	type="Spring.Transaction.Interceptor.AttributesTransactionAttributeSource, Spring.Data">
public SaveEditedTodosResponse SaveTodos(SaveEditedTodosRequest request)
    // do stuff

At runtime, Spring.Net will create a proxy for each service that has the tranascation attribute declared on its methods and manage the transaction from in that generated class. Everything you’ve written will be transactional from that point until the method that is being called is completed. For now however, let’s use the TransactionProxyFactoryObject. To use this approach I only need to change my service definition. Through the transaction attributes property I can define which methods need to be transactional, in this case any method that starts with Save. The target property can be any object in your context.

<object id="TodoService" 
		type="Spring.Transaction.Interceptor.TransactionProxyFactoryObject, Spring.Data">
	<property name="PlatformTransactionManager" ref="TransactionManager"/>
	<property name="TransactionAttributes">
			<add key="Save*" value="PROPAGATION_REQUIRED"/>
	<property name="Target">
		<object type="TodoCore.AppService.TodoService, TodoCore">
			<property name="TodoRepository" ref="NhnTodoRepository"/>

With this in place we now have a basic application which is workable in a test environment. Speaking about tests, I really need to add them to the project. I’m not a very good TDD’er myself, though I’m convinced it is the way to go. I should start applying it.

SampleApplication04092008.rar (2.95 mb)

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">
    <assemblyIdentity name="System.Data.SQLite" culture="neutral" publicKeyToken="db937bc2d44ff139"/>
    <bindingRedirect oldVersion="" newVersion=""/>

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 name="dialect">NHibernate.Dialect.SQLiteDialect</property>
      <property name="query.substitutions">true=1;false=0</property>

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">
  <property name="HibernateProperties">
      <entry key="connection.provider"
      <entry key="connection.driver_class" 
      <entry key="dialect" 
      <entry key="query.substitutions" 
  <property name="ExposeTransactionAwareSessionFactory" value="true" />

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.