Month: June 2007

Dynamic Strongly-Typed Configuration in C#

    I’ve written at great length in the past about the perils of configuration, and I thought I’d written as much as I was willing on the topic. But I thought it was worth describing this solution, since it was so neat, and easy, and had most of the benefits of text based configuration and strongly typed inline configuration. I was recently messing about with some WCF P2P code, and the setup code had some configuration that looked like a likely candidate for a strongly typed configuration object that wouldn’t change frequently. I think this solution neatly addresses one of the main objections to hard coded configuration, which is that we do sometimes need to change configuration data at runtime without having to take down the servers or recompile them.

    The idea behind this solution stems from the use of a plug-in architecture such as the forthcoming System.AddIn namespace to arrive in VS2008. In that you get the options to load a namespace from a designated directory and make use of types found inside of the assembly. Why not use the same approach with configuration? We can dynamically load configuration assemblies and then use a single configuration setting to specify which type from those assemblies would be used as the new configuration. This has all the benefits normally reserved for text based dynamic configuration such as System.Configuration.ConfigurationManager, but with the added benefits of strong typing, inheritance, calculated configuration settings and added performance of POCOs.

    My WCF program was a simple chat client that I hope to be able to use between members of my family. Typical configurations were MeshAddress, and CredentialType that are unlikely to ever change frequently. Each of these configuration settings was defined on an interface called IChatClientConfig. Implementing that full interface was my default configuration class called DefaultChatConfig. That provided all of my defaults, and is perfectly usable. I then specialized that class with some others, for example with a different mesh address for chatting with people at work. A class diagram for the configuration objects are shown below.

    clip_image001

    Each class just provides a new implementation for the field that it provides a different value for.

    Loading the configuration is extremely simple. First you have to say which one of those classes you want to use for your configuration.

    <appSettings>
        <add key="P2PConfigSettings" value="ChatClient.Configuration.TechChatConfig, ChatClient.Configuration, Version=1.0.0.0"/>
    </appSettings>
    

    This simple app setting is the fully qualified type name of the TechChatConfig class on the bottom right of the diagram above. Which will be a default chat configuration with whatever tech chat configuration added. That’s all the prerequisites for loading configuration. Not all I need to do to load the configuration is this:

    private static IChatClientConfig GetConfigObject()
    {
        string configType = ConfigurationManager.AppSettings["P2PConfigSettings"];
        Type t = Type.GetType(configType);
        return Activator.CreateInstance(t) as IChatClientConfig;
    }
    

    Get whatever type I specified as a string from the configuration file, get the type specified by that string create and instance and return it. Simple. That configuration could be then stored as a singleton or whatever you need to do.

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public partial class Window1 : IPeerChat
    {
        private IChatClientConfig configuration;
    

    In my case I just stored it in the window object I was using it for – my chat client only has one window! Now I can just use it, whenever I do any comms.

    private NetPeerTcpBinding CreateBindingForMesh()
    {
        NetPeerTcpBinding binding = new NetPeerTcpBinding();
        binding.Resolver.Mode = config.PeerResolverMode;
        binding.Security.Transport.CredentialType = config.CredentialType;
        binding.MaxReceivedMessageSize = config.MaxReceivedMessageSize;
        return binding;
    }
    

    So you see that the process is very simple. With the addition of an AddIn model we could use a file system monitor to watch the configuration file, detect changes and reload the configuration object singleton using the mechanism described above. That fulfils most of the requirements that we have for type safety, performance, dynamism, intelligence, and object orientation. Very few configuration scenarios that fall outside of the bounds of this solution should be solved using local configuration settings anyway – in those cases you really ought to be looking at an administration console and database.

Using Mock Objects When Testing LINQ Code

I was wondering the other day whether LINQ could be used with NMock easily. One problem with testing code that has not been written to work with unit tests is that if you test business logic, you often end up making multiple round-trips to the database for each test run. With a very large test suite that can turn a few minute’s work into hours for a test suite. the best approach to this is to use mock data access components to dispense canned results, rather than going all the way through to the database.

After a little thought it became clear that all you have to do is override the IOrderedQueryable<T>.GetEnumerator() method to return an enumerator to a set of canned results and you could pretty much impersonate a LINQ to SQL Table (which is the IOrderedQueryable implementation for LINQ to SQL). I had a spare few minutes the other day while the kids were going to sleep and I decided to give it a go, to see what was involved.

I’m a great believer in the medicinal uses of mock objects. Making your classes testable using mocking enforces a level of encapsulation that adds good structure to your code. I find that the end results are often much cleaner if you design your systems with mocking in mind.

Lets start with a class that you were querying over in your code. This is the type that you are expecting to get back from your query.

public class MyEntity
{
    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public string Desc
    {
        get { return desc; }
        set { desc = value; }
    }

    private string name;
    private int age;
    private string desc;
}

Now you need to create a new context object derived from the DLINQ DataContext class, but providing a new constructor function. You can create other ways to insert the data you want your query to return, but the constructor is all that is necessary for this simple example.

public class MockContext : DataContext
{
    #region constructors

    public MockContext(IEnumerable col):base("")
    {
        User = new MockQuery<MyEntity>(col);
    }
    // other constructors removed for readability
    #endregion
    public MockQuery<MyEntity> User;
}

Note that you are passing in an untyped IEnumerable rather than an IEnumerable<T> or a concrete collection class. The reason is that when you make use of projections in LINQ, the type gets transformed along the way. Consider the following:

var q = from u in db.User
        where u.Name.Contains("Andrew") && u.Age < 40
        select new {u.Age};

The result of db.User is an IOrderedQueryable<User> query class which is derived from IEnumerable<User>. But the result that goes into q is an IEnumerable of some anonymous type created specially for the occasion. there is a step along the way when the IQueryable<User> gets replaced with an IQueryable<AnonType>. If I set the type on the enumerator of the canned results, I would have to keep track of them with each call to CreateQuery in my Mock Query class. By using IEnumerable, I can just pass it around till I need it, then just enumerate the collection with a custom iterator, casting the types to what I ultimately need as I go.

The query object also has a constructor that takes an IEnumerable, and it keeps that till GetEnumerator() gets called later on. CreateQuery and CloneQueryForNewType just pass the IEnumerable around till the time is right. GetEnumerator just iterates the collection in the cannedResponse iterator casting them to the return type expected for the resulting query.

public class MockQuery<T> : IOrderedQueryable<T>
{
    private readonly IEnumerable cannedResponse;

    public MockQuery(IEnumerable cannedResponse)
    {
        this.cannedResponse = cannedResponse;
    }

    private Expression expression;
    private Type elementType;

    #region IQueryable<T> Members

    IQueryable<S> IQueryable<T>.CreateQuery<S>(Expression expression)
    {
        MockQuery<S> newQuery = CloneQueryForNewType<S>();
        newQuery.expression = expression;
        return newQuery;
    }

    private MockQuery<S> CloneQueryForNewType<S>()
    {
        return new MockQuery<S>(cannedResponse);
    }
    #endregion

    #region IEnumerable<T> Members
    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        foreach (T t in cannedResponse)
        {
            yield return t;
        }
    }
    #endregion

    #region IQueryable Members
    Expression IQueryable.Expression
    {
        get { return System.Expressions.Expression.Constant(this); }
    }

    Type IQueryable.ElementType
    {
        get { return elementType; }
    }
    #endregion
}

