NHibernate: count(…) will return a long, even if it is 0

by Oliver Thu, May 17 2012 12:48

Today, I was doing some HQL with NHibernate trying to retrieve some object count from the database. Running the following piece of code, unfortunately, would throw an exception:

image

System.ArgumentException : The value "0" is not of type "System.Int32" and cannot be used in this generic collection.
Parameter name: value

This was quite confusing for me and I tried a few different things which all did not work. Then I went to debug this line and it turns out that the “0” we’re getting back here is of type long! So the correct version of the above code reads:

image

Easy, once you know :-)

Alternatively, with newer versions of NHibernate ( > 3.0 but I’m not sure exactly) you can use QueryOver and ToRowCountQuery to get an int count:

image

ToRowCountInt64Query() on the other hand would return a long.

Happy coding!

Tags:

A jQuery based tooltip solution for a large web application

by Oliver Tue, March 13 2012 01:37

Finally, with an update we rolled out last week, (almost) all tooltips on Camping.Info look and behave similar, differing mostly in positioning and size, but not in the general look and feel. We chose the jQuery Tools Tooltip as the base for our own solution and it got us pretty far, but there were some pitfalls and scenarios that we needed to handle ourselves. This post is about what limitations we experienced and how we dealt with them.

The original

As you can read in the jQuery Tools Tooltip documentation, the tooltip plugin is highly configurable. It can take different elements as the tooltip for any given trigger:

  • the value of title attribute of the trigger element
  • the html element immediately following the trigger
  • the html element immediately following the first parent of the trigger
  • an arbitrary html element on the page.

You can also position the tooltip pretty much wherever you want relatively to the trigger:

jQuery Tools Tooltip Positioning

Our adaptations

Another way to chose the tooltip

We found one more useful way to define the tooltip for a trigger element: if the trigger is e.g. a table cell in an html table and you don’t want to specify a static tooltip for some or all table cells but a different one for each cell or at least a number of cells, it makes sense to define the tooltip element inside the trigger (the table cell). Since this effect was not achievable extending the jQuery Tools Tooltip plugin we started changing their source:

image

Breaking the tooltip out of some parent container

We also faced some problem properly showing tooltips that needed to “break out” of some bounding box, inside which they were defined (i.e. their html markup). This problem e.g. occurred inside elements with style position: relative, which we have a few of on Camping.Info. Our first attempt was to clone the tooltip element and show the clone instead of the original. This worked in almost all cases – until we tried to attach some more behavior to elements inside the tooltip. The behavior, e.g. some click event handler that we expected to fire when clicking on some element inside the tooltip, wouldn’t execute, since we were working with the clone! So we decided to simply move the tooltip up in the DOM tree for the time it is being shown, more precisely just beneath the form tag that we have on all our pages. We create a placeholder at the place where we removed the tooltip to reinsert it again once it’s being hidden. The code we added to the show() method looks like this:

image

… and here’s the counterpart in hide():

image

Now, this works quite well everywhere, independent of the position of the tooltip in the DOM tree.

Global tooltip configuration

Using inline static configuration

One feature we quickly missed was some kind of static tooltip configuration without calling  $(...).tooltip({ settings: ... }) for every single tooltip we wanted to create or hook up, respectively. What we came up with is to use the HTML5 data attributes to define any specific configuration statically inside the trigger element’s html markup. Thus, we need to call the tooltip initialization code only once for the whole page. The configuration now looks like this:

image

We use specific prefixes with the data attributes to make them easier to understand, e.g. data-tt-position for an attribute that is used for tooltips and jq-tt-trigger for a class that is used by some jQuery code for tooltips.

