lauantai 14. elokuuta 2010

Moving blog to

As Blogspot is a bit limited blogging platform I have decided to move my blog to I recently registered a new domain for my blog: I would have wanted to have but the owner didn't feel like selling it.

So from this moment on my blog will be at and this blog isn't maintained anymore.

keskiviikko 4. elokuuta 2010

Using libmirror to read RFID tags with Violet's Mir:ror-reader

Libmirror is .NET-library that allows reading RFID tags with cheap reader from Violet called Mir:ror. Libmirror works in Windows on top of .NET Framework but by design it should also work in Linux and Mac OS X over mono but that hasn't been tested. Reader itself supports both A and B standards, connects to USB, looks cool and costs only about 50 €.
Violet is more known for their bunny Nabaztag. Personally I find the Nabaztag bunny pretty useless as also the Internet of Things ideology behind Mir:ror. At August 2009 Violet filed bankruptcy as their business seemed to have failed. Few months after bankruptcy, in October 2009, Violet was acquired by Mindscape. Recently the availability of Mir:rors and Nabaztags has resumed to pre-bankruptcy level so I decided to resurrect the libmirror projects.
Usually Mir:ror is used together with Violet's Mirware application that is based around the idea of internet of things. This means that every time you show RFID tag for the reader it will send it's identifier to Violet's server and look for any associated actions or applications. If applications or actions are found, them are then executed on client machine. For example you can associate action open URL with tag attached to umbrella and it will open Internet weather forecast site for you.
Libmirror frees Mir:ror from its restrictions and allows you to communicate directly with it without annoying Mirware. Current 2.0 version allows getting events for tag shown, hid, orientation changed and device removed.
Choreographies would allow controlling leds and sounds of Mir:ror but currently support for choreographies is non-existent as no-one has been able to reverse engineer the protocol. Currently it is possible to disable sounds and lights of device by calling SetChoreoOff after initialization before any tags are shown for the device but as no-one really understands the protocol I would recommend against using any methods related to choreographies. It's also possible to re-enable lights and sounds by calling PlayChoreo. That command also replays previous choreography.
To use libmirror go to and download latest version. Currently library uses 3.5 framework and should work on both 32 bit and 64 bit projects.
To get all connected mirrors you need to call MirrorFactory.GetMirrors() or if you want only the first one call MirrorFactory.GetMirror(). Here is example how to initialize one Mir:ror and attach events to it.
var description = MirrorFactory.GetMirror();
if( !description.IsInUse )
    var mirror = description.Create();
    mirror.TagShown += OnTagShown;
    mirror.DeviceRemoved += OnDeviceRemoved;
    mirror.OrientationChanged += OnOrientationChanged;
Remember that HIDDevice objects has to be correctly disposed otherwise device might appear in use as handler to device stays open until garbage collector disposes the object. This should be done with using syntax or binding to DeviceRemoved event and then gracefully disposing the object. Note that if you don't handle DeviceRemoved event then DeviceRemovedException is thrown by next method that tries to read or write to mirror. Here is example how to handle DeviceRemoved event.
private void OnDeviceRemoved(object sender, DeviceRemovedEventArgs e)
    e.IsHandled = true;

Other related projects and resources at net:

tiistai 27. huhtikuuta 2010

Creating external connection to same database server from inside SQLCLR

I recently had this need to create external connection apart from context connection within SQL CLR procedure. Of course I could have made connection string as parameter but that just didn't feel right. I wanted to connect to another database in same server with same credentials than current connection.
First problem here is to get even the name of current SQL Server because when using context connection SqlConnection.DataSource is null. Name of local server can be obtained with little SQL executed within context connection:
var getServerNameCommand = ContextConnection.CreateCommand();
getServerNameCommand.CommandText = "SELECT @@SERVERNAME;";
var serverName = (string) getServerNameCommand.ExecuteScalar(); 
To get database name we can use the same trick:

var getDatabaseNameCommand = ContextConnection.CreateCommand();
getDatabaseNameCommand.CommandText = "SELECT db_name()";
var databaseName = (string) getDatabaseNameCommand.ExecuteScalar();
Now we can create the another connection but problem is that CLR inside SQL Server is running actually as part of SQL Servers process. This means that if we try to create a connection with integrated security it will try to connect as SQL Server process. Luckily we can access to the identity of current user through SqlContext.WindowsIdentity. To create connection string I use SqlConnectionStringBuilder.
var builder = new SqlConnectionStringBuilder();
builder.IntegratedSecurity = true;
builder.InitialCatalog = databaseName;
builder.DataSource = serverName;
var impersonationContext = SqlContext.WindowsIdentity.Impersonate();
var connection = new SqlConnection(builder.ToString());
// Impersonation has to be undone otherwise you will get exception:
// ".NET Framework execution was aborted. The UDP/UDF/UDT did not revert
// thread token."                 
That's pretty much it. This might not work if you use SQL Server Authentication instead of integrated one. Deployed assembly also has to have EXTERNAL_ACCESS or UNSAFE permission to access SqlContext.WindowsIdentity.

torstai 11. maaliskuuta 2010

ASP.NET and data binding done right

I remember myself earlier having lot's of trouble with ASP.NET and databinding. Especially with events when there was post backs involved. That's because I did it all wrong. Most of people do it all wrong, even guys at Microsoft are writing terrible samples. For example at this years TechEd 2010 at Helsinki I saw many ASP.NET demos done with shortcut way.

But how to do it right? Keep the aspx-page clean. If you need to display some alternative stuff for user add it all to aspx page and then bind the visibility of those controls to your business data. From the other way around don't put presentation code to codebehind. With that I mean don't for example toggle visibility of controls from codebehind. Bind the visibilities at aspx side and let data binding do it's job.

In this post I'll give you an example how to create very simple web application with data binding done right. In the beginning you need empty ASP.NET Web Application. I named it BindingDemo.

First thing is to add properties holding your data to codebehind class.
public partial class _Default : Page
    protected string LabelText { get; set; }

Second thing is to add some controls to aspx page. Here's the ASPX-page with label, textbox and button. Nothing special there. Note the data binding of Text property of label.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BindingDemo._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="" >
    <head runat="server">
        <title>Binding Demo</title>
        <form id="form1" runat="server">
                <asp:Label runat="server" Text='<%# LabelText %>' />
                <br />
                <asp:TextBox runat="server" ID="SourceText" />
                <asp:Button ID="ChangeTextButton" runat="server" 
                            Text="Change text" onclick="OnChangeText" />
Third thing you need to do is to override OnDataBinding. It is called just before data binding occurs. That is the place where you get your latest data. In this example I just get stuff from session but you should propably get your data from database or something.
protected override void OnDataBinding(EventArgs e)
    LabelText = (string)Session[“Data”];
Last thing we want to do is to add some functionality to button. Here we are just going to store stuff to session for the sake of simplicity but in the real world you should propably store it to database.
protected void OnChangeText(object sender, EventArgs e) 
    Session[“Data”] = SourceText.Text;
And that's it. Here you have very simple ASP.NET application with data binding done right. Just remember that to keep things simple you don't want to set any of controls' properties directly from code behind. Let the data binding do that always for you.

torstai 4. maaliskuuta 2010

When not to implement GetHashCode() or Equals()

This question raises time to time and there seems to be no clear answer. But after working with NHibernate for five years the simple answer is don't. Of course that answer is over simplification and doesn't take account all the scenarios. In this post I'm going through one scenario.

When objects are not shared between sessions do not implement

When you only have objects living during life-cycle of session let the session's first level cache handle instances. NHibernate's first level cache will make sure that there is only one instance of your entity for each identifier.

Let's first consider why we have identifier for entities anyway? This is because databases require some kind of unique identifier to separate rows from each other. The identifier is not required at your domain model because every instance of object has it's own internal identity that separates it from other instances. The requirement of identifiers comes from the fact that databases are not planned to store objects. My tip would be that if you ever require to access identifier property from your model you are doing something wrong. Identifier only exists because it is required by your database.

If you do implement GetHashCode or Equals you will get trouble when creating new unsaved entities. The most obvious way to implement GetHashCode or Equals would be by associating them with identifier. But what happens when you create two new instances? If you use automatic identity generation provided by database those entities will have uninitialized identifiers until you save them for first time.

When you don't implement GetHashCode and Equals everything will work just fine as long as entities are not share between sessions. From the point of view of your model the identifiers don't exists. Actually I wonder why NHibernate don't just generate identifier properties on-fly when it generate proxies.