For the sake of readability I have left out the required interface methods that were not implemented, since they play no part in this solution. Now lets look at a little test harness:

class Program
{
    static void Main(string[] args)
    {
        MockContext db = new MockContext(GetMockResults());

        var q = from u in db.User
                where u.Name.Contains("Andrew") && u.Age < 40
                select u;
        foreach (MyEntity u in q)
        {
            Debug.WriteLine(string.Format("entity {0}, {1}, {2}", u.Name, u.Age, u.Desc));
        }
    }

    private static IEnumerable GetMockResults()
    {
        for (int i = 0; i < 20; i++)
        {
            MyEntity r = new MyEntity();
            r.Name = "name " + i;
            r.Age = 30 + i;
            r.Desc = "desc " + i;
            yield return r;
        }
    }
}

The only intrusion here is the explicit use of MockContext. In the production code that is to be tested, you can’t just go inserting MockContext where you would have used the SqlMetal generated context. You need to use a class factory that will allow you to provide the MockContext on demand in a unit test, but dispense a true LINQ to SQL context when in production. That way, all client code will just use mock data without knowing it.

Here’s the pattern that I generally follow. I got it from the Java community, but I can’t remember where:

class DbContextClassFactory
{
    class Environment
    {
        private static bool inUnitTest = false;

        public static bool InUnitTest
        {
            get { return Environment.inUnitTest; }
            set { Environment.inUnitTest = value; }
        }
        private static DataContext objectToDispense = null;

        public static DataContext ObjectToDispense
        {
            get { return Environment.objectToDispense; }
            set { Environment.objectToDispense = value; }
        }
    }

    public object GetDB()
    {
        if (Environment.InUnitTest)
            return Environment.ObjectToDispense;
        return new TheRealContext() as DataContext;
    }
}

Now you can create your query like this:

DbContextClassFactory.Environment.ObjectToDispense = new MockContext(GetMockResults());
var q = from u in DbContextClassFactory.GetDB() where ...

And your client code will use the MockContext if there is one, otherwise it will use a LINQ to SQL context to talk to the real database. Perhaps we should call this Mockeries rather than Mock Queries. What do you think?

Ubuntist deviant atones for sins

Some time back I wrote  a quote of the day: There is no greater joy than soaring high on the wings of your dreams, except maybe the joy of watching a dreamer who has nowhere to land but in the ocean of reality. For a moment I though the quote was apropos for Alec Clew’s announcement of his apostasy, but after a moment’s reflection I realize that it’s not.