To process this kind of static configuration we need some custom code that will, at some point, call the original (well, modified by now) plugin code. Unfortunately, the jQuery Tools Tooltip plugin was not designed to allow runtime configuration of the tooltip to show, but we found a way using the onBeforeShow and onHide event handlers. The basic idea is to change the global Tooltip configuration during the first method so that the tooltip we will be showing will be configured correctly, and to reset the global configuration once the tooltip has been hidden again. To achieve this, we iterate over all configuration properties that the jQuery Tools Tooltip plugin supports and search for the respective data attributes on the currently processes trigger element. One example would be the position property: to replace the default value provided by the plugin we look for an attribute that’s called data-tt-position and use its value to temporarily overwrite the default value during the onBeforeShow event handler.

Using global profiles

Once we had the static configuration working and started to replace all of those clumsy and overly complicated AjaxControlToolkit HoverMenuExtenders, it quickly turned out that we were copy’n’pasting the same configuration in a thousand places. This was not only ugly and violated the DRY principle, it also lead to some unnecessarily bloated html. As a solution to this maintenance nightmare we came up with profiles that comprise a set of configuration options that would else be repeated over and over again:

image

Now, they lead to some really clean html markup:

image

The only change from using the inline static configuration is to use the profile’s properties – everything else stays the same!

Conclusion

The jQuery Tools Tooltip plugin is a nice, small and highly configurable tool for easy tooltip creation and usage. In a larger web application there a few shortcomings that we’ve addressed here and which we’ve provided working solutions for. We hope to release those changes soon in its own project on our GitHub account.

Happy coding!

Tags:

jQuery | Web Applikationen | Software development | WEB 2.0 | Usability | Design

Updating the Sass gem to a new alpha version from the GitHub source

by Oliver Sat, February 18 2012 23:52

We use SASS for more productive CSS and the Ruby gem Sass to automatically convert our development .scss files into valid .css files.

Recently, an important bug fix appeared in the project’s master branch on GitHub and we wanted to update our local environments to use that new version for the translation from SASS to CSS.

This post is about how to do just that.

What we need

Of course, we need the project source from GitHub. You can either download a zip file and unpack it to a local folder or clone the repo (git clone "https://github.com/nex3/sass.git" "c:/projects/sass").

Now we need a Ruby command line. There’s a shortcut that’s already installed called “Start Command Prompt with Ruby” but running it returns an error:

'C:\Program' is not recognized as an internal or external command, operable program or batch file.

You need to fix the command used in that shortcut: in the Windows start menu right-click on the above mentioned entry, choose Properties and add double quotes to the last argument so that the command reads:

C:\Windows\System32\cmd.exe /E:ON /K "C:\Program Files (x86)\Ruby192\bin\setrbvars.bat"

Now start the command as Administrator and it returns on the first line:

ruby 1.9.2p290 (2011-07-09) [i386-mingw32]

Compile the source and install the new gem

From the command line we can now execute Ruby programs, e.g. gem. Navigate to the Sass source code directory, build the gem and then update the already installed version with the new one from the local gem file. Finally, install a new gem called fssm which seems to be needed by this new version but forgotten to be added to the sass.gemspec file:

cd c:\Projects\sass

gem build sass.gemspec

gem update sass -–prerelease

gem install fssm

This should output something like:

NOTE: Gem::Specification#has_rdoc= is deprecated with no replacement. It will be removed on or after 2011-10-01.
Gem::Specification#has_rdoc= called from sass.gemspec:31
.
  Successfully built RubyGem
  Name: sass
  Version: 3.2.0.alpha.0
  File: sass-3.2.0.alpha.0.gem

and

Updating installed gems
Updating sass
Successfully installed sass-3.2.0.alpha.0
Gems updated: sass
Installing ri documentation for sass-3.2.0.alpha.0...
Installing RDoc documentation for sass-3.2.0.alpha.0...

Fetching: fssm-0.2.8.1.gem (100%)
Successfully installed fssm-0.2.8.1
1 gem installed
Installing ri documentation for fssm-0.2.8.1...
Installing RDoc documentation for fssm-0.2.8.1...

That’s it, you’re ready to use the newest version of Sass!

Happy coding!

Tags:

Learning how to program and teaching someone else how to program

by Oliver Thu, December 29 2011 03:02

