LinqToLfsWorld v1.0 Released!

Just a quick post to say that LinqToLfsWorld 1.0 has been released; you can grab it from the project homepage on codeplex.com.

Whilst the interface hasn’t changed, under the bonnet the expression parsing code has been vastly improved and you can now do a lot more with it, compared to the 0.8 release from the beginning of the month.
For example, with the preview code you couldn’t write a query such as:

var stat = from stats in context.RacerStats
where stats.RacerName == GetRacerName()
select stats;

.. the point here being that the expression parser couldn’t evaluate local expressions, i.e. any expression which didn’t contain a parameter expression from inside the query itself (in the example above, this local expression would be the call to GetRacerName()). Now though, all expressions which can be evaluated before the query is even looked at are evaluated down to a constant value. This means you can call any method or access any property you like from inside the query.

Some of the common selection methods are now supported also; you can directly call Single, SingleOrDefault, First, FirstOrDefault, Last, LastOrDefault and Count on an LfsWorldContext query. You can also call Select,provided the query only selects either a single entity or a list of entities. In other words, you cannot create an anonymous type from these queries. This limitation is trivial however, since you can just convert your results into a list and use plain Linq To Objects to select only the fields you need. The example website included with the download demonstrates this.

This released also fixed a number of bugs which were flagged up from testing the preview version, mainly to do with caching and the expression engine.

There are a couple of issues I’d like to sort out with regards to serialization, which will come out as some sort of ’1.0.1′ release perhaps. Over the next week or so I’m also going to give you a full run down of each type of query you can perform with this library on this very site.

If anyone is using the library and finds any issues with it, please direct them to the issue tracker on the project home page.

Leave the first comment

LinqToLfsWorld v0.8 Preview

After a bit of umming and arrrring I managed to make quite a bit of headway with a project I’ve been mulling over for a while – LinqToLfsWorld. It’s a custom LINQ provider which allows the client to communicate with LfsWorld via its Pubstat web service.

What is that exactly? Live For Speed (LFS) is (primarly) an online racing simulator, and LFSWorld is an online base for checking your racing stats, viewing and comparing hotlaps and watching other races in real time via a neat flash application. Pubstat is it’s webservice which you can query to retrieve information about racers, hosts, teams and hotlaps. You send it a url and it will return either JSON, PHP or XML formatted responses.
Since it’s url based, and it has a fairly simple interface, Ithought it would be a good introduction into finding out what it takesto build a custom LINQ provider. My implementation isn’t great nortotally versatile (yet), but it works and I’m pretty pleased with theproject so far.

The reason the release is tagged as 0.8 Preview is because there’s acouple of issues I’d like to sort out before I give it that ‘release1.0′ milestone; the object documentation (currently there isn’t any)and I’d like to work a bit more on the expression visitor, to make thequeries just a bit more friendly.

So, if you’re interested in having a look, please visit the project page on Codeplex and download the latest release and/or the source code and play aroundwith it. Send me any issues if you want via the issue tracker, and feelfree to contact me with any suggestions or queries relating to theproject.

I’m going to publish a couple more articles over the course of thenext couple of weeks as I improve the library, and to show you a couplemore examples on how to use it.

Leave the first comment

Querystring Element Insertion

One problem I frequently come across is having to redirect to a page using the current query string in the request, but also having to add new parameters. Furthermore, the parameters I want to add might already exist in the querystring, and if you’re redirecting to the same page all hell breaks loose within a few clicks of the link.

The exact problem I’m trying to solve is this: I have one page which gathers parameters from the user for an advanced product search, which then passes the parameters through the querystring to a search results page. This page contains a GridView control that has column headings which also pass some values through the querystring (information about which column to sort on and in what direction – I’ll blog about this another time). When the column is clicked, I still want to keep the information about the search and also the sort criteria. Not all of the parameters will be in the querystring at any given time.

I have to deal with this problem on a few pages, and I need a way to quickly and easily redirect to a url passing the current querystring parameters whilst at the same time injecting one or more new parameters if they don’t currently exist. If they do exist, I might want to re-assign it a new value.
The (hopefully) obvious solution is to work with the querystring while it’s still in the form of a Collection, rather than a string. Unfortunately for us, the Request.Querystring instance during a page is read-only. So how do we go about this?

What I’ve come up with is a pattern for achieving the solution, rather than a handy method or object. It’s quick, painless and flexible, and here’s the code:

Dim newQsColl As New NameValueCollection(HttpContext.Current.Request.QueryString)
newQsColl.Set(sortExpressionParam, sortExpression)
newQsColl.Set(sortDirectionParam, CType(sortDir, Integer))

Dim newQs As String = newQsColl.GlueElements("&")

The last line I’ll talke about in a second. This code snippet allows you to take the current querystring and essentially add more key/value pairs to it. Here I’ve used the ‘Set’ method to create the new key/value pairs; this method will add the new pair if the key doesn’t exist, but will change the key if it doesn’t exist. Exactly the behaviour I was after!
An extra facility I wanted to finish this off was some easy method to glue the elements together in a format I could stick straight back into a hyperlink without any fuss. You could create a special lightweight class to do this, but since I’m using Asp.Net 3.5 I used an extension method. Ideally I’d like to implement the following on any IDictionary (since that interface follows the same key/value element structure), but alas NameValueCollection doesn’t inherit from such an interface.
Nevertheless here’s my extension method, named ‘GlueElements’:

<Extension()> _
Public Function GlueElements(ByVal collection As NameValueCollection, _
ByVal glue As String) As String
  Dim sb As New Text.StringBuilder()
  For Each key In collection.Keys
    sb.Append(String.Format("{0}={1}{2}", key, collection(key), glue))
  Next     

  Dim result As String = sb.ToString()
  If Not String.IsNullOrEmpty(glue) Then
    result = Left(result, result.Length - glue.Length)
  End If     

  Return result
End Function

This method simply loops through the keys in the collection and joins together the keys and values using a specified ‘glue’ string. It then outputs the result, stripping off the last instance of the glue before returning it. If you set the glue string to ‘&’, you end up with a string suitable for inserting straight into a url as a querystring.

Leave the first comment

VB Dynamic Query Library woes

According to my searches on the internet, not many people were having trouble trying to use the Linq Dynamic Query library inside a class library project.

The problem was that with my Asp.Net web project, I wanted to have my middle-tier code inside a class library which would then be referenced by the website (and another planned website later on). This class library would contain (amongst other things) my Linq data context and the Dynamic Query library. However, whenever I added the Dynamic Query library to the project the compiler would start complaining about missing objects.

After much tearing my hair out and research I still couldn’t find the problem so I left it to work on something else. A similar issue arised when I was working on a completely unrelated piece of code, so it wasn’t just attributed to the Linq library in my original problem. The real issue?

VB.Net class library namespaces. When you create a VB.Net class library project, you can specify a default namespace for everything in that library, and so when you are creating something inside a sub-namespace you leave off the default namespace which is already set on the project.

The dynamic library is implemented inside the namespace System.Linq.Dynamic, and so when I added it to my class library project the namespace it was in was actually MyNamespace.System.Linq.Dynamic. This meant that the System namespace now clashed with MyNamespace.System, and the data context which imports the System namespace, and was in MyNamespace, was importing the wrong one. Obviously, this was also happening to anything which imports the System or any sub-namespace of System. Which means essentially that the hellmouth opened and the world was in chaos. This issue doesn’t arise in a normal web project, since you don’t define a default namespace for classes. I haven’t tried this, but I also assume the issue won’t arise in a C# class library project since, while you can specify a default namespace for your classes, the compiler doesn’t anonymously prepend your default namespace name onto the one you’ve explicitely set in the code file.
The solution is simple – dive into the code file for the Linq Dynamic Query library and remove the namespace declaration.

7 comments so far, add yours

LCD HD44780 activities

This blog opener isn’t strictly about coding, but having some time off work recently I decided to do something that, for me, is pretty cool. What could possibly be cooler than displaying car data from my favourite racing simulator Live For Speed on an external LCD device!

The image on the right shows the finished display, showing the car speed, gear and fuel tank level. It’s updated in real-time using the game’s Outgauge system – Outgauge uses network packets to communicate with the world outside the game, and cool applications have been built to control external hardware devices, from real car gauges to full-motion simulators. The whole device is pretty simple, and cost me just shy of £20 for parts. The LCD device is an HD44780-compatible supertwist LCD display (model #N27AZ from Maplin), and then all you really need is a parallel cable and a power source. I’ve powered my device from three 1.5v AA batteries, so for convenience I added an on/off switch. You can also add a potentiometer to the contrast input to the device, but I chose not to since I want it to display at full contrast all the time.

The parallel cable was also a bit of a DIY project in itself. I couldn’t easily find (nor was willing to pay delivery for) a D25 male->male cable, but I did have a D25->C36 cable handy. So, I slaughtered one end of it, cut of the wires I didn’t need and wired a 25-pin plug on the end!

At the moment the device is powered on batteries, but I plan to change this so that it’s powered from a standard hard-disk connector. I’ve found that when configuring the LCD to display data on two lines the contrast dips considerably (which is why in the video below I’m displaying the data on only one line), and it’s been pointed out that this could be the batteries not being able to supply enough current.


Connecting to the LCD The rest of the work is done in software. I used the excellent LFSLib to retrieve the data packets from Live For Speed, and my own custom library to interface with the LCD. There are a couple of methods you can use in .Net to send data through the parallel port, and I used the inpout32.dll method. This Win32 library contains two main functions – one to send data and one to receive data. Once you’ve got the hang of using the parallel port, controlling the LCD unit is a fairly straight-forward affair. You basically send a byte of data representing an instruction, send a high voltage to the ‘enable’ pin (causing the LCD to read and act upon the instruction) then clear the enable pin again. There’s an initialization sequence which you must follow, after which text data is sent by setting the RS pin to ‘high’ (letting it know you’re going to send data) and then sending each character in turn down the data pins (setting the ‘enable’ pin high after every character). The LCD will advance the cursor after every character. You can optionally tell the unit where you want to start the text from, in case you wanted to centre the text on the display.

My device is not without it’s issues (there’s a rant coming up in a future post about the BackgroundWorker object) but it was a fun project to work on, and you should have seen the smile on my face once I got it working! If you know a little bit about electronics and can solder, definitely give some thought to attempting a similar thing. I’ve included some references below which helped me get this up and running. The next thing for me to do is to make an enclosure for it, and put the project to bed.

Here’s the final result!

References:

Leave the first comment