Alec wrote the other day that, due to driver problems, he was thinking that he may have to depart the sunlit pastures of Gnu/Linux to return to the dreary halls of Windows XP. If you’ve noticed any of the censure I’ve directed towards Alec’s perverse habits (disgusting admissions of Ubuntism and flagrantly exhibitionist open-sourcism) over the last year, then you might think that there would be a spiteful little gleam in my eye. But I have admit I’m saddened. We are nearly at a point where we can perform painless .NET development entirely within a Gnu/Linux environment. It would be a sad thing if that were not possible because of hardware support shortcomings, rather than the quality of the toolset (which should be the only deciding factor).

GroupJoins in LINQ

OWL defines two types of property: DatatypeProperty and ObjectProperty. An object property links instances from two Classes, just like a reference in .NET between two objects. In OWL you define it like this:

<owl:ObjectProperty rdf:ID=”isOnAlbum”>
  <rdfs:domain rdf:resource=”#Track”/>
  <rdfs:range rdf:resource=”#Album”/>
</owl:ObjectProperty>

A DatatypeProperty is similar to a .NET property that stores some kind of primitive type like a string or an int. In OWL it looks like this:

<owl:DatatypeProperty rdf:ID=”fileLocation”>
  <rdfs:domain rdf:resource=”#Track” />   
  <rdfs:range  rdf:resource=”&xsd;string”/>
</owl:DatatypeProperty>

The format is very much the same, but the task of querying for primitive types in LINQ and SPARQL is easy compared to performing a one to many query like a SQL Join. So far, I have confined my efforts to DatatypeProperties, and tried not to think about ObjectProperties too much. But the time of reckoning has come – I’ve not got much else left to do on LinqToRdf except ObjectProperties.

Here’s the kind of LINQ join I plan to implement:

[TestMethod]
public void TestJoin()
{
    TestContext db = new TestContext(CreateSparqlTripleStore());
    var q = from a in db.Album 
            join t in db.Track on a.Name equals t.AlbumName into tracks
            select new Album{Name = a.Name, Tracks = tracks};
    foreach(var album in q){
        Console.WriteLine(album.Name);
        foreach (Track track in album.Tracks)
        {
            Console.WriteLine(track.Title);
        }
    }
}

This uses a GroupJoin to let me collect matching tracks and store them in a temporary variable called tracks. I then insert the tracks into the Tracks property on the album I’m newing up in the projection. I need to come up with a SPARQL equivalent syntax, and convert the expression passed for the join into that. SPARQL is a graph based query language, so I am going to be converting my requests into the usual SPARQL triple format, and then using the details from the NewExpression on the query to work out where to put the data when I get it back.

With the non-join queries I have been testing my query provider on, I have observed that for each syntactical component of the query I was passed an Expression tree, representing its contents. With a GroupJoin, you get one, and it contains everything you need to perform the query. My first quandary is over the process of converting this new expression structure into a format that my existing framework can understand. Below is a snapshot of the expression tree created for the join I showed above.

GroupJoin Expression contents

There are five parameters in the expression:

  1. The query object on the Album. That’s the “a in db.Album” part.
  2. The query object on the Track. The “t in db.Track” part.
  3. A lambda function from an album to its Name.
  4. A lambda function from a track to its AlbumName.
  5. A projection creating a new Album, and assigning the tracks collected to the Tracks collection on the newly created Album.

Parameters 1 & 2 are LinqToRdf queries that don’t need to be parsed and converted. I can’t just ask them to render a query for me, since they don’t have any information of value to offer me other than the OriginalType that they were created with. They have received no expressions filtering the kind of data that they return, and they’ll never have their results enumerated. These query objects are just a kind of clue for the GroupJoin about how to compose the query. They can tell it where the data that it’s looking for is to be found.

Here’s how I would guess the SPARQL query would look:

SELECT ?Name ?Title ?GenreName <snip> 
WHERE {
    _:a a a:Album .
    _:t a a:Track .
    _:a a:name ?Name.
    _:t a:albumName ?Name .
    OPTIONAL {_:t a: ?Title}
    OPTIONAL {_:t a: ?GenreName}
    <snip>
}

We can get the names for blank nodes _:a and _:t from the parameter collections of the GroupJoins parameters 3 and 4 respectively. We know that we will be equating ?Name on _:a and ?Name on _:t since those are the lambda functions provided and that’s the format of the join. The rest of the properties are included in optional sections so that if they are not present it won’t stop the details of the OWL instance coming back. By using

    _:a a:name ?Name.
    _:t a:albumName ?Name .

We achieve the same as equality, since two things that are equal to the same are equal to each other. That restricts the tracks to those that are part of an album at the same time.

I’m not sure yet what I will do about the projection, since there is an intermediate task that needs to be performed: to insert the temporary variable ‘tracks’ into the Album object after it has been instantiated. More on that once I’ve found out more.

Wireless Power Transmission

I spent years bemoaning the fact that the laws of physics didn’t allow the wireless transmission of power. Now it seems that I bemoaned prematurely. Researchers at MIT have a found a way to use inductance to power a 60W (think similar power rating to a laptop) lightbulb from a distance of up to 2 metres.