I will be taking on teaching my brother-in-law how to program soon and while thinking about how to go about it I thought of putting together some essential information in one place for him and myself to check while we move along.

My first suggestions are:

  1. Get to know your keyboard – really well. For everything you do on your PC, find shortcuts and use them. Treat your mouse as poison to your programming skills. It will keep you from being fast on your keyboard which will keep you from coding quickly which in turn will keep you from learning quickly. I’ve put this at the top of the list because it is THAT important.
  2. Use git and specifically GitHub to version your code. It’s free and offers great ways to browse and share code, to do code reviews and a bunch of other stuff. On your windows machine, use GitExtensions to work with GIT.
  3. Setup your own blog. From the very beginning, write about what you’ve learned. Trying to put your newly acquired knowledge into words and maybe images is one of the best ways to ensure you really understood what you’re doing.
  4. Get involved in stackoverflow.com or something similar. This goes along the same lines as 2. Reading questions and their answers, posting new questions yourself will help just as much as writing about your own code. Check out http://programmers.stackexchange.com/ as well. I contains lot of questions and discussion on ways to become a (better) programmer.
  5. Finally: code, code, code. Use the development tool of your choice and get to know it really well, so that it won’t be in your way once you have a good idea what to write.

Enjoy!

Tags:

Customize and debug your Google+ button

by Oliver Sat, December 03 2011 19:17
image

This week we added a Google +1 button to Camping.Info – well, actually several of them. Adding a button with a static URL is quite straight-forward and well described on Google’s pages (refer here for documentation and the Google+ button configuration tool).

As Google recommends (at the bottom of the page), we chose to put two Google +1 buttons on each of our (important) pages: one in the header to +1 the whole portal and one page/context sensitive button to +1 the specific page.

Dynamic loading

An interesting customization we added was dynamically loading a +1 button when the user changes their location on the search page using AJAX where the browser URL stays the same (although this behavior can now be customized with HTML5!) – there we use the following code snippet to render the +1 button to use the correct (currently searched) URL:

if (window.gapi) {
    gapi.plusone.render(
        'g-plusone-search',
        { size: 'medium', href: $('div#g-plusone-search').data('href') }
    );
}

This code assumes that the div with class “g-plusone-search” contains the attribute “data-href=<URL>” with the URL we wish to +1.

Debugging the Google +1 button – tell me the URL!

To properly test and debug the scenario for the dynamic +1 button, I ‘ve put together a short piece of jQuery code that shows the URL of the Google +1 button currently under the mouse:

// debug tooltip for Google+ buttons which contains the targeted URL
$('div.gp1').live('hover', function () {
    var div = $(this);
    div.attr('title',
            decodeURIComponent(decodeURIComponent(new RegExp("url=[^&]+").exec(div.find('iframe').attr('src'))))
                .substring(4) // cut off "url="
                .replace(/\//g, '/ ').replace(/\/ \/ /, '//')) // add spaces after / but not in //
        .tooltip({ position: "center left" });
});

The call to .tooltip() requires the jquery.tools.tooltip.js to be included on the page but you don’t really need it since without it you will see a normal title popup. The double call to decodeURIComponent was necessary for us since our URL contain special characters that are already encoded and Google encodes them a second time to be a safe parameter in their internally used link. The .replace() call simply inserts some whitespace which we needed for long URLs to fit into our custom tooltip.

Go and have fun

That’s two pieces of code I found useful when integrating Google +1 buttons into our site. Hope you find them useful, too.

Happy Coding!

Tags:

Frustrating development – non-deterministic behavior

by Oliver Thu, November 24 2011 00:39

Generally, when I execute Action A and get result B, then change Action A to A2 receiving a different result R2 and then change Action A2 back to A, I would expect to get result R once again.

Well, today this logic twice failed me during development.

Trying to use the PreApplicationStartMethodAttribute of .NET 4.0

Recently, I was developing a small module to track some performance metrics in our new Orchard based portal marina finder, when I just could not get this wonderful new attribute working. The idea behind it is, that you can decorate any assembly with it and call some custom code from that assembly very early in the Application life time (read more in Phil Haack’s post), e.g. register some HttpModule that I don’t want to register using the application’s web.config file. This is especially important when developing with Orchard because during an update to a new version any change to their original source code would either be lost or would need to be somehow manually reapplied. So it’s preferable not to touch the web.config.

Well, this great attribute simply did not work on my local development application instance. To get the functionality done anyways, I chose to add that module registration to the web.config despite my bad feeling about it. It worked as expected so the next step was to deploy this new feature to our staging system.

That’s where it made “Bang!”. The exception was “Item has already been added”. The offending code looked like this:

image

How was that possible? I registered this event handler exactly once for the Application.BeginRequest event – so I really didn’t grasp how that code could execute more than once for any given request. Wait, there is one scenario where this could happen – if the module has been registered twice! A little debugging led me that exact conclusion, so how could the module be registered twice? Well, obviously on our staging server the registration inside the PreApplicationStartMethod worked just as well as the registration in the web.config – once I removed the module registration from the web.config the module code was called only once.

So why did this not work on my machine? I set up another web site in IIS with – as it turns out, almost – the same, identical application code and it worked just fine, just like on our server. So I grabbed WinMerge (an indispensible tool in my toolbox, by the way), compared the folder hierarchy and found a difference in the web.configs:

image

As weird as it seemed to me that this difference might cause the .dll with my HttpModule not to load as expected – after changing the “debug” attribute to “false” the module would finally load! Heureka! So now, can anybody explain, why? Well, I tried to dig deeper into this problem, but changing the value back to “true” would not change a thing!!! Now I was completely baffled. Well, I still am. That’s what I was talking about in the introduction. It works as expected – but somehow I’m not happy with how it did.

An HttpModule and a database connection error

The second thing happened on the way of fixing the above error. When I started fixing the “Item has already been added” exception by adding some debugging code, my local application instance would suddenly return a database connectivity error most ASP.NET know all too well:

image

I spent more than half an hour trying to find the cause – checked my network connection (as our dev DB sits on one of our servers), tried to log into the DB using SSMS (which worked, surprisingly), got a copy of the DB and threw it into my local SQL server instance trying to connect to the DB there – all to no avail. Finally it hit me. “Just revert the new code you wrote, maybe it’s that!” Well, as improbable as that seemed, it worked. Trying to find out which line contained the offending piece of code, I reinserted all of what I’d changed before, this time line by line. The error would not reappear! Can you believe it? This feels like some black magic or a really bad joke to me.

Lesson learned

I’m not sure yet. I dare to assume that there might have been a problem with some old cached code/dlls somewhere but it’s a vague assumption. I’m not sure what to make of all of this. Do you, dear reader?

Happy coding!

Tags:

Showing the version number of the currently deployed application

by Oliver Fri, October 07 2011 22:27

Yesterday I just quickly wanted to add the version number of our new Todo management application to the footer of every page. I could have just checked our own blog history or went off to Google or Stackoverflow but I just wanted to do it myself. Simple enough, isn’t it?

To get the assembly of the web application from inside a view, for example, unfortunately this won’t work:

image

It will print out something like  Version: App_Web_xu4dep5e, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null

Well, this is the dynamically compiled dll for just my view – not what I’m looking for.

The following does the trick:

image

This prints  Version: Todo.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.

So now, the only thing left is to get the version number from the assembly. Should be easy, there should be some kind of property named Version, or a method called GetVersion() right? Well, there isn’t:

image

Looking at the AssemblyInfo.cs, I saw that the AssemblyVersion is an attribute on the assembly:

image

So I thought the following code would work, but it didn’t (throws on .First() with System.InvalidOperationException: Sequence contains no elements):

image

In the end, the solution is really short but not quite intuitive. Why is Version a member of the type AssemblyName which you access by calling GetName()? I don’t know.

image

Happy Coding!

Tags:

ToDebugString() – give me some debug info about my object, e.g. Request.Url

by Oliver Fri, September 16 2011 20:06

Lately, I was having trouble debugging certain parts of my code in Visual Studio, and all I wanted to know was the value of some variable at some point in time. Well, I’d use some logging if I could just get at that value easily. But for some objects I don’t really know what I’m looking for or where I should be looking for it. So just give me the values of all the members of that object, will ya? And could you recurse that? But no deeper than 3 levels, alright? Or let’s say… 5?

public static string ToDebugString(this object obj, int maxdepth, int depth=0)
{
    if (obj == null)
        return "null";
 
    if (obj is IConvertible)
        return obj.ToString();
 
    if (depth >= maxdepth)
        return "...";
 
    var sb = new StringBuilder();
 
    if (depth > 0)
        sb.AppendLine();
 
    foreach (var propertyInfo in obj.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
    {
        sb.Append(new string(' ', 2*depth)).Append(propertyInfo.Name).Append(": ");
        try
        {
            var value = propertyInfo.GetValue(obj, new object[0]);
            sb.AppendLine(ToDebugString(value, maxdepth, depth + 1));
        }
        catch (Exception ex)
        {
            sb.AppendLine(string.Format("[{0}]", ex.Message));
        }
    }
 
    // remove newline from end of string
    var newLine = Environment.NewLine;
    if (sb.Length >= newLine.Length)
        sb.Replace(newLine, "", sb.Length - newLine.Length, newLine.Length);
 
    return sb.ToString();
}
With this little helper I can now simply call anyobject.ToDebugString(4 /* maxdepth */) and I get a nicely formatted debug view of that object; e.g. Request.Url.ToDebugString(3) gives me:
AbsolutePath: /logg.aspx
AbsoluteUri: http://localhost:55235/logg.aspx
Authority: localhost:55235
Host: localhost
HostNameType: Dns
IsDefaultPort: False
IsFile: False
IsLoopback: True
IsUnc: False
LocalPath: /logg.aspx
PathAndQuery: /logg.aspx
Port: 55235
Query:
Fragment:
Scheme: http
OriginalString: http://localhost:55235/logg.aspx
DnsSafeHost: localhost
IsAbsoluteUri: True
Segments:
Length: 2
LongLength: 2
Rank: 1
SyncRoot:
Length: 2
LongLength: 2
Rank: 1
SyncRoot: ...
IsReadOnly: False
IsFixedSize: True
IsSynchronized: False
IsReadOnly: False
IsFixedSize: True
IsSynchronized: False
UserEscaped: False
UserInfo:

Nice Smile

Right now this method chokes on indexed properties but once I’ll need it I’ll go and look for a way to include them. It also chokes any exceptions on the way to just get the job done.

Happy coding!

Tags:

.NET | C# | Debugging | Software development | Tips & Tricks | Visual Studio | developer

Unexpected EOF encountered in BCP data-file

by Oliver Thu, September 15 2011 17:05

Today, I tried importing a CSV file like the following into one of our MS SQL Server databases:

Id;Latitude;Longitude
4610;43.7119;-1.0737
5502;49.4297;-1.806
11360;46.9343;-1.8875

I tried it using the following command line:

   1: bcp GeoDataImport in geodata.csv -w -t; -T

but that threw the mentioned error:

“Unexpected EOF encountered in BCP data-file”

cmd> bcp GeoDataImport in geodata.csv -w -t; -T
Starting copy...
SQLState = S1000, NativeError = 0
Error = [Microsoft][SQL Server Native Client 10.0]Unexpected EOF encountered in BCP data-file
0 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.) Total     : 1

I’ve had this problem before and somehow managed to remember that it might have something to do with the encoding of the file. So I opened it with Notepad++ where you can easily check and change the file encoding and found it was ANSI encoded:

image

Well, the UCS-2 Little Endian encoding is what SQL Server expects as default encoding, so I changed the encoding, saved the file and imported it again – with success. UCS-2 might be something you rarely hear about – that’s because it’s been superseded by UTF-16 but in most situations they are pretty much identical (check out http://en.wikipedia.org/wiki/UTF-16/UCS-2 for more info).

That’s all for now – happy coding!

Tags:

MS-SQL Server | developer | Tips & Tricks

Orchard and Lucene: getting started with custom search – problems with booleans

by Oliver Mon, September 12 2011 01:46

Update: I filed a bug in the Orchard issue tracker and it’s already been fixed. Nice work!


We’ve just started to build our own customized search module. The goal is to have checkboxes for all searchable boolean properties of a given ContentPart and search by checking or unchecking them.

In Orchard, one can add contents to the search index using the following code (this is an example for adding a boolean):

   1: public class MyPartHandler : ContentHandler
   2: {
   3:     public MyPartHandler(IRepository<MyPartRecord> repository)
   4:     {
   5:         Filters.Add(StorageFilter.For(repository));
   6:  
   7:         OnIndexing<MyPart>(
   8:             (context, myPart) => context.DocumentIndex
   9:                                      .Add("DogsAllowed", myPart.DogsAllowed == true ? "true" : "false").Store());
  10:     }
  11: }
Now, when a user checks the checkbox for “DogsAllowed” we want to ask the search index for all documents (Lucene term for what I would call an entity) with the DogsAllowed property set to true. The way we would do that is something along the following lines:
   1: ...
   2: var searchBuilder = _indexProvider().CreateSearchBuilder("Search")
   3: searchBuilder.WithField("DogsAllowed", true);
   4: ...

The problem with this is: it gives me zero results! Of course, to get something into the index you have to go and save some document/entity for the OnIndexing handler to run, but I’d done that. Somehow I had the feeling that my search was not doing what it was supposed to…

So I wanted to know more about the index Lucene had generated so far. Searching for lucene index visualizer lead me to Luke, the Lucene index toolbox which I downloaded v 0.9.9.1 of because it was built against Lucene 2.9.1 and in Orchard the Lucene.NET version is only 2.9.2. Maybe a newer version would have also worked but I got what I wanted anyways.

After providing the path to the index files, Luke showed me some interesting stuff, among other things that the boolean was stored as string “True” (mind the upper case!):

image

This behavior is actually no surprise when we look at the source code for the Add(string name, bool value) method, it just calls the Add(string name, string value) method with the bool converted to a string:

   1: public IDocumentIndex Add(string name, bool value) {
   2:     return Add(name, value.ToString());
   3: }
It’s good to know that true.ToString() == “True” btw.

So, now when I search inside Luke using the query DogsAllowed:True I do get a result – but using DogsAllowed:true I don’t! (The syntax for searches is field:value.)

image               image

So now, why does my search (in Orchard) for all documents that have the DogsAllowed property set to true return no results when there obviously is a document in the index with exactly that?

Well, let’s look at the implementation of .WithField():

   1: public ISearchBuilder WithField(string field, bool value) {
   2:     CreatePendingClause();
   3:     _query = new TermQuery(new Term(field, value.ToString().ToLower()));
   4:     return this;
   5: }
When I debugged through the search I saw that all of a sudden we were searching for DogsAllowed==true instead of True which to Lucene are two completely different things (at least in this scenario). Actually, turning on logging for the Lucene.Services namespace, we get some debug logging telling us what the search is currently looking for:
   1: 2011-09-10 00:44:33,026 [6] Lucene.Services.LuceneIndexProvider - Searching: DogsAllowed:true* 

Now I’m not surprised anymore that I’m not getting any results!

This is obviously a bug in Orchard’s Lucene module, but for now I can easily get around it using simply passing the lower case strings to the Add() method myself like this:

   1: OnIndexing<MyPart>(
   2:     (context, myPart) => context.DocumentIndex
   3:                             .Add("DogsAllowed", myPart.DogsAllowed == true ? "true" : "false").Store());

Happy coding!

Tags: ,

Orchard | Web Applikationen