I  know it doesn’t sound like much, but as I look at my desk I can’t help thinking that a short range power transmitter would help. I’m sure it beats Quartz crystals as a source of magic moonbeams as well.

cables

Perils of Agile development – the outsourcee’s perspective

Alex Deva has recently written a very persuasive article on the frustrations of Agile development as seen from the far end of an outsourcing agreement. He runs a company in Romania – Indigenous Development – and has past experience of many Agile projects.

I couldn’t agree with his observations more. The problems he observes are problems that arise in on-shored and near-shored development models as well. They are inherent weaknesses of Agile. I think he stated them very clearly though.

Unlike Alex, I think what is required is not a return to the classic waterfall model. After all, what Agile sought to overturn really was just as bad. Instead, I think that what we need is a more formal version of Agile  with a period of up-front intense requirements analysis and high-level architecture. In other words we need to merge the benefits of both methodologies, throwing out any practices that will upset the balance of power within the project team.

Easily Bored?

Darren Neimke posted some interesting thoughts today about the way developers lose their drive on a project, and how it’s reflected in SCRUM meetings. He thought that it might be due to the SCRUM meetings themselves. Daniel Crowley-Wilson has another idea – the developers are just bored.

Developers relish challenges and opportunities to do new things, and solve novel problems. As Daniel says, about midway through a project, there is little novelty in the problems left to be solved. At the end there is just the soul destroying finishing touches, which we all know have to be done, but which we hate doing.

I think that ‘good’ developers (Daniel’s phrase) are a particular breed. They are stimulus hungry people. They tend to quickly become immune to the initial piquancy of stimuli, entertainments or whatever interests them this week. They are not likely to remain interested in a domain or technology for long.

Evidence of this trait can be seen by the amount of staff turnover that most software vendors suffer, or the amount of technological churn that the developers tend to create. Those are the negatives – there’s also positives, like the rampant pace of forward progress. Developers can (given practice & solitude) sustain a high level of attention on a topic for long periods of time. I think this just exacerbates the problem of their easy boredom in the long run.

Because of the two characteristics of easy boredom and manic singlemindedness, Darren’s solution will probably not solve the problem either – the problem is that they require fresh inputs. Both in the job and in the SCRUM meetings. Perhaps your best bet, Darren, is to periodically change the format of the SCRUM meetings, and mix up the teams if you can.

Here’s a simple test to see whether a team member falls into this category – ask them some of the following:

  • how many hobbies have they had
  • how often do they change their desktop backgrounds
  • how frequently do they change jobs
  • how many projects do they have on the go, or up their sleeves
  • how many ideas for killer apps have they had (and not followed up)

Designing a LINQ Query Provider

The process of creating a LINQ query provider is reasonably straightforward. Had it been documented earlier, there would have doubtless been dozens of providers written by now. Here’s the broad outline of what you have to do.

  1. Find the best API to talk to your target data store.
  2. Create a factory or context object to build your queries.
  3. Create a class for the query object(s).
  4. Choose between IQueryable<T> and IOrderedQueryable<T>.
  5. Implement this interface on the query class.
  6. Decide how to present queries to the data store.
  7. Create an Expression Parser class.
  8. Create a type converter.
  9. Create a place to store the LINQ expressions.
  10. Wrap the connecting to and querying of the data store.
  11. Create a result deserialiser.
  12. Create a result cache.
  13. Return the results to the caller.

What It Means

These steps provide you with a high-level guide to the problems you have to solve when creating a query provider for the first time. In the sections below I’ve tried to expand on how you will solve the problem. In many cases I’ve explained from the viewpoint I took when implementing LINQ to RDF. Specifically, that means my problem was to create a query provider that supported a rich textual query language communicated via an SDK, and retrieved results in a format that needed subsequent conversion back into .NET objects.

Find the best API to talk to your target data store.

Normally there is going to be some kind of API for you to request data from your data store. The main reason for creating a LINQ query provider is that the API reflects the underlying technology to much, and you want a more full encapsulation of the technology. For instance, standard APIs in the Semantic web space deal with triples and URIs. When you’re an object oriented developer, you want to be dealing with objects not triples. That almost definitely means that there will be some kind of conversion process needed to deal with the entities of the underlying data store. In many cases there will be several APIs to choose between, and the choice you make will probably be due to performance or ease of interfacing with LINQ. If there is no overall winner, then prepare to provide multiple query types for all the ways you want to talk to the data store. :-)

Create a factory or context object to build your queries.

This class will perform various duties for you to help you keep track of the objects you’ve retrieved, and to write them back to the data store (assuming you choose to provide round-trip persistence). this class is equivalent to the Context class in LINQ to SQL. This class can provide you with an abstract class factory to perform the other tasks, like creating type converters, expression translators, connections, command objects etc. It doesn’t have to be very complex, but it IS useful to have around.

In the case of LinqToRdf, I pass the class factory a structure that tells it where the triple store is located (local or remote, in-memory or persistent) and what query language to use to to query it.

Create a class for the query object(s).

This class is the brains of the operation, and is where the bulk of your work will be.

This is the first main step in the process of creating a query provider. You will have to implement one of the standard LINQ query interfaces on it, and either perform the query from this class, or use it to coordinate those components that will do the querying.

LINQ talks to this query class directly, via the CreateQuery method, so this is the class that will have to implement the IQueryable or IOrderedQueryable interface to allow LINQ to pass in the expression trees. Each grammatical component of the query is passed into CreateQuery in turn, and you can store that somewhere for later processing.

Choose between IQueryable<T> and IOrderedQueryable<T>.

This is a simple choice. Do you want to be able to order the results that you will be passing back? If so use IOrderedQueryable, and you will then be able to write queries using the orderby keyword. Declare your query class to implement the chosen interface.

Implement this interface on the query class.

Now you’ve decided which interface to use, you have to implement this interface on the query class  from point 3. Most of the work is in the CreateQuery and GetEnumerator methods.

CreateQuery gets called once for each of the major components of the query. So for a query like this:

var q = (from t in qry
    where t.Year == "2006" &&
    t.GenreName == "History 5 | Fall 2006 | UC Berkeley" 
    orderby t.FileLocation
    select new {t.Title, t.FileLocation}).Skip(10).Take(5);

Your query class will get called five times. Once each for the extension methods that are doing the work behind the scenes: Where, OrderBy, Select, Skip and Take. If you’re not aware of the use of Extension methods in the design of LINQ, go over to the LINQ project site on Microsoft and peruse the documents on the Standard Query Operators. The integrated part of LINQ is a kind of syntactic sugar that masks the use of extension methods to make successive calls on an object in a way which is more attractive than plain static calls.

My initial attempt at handling the expressions passed in through CreateQuery was to treat the whole process like a Recursive Descent compiler. Later on I found that to optimize the queries a little, I needed to wait till I had all of the expressions before I started processing them. The reason I did this is that I needed to know what parameters were going to be used in the projection (The Select part) before I could generate the body of the graph specification that is mostly based on the where expression.

Decide how to present queries to the data store.

Does the API use a textual query language, a query API or its own Expression tree system? This will determine what you do with the expressions that get sent to you by LINQ. If it is a textual query language, then you will need to produce some kind of text from the expression trees in the syntax supported by the data store (like SPARQL or SQL). If it is an API, then you will need to interpret the expression trees and convert them into API calls on the data store. Lastly, if the data store has it’s own expression tree system, then you need to create a tree out of the LINQ expression tree, that the data store will be able to convert or interpret on its own (Like NHibernate).

SPARQL is a textual query language so my job was to produce SPARQL from a set of expression trees. Yours may be to drive an API, in which case you will have to work out how to invoke the methods on your API appropriately in response to the nodes of the expression tree.

Create an Expression interpreter class.

I found it easier to break off various responsibilities into separate classes. I did this for filter clause generation, type conversion, connections, and commands. I described that in my previous post, so I won’t go into much depth here. Most people would call this a Visitor class, although I think in terms of recursive descent (since that’s not patented). I passed down a StringBuilder with each recursive call to the Dispatch method on the expression translator. The interpreter inserts textual representations of the properties you reference in the query, the constant values they are compared against and it appends textual representation of the operators supported by the target query language. If necessary this is where you will use a type converter class to convert the format of any literals in your expressions.

Create a type converter.

I had to create a type converter because there are a few syntactic conventions about use of type names in SPARQL. In addition, DateTime types are represented differently between SPARQL and .NET. You may not have this problem (although I bet you will) and if that’s so, then you can get away with a bit less complexity.

My type converter is just a hash table mapping from .NET primitives to XML Schema data types. In addition I made use of some custom attributes to allow me to add extra information about how the types should be handled. here’s what the look up table works with:

public enum XsdtPrimitiveDataType : int
{
    [Xsdt(true, "string")]
    XsdtString,
    [Xsdt(false, "boolean")]
    XsdtBoolean,
    [Xsdt(false, "short")]
    XsdtShort,
    [Xsdt(false, "int")]
    XsdtInt,

The XsdtAttribute is very simple, but provides a means, if I need it, to add more sophistication at a later date:

[AttributeUsage(AttributeTargets.Field)]
public class XsdtAttribute : Attribute
{
    public XsdtAttribute(bool isQuoted, string name)
    {
        this.isQuoted = isQuoted;
        this.name = name;
    }

isQuoted allows me to tell the type converter whether to wrap a piece of data in double quotes, and the name parameter indicates what the type name is in the XML Schema data types specification. Your types will be different, but the principle will be the same, unless you are dealing directly with .NET types.

I set up the lookup table like this:

public XsdtTypeConverter()
{
    typeLookup.Add(typeof(string), XsdtPrimitiveDataType.XsdtString);
    typeLookup.Add(typeof(Char), XsdtPrimitiveDataType.XsdtString);
    typeLookup.Add(typeof(Boolean), XsdtPrimitiveDataType.XsdtBoolean);
    typeLookup.Add(typeof(Single), XsdtPrimitiveDataType.XsdtFloat);

That is enough for me to be able to do a one-way conversion of literals when creating the query.

Create a place to store the LINQ expressions.

As I mentioned above, you may need to keep the expressions around until all calls into CreateQuery have been made. I used another lookup table to allow me to store them till the call to GetEnumerator.

protected Dictionary<string, MethodCallExpression> expressions;
public IQueryable<S> CreateQuery<S>(Expression expression){
    SparqlQuery<S> newQuery = CloneQueryForNewType<S>();
    MethodCallExpression call = expression as MethodCallExpression;
    if (call != null){
        newQuery.Expressions[call.Method.Name] = call;
    }
    return newQuery;
}

You may prefer to have named variables for each source of expression. I just wanted to have the option to gather everything easily, before I had provided explicit support for it.

Wrap the connecting to and querying of the data store.

This is a matter of choice, but if you wrap the process of connecting and presenting queries to your data store inside of a standardized API, then you will find it easier to port your code to new types of data store later on. I found this when I decided that I wanted to support at least 4 different types of connectivity and syntax in LinqToRdf. I also chose to (superficially) emulate the ADO.NET model (Connections, Commands, CommandText etc) there was no real need to do this, I just thought it would be more familiar to those from an ADO.NET background. the emulation is totally skin deep though, there being no need for transactions etc, and with LINQ providing a much neater way to present parameters than ADO.NET will ever have.

When you implement the IQueryable interface, you will find that you have two versions of GetEnumerator, a generic version and an untyped version. Both of these can be served by the same code. I abstracted this into a method called RunQuery.

protected IEnumerator<T> RunQuery()
{
    if (Context.ResultsCache.ContainsKey(GetHashCode().ToString()))
        return (IEnumerator<T>)Context.ResultsCache[GetHashCode()
.ToString()].GetEnumerator(); StringBuilder sb = new StringBuilder(); CreateQuery(sb); IRdfConnection<T> conn = QueryFactory.CreateConnection(this); IRdfCommand<T> cmd = conn.CreateCommand(); cmd.CommandText = sb.ToString(); return cmd.ExecuteQuery(); }

The first thing it does is look to see whether it’s been run before. If it has, then any results will have been stored in the Context object (see point 2) and they can be returned directly.

If there are no cached results, then it passes a string builder into the CreateQuery object that encapsulates the process of creating a textual query for SPARQL. The query class also has a reference to a class called QueryFactory, that was created for it by the Context object. This factory allows it to just ask for a service, and get one that will work for the query type that is being produced. This is the Abstract Factory pattern at work, which is common in ORM systems and others like this.

The IRdfConnection class that this gets from the QueryFactory encapsulates the connection method that will be used to talk to the triple store. The IRdfCommand does the same for the process of asking for the results using the SPARQL communications protocol.

ExecuteQuery does exactly what you would expect. One extra facility that is exploited is the ability of the IRdfCommand to store the results directly in the context so that we can check next time round whether to go to all this trouble.

I wrote my implementation of CreateQuery(sb) to conform fairly closely to the grammar spec of the SPARQL query language. Here’s what it looks like:

private void CreateQuery(StringBuilder sb)
{
    if (Expressions.ContainsKey("Where"))
    {
        // first parse the where expression to get the list 
// of parameters to/from the query.
StringBuilder sbTmp = new StringBuilder(); ParseQuery(Expressions["Where"].Parameters[1], sbTmp); //sbTmp now contains the FILTER clause so save it
// somewhere useful.
FilterClause = sbTmp.ToString(); // now store the parameters where they can be used later on. if (Parser.Parameters != null) queryGraphParameters.AddAll(Parser.Parameters); // we need to add the original type to the prolog to allow
// elements of the where clause to be optimised
namespaceManager.RegisterType(OriginalType); } CreateProlog(sb); CreateDataSetClause(sb); CreateProjection(sb); CreateWhereClause(sb); CreateSolutionModifier(sb); }

I’ve described this in more detail in my previous post, so I’ll not pursue it any further. The point is that this is the hard part of the provider, where you have to make sense of the expressions and convert them into something meaningful. For example the CreateWhereClause looks like this:

private void CreateWhereClause(StringBuilder sb)
{
    string instanceName = GetInstanceName();
    sb.Append("WHERE {\n");
    List<MemberInfo> parameters = new List<MemberInfo>(
queryGraphParameters.Union(projectionParameters)); if (parameters.Count > 0) { sb.AppendFormat("_:{0} ", instanceName); } for (int i = 0; i < parameters.Count; i++) { MemberInfo info = parameters[i]; sb.AppendFormat("{1}{2} ?{3} ", instanceName,
namespaceManager.typeMappings[originalType] + ":",
OwlClassSupertype.GetPropertyUri(originalType,
info.Name, true), info.Name); sb.AppendFormat((i < parameters.Count - 1) ? ";\n" : ".\n"); } if (FilterClause != null && FilterClause.Length > 0) { sb.AppendFormat("FILTER(\n{0}\n)\n", FilterClause); } sb.Append("}\n"); }

 The meaning of most of this is specific to SPARQL and won’t matter to you, but you should take note of how the query in the string builder is getting built up piece by piece, based on the grammar of the target query language.

Create a Result Deserialiser.

Whatever format you get your results back in, one thing is certain. You need to convert those back into .NET objects. SemWeb exposes the SPARQK results set as a set of Bindings between a

public override bool Add(VariableBindings result)
{
    if (originalType == null) throw new ApplicationException
("need a type to create"); object t = Activator.CreateInstance(instanceType); foreach (PropertyInfo pi in instanceType.GetProperties()) { try { string vn = OwlClassSupertype.GetPropertyUri(OriginalType, pi.Name).Split('#')[1]; string vVal = result[pi.Name].ToString(); pi.SetValue(t, Convert.ChangeType(vVal, pi.PropertyType), null); } catch (Exception e) { Console.WriteLine(e); return false; } } DeserialisedObjects.Add(t); return true; }

InstanceType is the type defined in the projection provided by the Select expression. Luckily LINQ will have created this type for you. You can pass the type (as a generic type parameter) to the deserialiser. the process is quite simple. In LinqToRdf, the following steps are performed:

  1. create an instance of the projected type (or the original type if using an identity projection)
  2. for each public property on the projected type
    1. Get the matching property from the original type (which has the OwlAttributes on each property)
    2. Lookup the RDFS property name used for the property we’re attempting to fill
    3. Lookup the value for that property from the result set
    4. Assign it to the newly created instance
  3. Add the instance to the DeserialisedObjects collection

The exact format your results come back in will be different, but again the principlple remains the same – create the result object using the Activator, fill each of its public properties with values from the result set. Repeat until all results have been converted to .NET objects.

Create a Result Cache.

One advantage of being able to intercept calls to GetEnumerator is that you have the option to cache the results of the query, or to cache the intermediate query strings you used to get them. This is one of the great features of LINQ (and ORM object based queries generally).

In the case of Semantic web applications we don’t necessarily expect the data in the store to be changing frequently, so I have opted to store the .NET objects returned from the previous query (if there is one).  I suspect that I will opt to unmake this decision, since in the case of active data stores there is no guarantee that the results will remain consistent. It is still a major time saving to be able to run the query using the query string generated the first time round. In the case of LINQ to RDF using SPARQL this corresponds to around 67ms to generate the query. Admittedly the query including connection processing and deserialisation takes a further 500ms for a small database, but there are further optimizations that can be added at a later date.

Return the Results to the Caller.

This is the last stage. Just get the results that you stored in the Context and return an enumerator from the collection. If you have the luxury to be able to use cursors or some other kind of incremental retrieval from the data store, then you will want to consider whether to use a custom iterator to deserialise objects on the fly.

LinqToRdf – Designing a Query Provider

When I started implementing the SPARQL support in LINQ to RDF, I decided that I needed to implement as much of the standard query operators as possible. SPARQL is a very rich query language that bears a passing syntactical resemblance to SQL. It didn’t seem unreasonable to expect most of the operators of LINQ to SQL to be usable with SPARQL. With this post I thought I’d pass on a few design notes that I have gathered during the work to date on the SPARQL query provider.

The different components of a LINQ query get converted into successive calls to your query class. My class is called SparqlQuery<T>. If you had a query like this:

[TestMethod]
public void SparqlQueryOrdered()
{
    string urlToRemoteSparqlEndpoint = @"http://someUri";
    TripleStore ts = new TripleStore();
    ts.EndpointUri = urlToRemoteSparqlEndpoint;
    ts.QueryType = QueryType.RemoteSparqlStore;
    IRdfQuery<Track> qry = new RDF(ts).ForType<Track>(); 
    var q = from t in qry
        where t.Year == 2006 &&
        t.GenreName == "History 5 | Fall 2006 | UC Berkeley" 
        orderby t.FileLocation
        select new {t.Title, t.FileLocation};
    foreach(var track in q){
        Trace.WriteLine(track.Title + ": " + track.FileLocation);
    }        
}

This would roughly equate to the following code, using the extension method syntax:

[TestMethod]
public void SparqlQueryOrdered()
{
    ParameterExpression t;
    string urlToRemoteSparqlEndpoint = http://someUri;
    TripleStore ts = new TripleStore();
    ts.EndpointUri = urlToRemoteSparqlEndpoint;
    ts.QueryType = QueryType.RemoteSparqlStore;
    var q = new RDF(ts).ForType<Track>()
        .Where<Track>(/*create expression tree*/)
        .OrderBy<Track, string>(/*create  expression tree*/)
        .Select(/*create  expression tree*/;
    foreach (var track in q)
    {
        Trace.WriteLine(track.Title + ": " + track.FileLocation);
    }
}

The bold red method calls are the succession of calls to the query’s CreateQuery method. That might not be immediately obvious from looking at the code. In fact it’s downright unobvious! There’s compiler magic going on in this, that you don’t see. Anyway, what happens is that you end up getting a succession of calls into your IQueryable<T>.CreateQuery() method. And that’s what we are mostly concerned about when creating a query provider.

The last I blogged about the CreateQuery method I gave a method with a switch statement that identified the origin of the call (i.e. Where, OrderBy, Select or whatever) and dispatched the call off to be immediately processed. I now realise that that is not the best way to do it. If I try to create my SPARQL query in one pass, I will not have much of a chance to perform optimization or disambiguation. If I generate the projection before I know what fields were important, I would probably end up having to get everything back and filter on receipt of all the data. I think Bart De Smet was faced with that problem with LINQ to LDAP (LDAP doesn’t support projections) so he had to get everything back. SPARQL does support projections, and that means I can’t generate the SPARQL query string till after I know what to get back from the Select call.

My solution to this is to keep all the calls into the CreateQuery in a Hashtable so that I can use them all together in the call to GetEnumerator. That gives me the chance to do any amount of analysis on the expression trees I’ve got stored, before I convert them into a SPARQL query. The CreateQuery method now looks like this:

protected Dictionary<string, MethodCallExpression> expressions;
public IQueryable<S> CreateQuery<S>(Expression expression)
{
    SparqlQuery<S> newQuery = CloneQueryForNewType<S>();

    MethodCallExpression call = expression as MethodCallExpression;
    if (call != null)
    {
        Expressions[call.Method.Name] = call;
    }
    return newQuery;
}

This approach helps because it makes it much simpler to start adding the other query operators.

I also been doing a fair bit of tidying up as I go along. My GetEnumerator method now reflects the major grammatical components of the SPARQL spec for SELECT queries.

private void CreateQuery(StringBuilder sb)
{
    if(Expressions.ContainsKey("Where"))
    {
        // first parse the where expression to get the list of parameters to/from the query.
        StringBuilder sbTmp = new StringBuilder();
        ParseQuery(Expressions["Where"].Parameters[1], sbTmp);
        //sbTmp now contains the FILTER clause so save it somewhere useful.
        Query = sbTmp.ToString();
        // now store the parameters where they can be used later on.
        queryGraphParameters.AddAll(Parser.Parameters);
    }
    CreateProlog(sb);
    CreateDataSetClause(sb);
    CreateProjection(sb);
    CreateWhereClause(sb);
    CreateSolutionModifier(sb);
}

The If clause checks whether the query had a where clause. If it did, it parses it, creating the FILTER expression, and in the process gathering some valuable information about what members from T were referenced in the where clause. This information is useful for other tasks, so it gets done in advance of creating the Where clause.

LinqToRdf – Progress Update 2007-06-05

I’ve been given a week by work to try to make some progress on the LINQ to RDF query provider, and I’m glad to say that the query generation phase is now pretty much complete for SPARQL. It’s amazing what a difference a full day can make to your progress, compared to trying to get as much done as I can when I’m on the train.

Last week when I blogged, I had the rough outlines of a SPARQL query, but it was missing quite a bit. There were also a few bits that were just plain wrong, such as commas separating SELECT parameters. That’s been corrected now. The properties in the GraphPattern are also restricted to those that are mentioned in the FILTER clause, or the projection.

I’ve also added support for the OrderBy, Take and Skip operators, which correspond to the “ORDER BY”, “LIMIT” and “OFFSET” clauses in SPARQL. The unit test I’m working with is looking pretty overweight now:

[TestMethod]
public void SparqlQueryWithTheLot()
{
    string urlToRemoteSparqlEndpoint = @"http://someUri";
    TripleStore ts = new TripleStore();
    ts.EndpointUri = urlToRemoteSparqlEndpoint;
    ts.QueryType = QueryType.RemoteSparqlStore;
    IRdfQuery<Track> qry = new RDF(ts).ForType<Track>(); 
    var q = (from t in qry
        where t.Year == 2006 &&
        t.GenreName == "History 5 | Fall 2006 | UC Berkeley" 
        orderby t.FileLocation
        select new {t.Title, t.FileLocation}).Skip(10).Take(5);
    foreach(var track in q){
        Trace.WriteLine(track.Title + ": " + track.FileLocation);
    }        
}

Here’s a sample of the query string that gets produced for it:

@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix xsdt: <http://www.w3.org/2001/XMLSchema#> .
@prefix fn: <http://www.w3.org/2005/xpath-functions#>  .
@prefix a: <http://aabs.purl.org/ontologies/2007/04/music#> .

SELECT ?FileLocation ?Title 
WHERE {
?t a:year ?Year .
?t a:genreName ?GenreName .
?t a:fileLocation ?FileLocation .
?t a:title ?Title .
FILTER {
((?Year)=(2006^^xsdt:int))&&((?GenreName)=("History 5 | Fall 2006 | UC Berkeley"^^xsdt:string))
}
}
ORDER BY ?FileLocation
LIMIT 5
OFFSET 10

Which is almost exactly what we want. I’m thinking it’s about time to set up some kind of SPARQL server to test the queries for real. We also have to check whether the ObjectDeserialisationSink is capable of deserialising results from a SPARQL query as well as an RSQuary query.