Theory of Relativity

Relativity-formula

Recently whilst putting a .NET web project to bed we had yet more reports from the field of some rendering issues with Internet Explorer 7.  Of course we had tested IE 7 using the compatibility modes present within later versions of IE but seemingly this does not throw up many issues that arise in the ‘real’ browser

I know, I know…., in an ideal world we’d all have the latest and greatest browsers but in the real world companies are not so ‘lithe’ when it comes IT infrastructure.

The issue being reported was that one form displaying an accordion control, which in turn had embedded within it a scrollable div which in turn contained three or four divs as well as a JQGrid was having ‘issues of parentage’… When the main scrollable div was being scrolled all underlying divs were being rendered correctly and scrolling with the content whilst the JQGrid was not moving at all, just merely floating in space and generally getting in the way. After a lot of digging I found the following solution that cured my issues:- The main HTML was defined thus

<div id=”QuestionnaireGridContainer”>
<table id=’QuestionnaireGrid’></table>
</div>

 with the ‘QuestionnaireGrid’ being the location that the javascript JQGrid is rendered into, The issue however seems to lie with the parent div and not the JQGrid itself, what I needed to do was attach a style via the css to the ‘QuestionnaireGridContainer’ div like thus:

#QuestionnaireGridContainer{
    position:relative;
}

This ‘position:relative’ style  in this instance seems to explicitly force all children objects to behave correctly with regard to their location within time and space and now when i scroll my div content all child objects are scrolled exactly as I would expect.

Advertisements

Float Like a Butterfly….Errr

floatlabRecently whilst putting a .NET web project to bed we had some reports from the field of some rendering issues with Internet Explorer 7.  Of course we had tested IE 7 using the compatibility modes present within later versions of IE but seemingly this does not throw up many issues that arise in the ‘real’ browser

I know, I know…., in an ideal world we’d all have the latest and greatest browsers but in the real world companies are not so ‘lithe’ when it comes IT infrastructure.

One such issue being reported was along the following lines:-

Our application was divided into a standard navigation-detail model with the navigation part of the equation being a host of controls displayed within an accordion located to the left hand side of the screen and the detail being displayed to the right hand side of the screen in line horizontally with the accordion. This was achieved through the div hosting the ‘Detail’ section having a ‘float:right’ instruction within the css like so:-

.mainPageContainer{
    display: inline-block;
    float: right;
    height: 75%;
    width: 74%;
}
 
This seemed to work without issue throughout the entire development cycle… We targeted the following browsers:-
 
Internet Explorer 8/9/10 (and 7 in compatibility mode!)
Chrome
Firefox
Opera
Safari
 
All seemed to display without issue, it was left to ‘the real’ Internet Explorer 7 to lower the tone…. Instead of rendering the detail directly to the right of the accordion IE 7 rendered the details BELOW and to the right of the accordion. The fix turned out to be very simple though NOT obvious to me although with hindsight I do kind of understand, the issue was css related  but not with my mainPageContainer, rather the issue was with my accordionContainer which was defined thus:-
 
.accordionContainer{
    height:650px;
    min-width:20%;
    width:25%;
    display:inline-block;
}
 
It is not obvious, to me at least, that in order for any items placed to the right of the accordion to float right ‘properly’ the accordion container itself should be explicitly be made to float left (which it seems to do very well itself without instruction!). Thus I made the following bold changes:-
 
.accordionContainer{
    height:650px;
    min-width:20%;
    width:25%;
    display:inline-block;
    float:left;
}

 Voila, now even Internet Explorer 7 can now correctly render our application,

 

 
 

Displaying Alternative Coloured Images in JQ Grid

RedAmberGreen

Whilst coding up a recent .NET MVC application built heavily using JQGrid I came across a requirement which to be honest I struggled with at first . In short I wanted to, on a column by column basis, colorise the icons that were to be displayed. Now JQGrid supports a icon colorset which seemingly cannot be changed easily so in the end I had to resort to changing the styles. Here is how I achieved this, warts and all….

Firstly of course JQGrid uses the standard set of JQuery Ui Icons to provide its user interface. I say ‘Icons’ but this is of course provided as one image which is broken up into sprites of 16 x 16 pixels, more of that later. So the first step is to download the set of colour icons that you require…. JQueryUI.com provides a standard set of these icons rolled in every colour you can dream so its in fact very easy. The hardest part is arriving at your chosen colours!

I arrived at the following soft representation of the Red, Amber and Green colours :-

  • Red Hex: FF99A3
  • Amber Hex: FFB380
  • Green Hex: 99FFB8

So using these hex values i was able to download my chosen colour schemes using the following url:-

In my instance i downloaded the following files:-

As you can see from the screen grab below the resultant images are in fact compound images containing many 16 x 16 sprites:

FF99A3

In my case I need to use the following icons Bullets and Ticks, as you can see if you examine the image the tick sprite is the fifth sprite across on the tenth line down whilst the bullet is the sixth character on the same line. Given that each character is 16 pixels wide and tall finding the location is relatively easy. The basic formula is (n-1) x16  expressed as a negative where n is the line number or character across.  So in the case of our tick as it is the fifth character across its horizontal location starts at -64 pixels, similarly its vertical location is -144 pixels (9 x 16 expressed as a negative)

We thus need to create some css classes to represent these icons so in my instance I created the following classes:-

.ui-green-tick{
width:16px;
height:16px;
background-image:url(../css/redmond/images/ui-icons_99FFB8_256x240.png)!important;
background-position:-64px -144px
}
.ui-red-tick{
width:16px;
height:16px;
background-image:url(../css/redmond/images/ui-icons_FF99A3_256x240.png)!important;
background-position:-64px -144px
}
.ui-amber-tick{
width:16px;
height:16px;
background-image:url(../css/redmond/images/ui-icons_FFB380_256x240.png)!important;
background-position:-64px -144px
}

.ui-green-bullet{
width:16px;
height:16px;
background-image:url(../css/redmond/images/ui-icons_99FFB8_256x240.png)!important;
background-position:-80px -144px
}
.ui-red-bullet{
width:16px;
height:16px;
background-image:url(../css/redmond/images/ui-icons_FF99A3_256x240.png)!important;
background-position:-80px -144px
}
.ui-amber-bullet{
width:16px;
height:16px;
background-image:url(../css/redmond/images/ui-icons_FFB380_256x240.png)!important;
background-position:-80px -144px
}

Note that each class points to the relevant colour image using the background-image:url property, in order to ensure that our image takes precendence over other images referred to in the JQGrid style sheets I habd to also use the !Important declaration, The sprite location is specified using the background-position: properties using the algorithm discussed above. As you can see we also specify the size of our images. in this instance 16 x 16 pixels.

OK, so believe it or not thats the worst part over with, all that is left now is for you to determine on a row by row and column by column basis which icons are to be displayed and change the relevant classes using javascript I defined the following javascript helper functions, some code has been removed for brevity so they may not be compilable (apologies in advance).

function OnLoadPrimeGridExclusive(grid, actionColumn, theTitle, dataColumn) {

    var iCol = getColumnIndexByName(grid, actionColumn);
    grid.children(“tbody”)
            .children(“tr.jqgrow”)
            .children(“td:nth-child(” + (iCol + 1) + “)”)
            .each(function () {
                $(“<div>”,
                    {
                        title: theTitle,
                        mouseover: function () {
                            $(this).addClass(‘ui-state-hover’);
                        },
                        mouseout: function () {
                            $(this).removeClass(‘ui-state-hover’);
                        },
                        click: function (e) {

                            /* Get the Contexts that we are using here. We need to know the Row
                                and the span in order to accomplish this task……*/

                            var row = $(e.target).closest(“tr.jqgrow”);
                            var span = $(e.target).closest(“span.ui-icon”)

                            /* And now call the Toggle Routine that will toggle the selection */

                            ToggleSelectedSelection(row, span, grid, dataColumn, true);

                            grid.saveRow($(row).attr(“id”), {
                                aftersavefunc: function (id, response, options) {
                                    var someRetValue = response; // set someRetValue to any value
                                }
                            });
                        }
                    }
                  ).css({ “margin-left”: “5px”, float: “left” })
                   .addClass(“ui-pg-div ui-inline-custom”)
                   .append(‘<span id=””></span>’)
                   .appendTo($(this).children(“div”));

                var row = $(this).closest(“tr.jqgrow”)
                var span = $(this).find(“span.ui-icon”);
                ToggleSelectedSelection(row, span, grid, dataColumn, false);

            });
    }
}
function ToggleSelectedSelection(row, span, grid, fieldName, toggle) {

    /* Get the Row id for the current row */

    var rowID = $(row).attr(“id”);
    var unselected =  bulletClass(fieldName);
    var selectedClass = tickClass(fieldName);

     /* And get the current selected value */

    var selected = grid.jqGrid(‘getCell’, rowID, fieldName);
    var removeClass = null;
    var addClass = null;
    var selectionState = null;

    /* Now work out what we need to show */

    if (toggle) {
        removeClass = (selected == ‘false’ || selected == false) ? unselected : selectedClass;
        addClass = (selected == ‘false’ || selected == false) ? selectedClass : unselected;
        selectionState = (selected == ‘false’ || selected == false) ? “true” : “false”;
    } else {
        addClass = (selected == ‘false’ || selected == false) ? unselected : selectedClass;
        removeClass = (selected == ‘false’ || selected == false) ? selectedClass : unselected;
    }

    /* And do that thing! */

    $(span).removeClass(removeClass);
    if (addClass != “”) {
        $(span).addClass(addClass);
    }
    if (selectionState != null) {
        grid.editRow(rowID);
        grid.jqGrid(‘setCell’, rowID, fieldName, selectionState, “”);
        grid.saveRow(rowID, {
           aftersavefunc: function (id, response, options) {
              }

         }
        );
    }
}

function bulletClass(fieldName) {
    switch (fieldName) {
        case “Red”: {
            return “ui-red-bullet”;
        }
        case “Amber”: {
            return “ui-amber-bullet”;
        }
        case “Green”: {
            return “ui-green-bullet”;
        }
        default: {
            return “ui-icon-bullet”;
        }
    }
}

function tickClass(fieldName) {
    switch (fieldName) {
        case “Red”: {
            return “ui-red-tick”;
        }
        case “Amber”: {
            return “ui-amber-tick”;
        }
        case “Green”: {
            return “ui-green-tick”;
        }
        default: {
            return “ui-icon-check”;
        }
    }
}
function  getColumnIndexByName (grid, columnName) {
    var cm = grid.jqGrid(‘getGridParam’, ‘colModel’), i = 0, l = cm.length;
    for (; i < l; i += 1) {
        if (cm[i].name === columnName) {
            return i; // return the index
        }
    }
    return -1;
}

And in the loadComplete event of the grid the following javascript starts the whole process….. If you are only colourising one column you need only call this routine once

OnLoadPrimeGridExclusive(grid, ‘RedAction’, ‘De/Select Red Rating’, ‘Red’, true);
OnLoadPrimeGridExclusive(grid, ‘AmberAction’, ‘De/Select Amber Rating’, ‘Amber’,true);
OnLoadPrimeGridExclusive(grid, ‘GreenAction’, ‘De/Select Green Rating’, ‘Green’, true);

A few notes that need to be made here, for each display column where the actual image is displayed ticked or not in this instance the columns RedAction/GreenAction/AmberAction there is also a hidden checkbox type data column which physically stores the boolean value indicating whether or not the grid is ticked or not (entitled Red/Green/Amber). This column is manipulated whenever the user clicks on an image to toggle the selection and the icon is set according to the underlying value of that column.

My time with JQGrid on this particular project has not been a happy one, I started off using the .NET MVC implementation but have overtime reverted to using the plain old javascript version as it offers a great deal more control and configurability. I think we may have turned a corner now and so thought I’d like to share some of that positivity with the community.

I hope this helps.

Faster Image Processsing (aka Lock your Bits).

colorful pixelsWhilst working on a small new project to write a console application that examines images for certain kinds of colour data I started, as I always do, with looking at how best to achieve this in a performant manner for the client. There is nothing worse than an application  that appears to hang whilst an invisible piece of processing occurs. True, in this instance it was a console app that would be automagically scheduled for use and so this was not such a design issue but I still think it’s good practice. The main remit of the application was to iterate over every single pixel within an image file and to perform various calculations against the colour data that we obtained,  the calculations were fairly simple and thus set in stone and so no real performance gains could be made out of a refactor, however this business of iterating over every pixel….

What of course springs to mind in the first instance is the easiest and quickest option and is demonstrated by the following code:-

    for (int y = 0; y &amp;lt; img.Height; y++){

      for (int x = 0; x &amp;lt; img.Width; x++){

        Color clr2 = img.GetPixel(x, y);

        if (clr2 == Color.Blue){

          Console.WriteLine("The colour was blue!");

      }

    }

  }

Job done, send it to the client…. But is that really the best way? If the client is processing huge amounts of very large files then very quickly your seemingly amazing turnaround of a solution for their issues seems ill thought out. A little more digging and I came across the Lockbits/UnlockBits methods of the bitmap object which I must admit that until this point I had not heard of. Please see this excellent blog if you need to know the precise mechanics of how this works.

http://www.bobpowell.net/lockingbits.htm

Effectively LockBits gives you direct access within memory to the underlying data that the image is composed of, access to the data is not via managed code instead using pointers and so needs to be marked as unsafe within the code, in addition the application itself needs to also allow unsafe code blocks to be run which can be done via the build tab within the project properties. After a little refactoring and we are presented with the following revisted code which performs the same job as the earlier snippet:-

      BitmapData picData = img.LockBits(new Rectangle(0, 0, img.Width, img.Height), ImageLockMode.ReadOnly, img.PixelFormat);

      try {

      /* Now ascertain the pixel size......*/

        int pixelSize = -1;
        switch (picData.PixelFormat) {
          case PixelFormat.Format32bppArgb: { pixelSize = 4; break; }
          case PixelFormat.Format24bppRgb: { pixelSize = 3; break; }
          case PixelFormat.Format8bppIndexed: { pixelSize = 1; break; }
        }

        if (pixelSize <= 0) {
          throw new FormatException("Pixel format is unsupported or could not be ascertained");
        }

      /* OK. Iterate over the Pixels */

        for (int y = 0; y < picData.Height; y++) {

      /* OK. As we are using unmanaged memory we need to mark the code segment as unsafe...*/

          unsafe { //AllowUnsafeCode

      /* Now obtain a pointer to the current row of data for the three bitmpas that we are processing
      The source image we access read only whilst we are writing the other two and thus need read-write
      access. */

          byte* row = (byte*)picData.Scan0 + (y * picData.Stride);

      /* Iterate over the width of the image */

          for (int x = 0; x < picData.Width; x++) {
            int[] array = { row[(x * pixelSize) + BLUE], row[(x * pixelSize) + GREEN], row[(x * pixelSize) + RED] };
            Color clr2 = Color.FromArgb(array[RED], array[GREEN], array[BLUE]);
            if(clr2==Color.Blue){
              Console.WriteLine("The colour was blue!");
            }
          }
        }
      }

      /* Whatever happens ensure that we unlock the images once processing has completed. */
     finally {
        try {
          img.UnlockBits(picData);
        } catch { }
     }


The proof of the pudding is of course in the eating, and this one tastes good. Against my 854 x 640 image using the original method the timings come in at 1.35 seconds per image, not exactly racing red especially when compared to the LockBits processing time which, even with all that extra set up code came in at under a 0.08 seconds which is in the region of 16 times faster.

Unit Testing Internal Methods

dotcover-resultsI’ll come straight out with it, I don’t like unit tests residing within the dll that they are testing, I know that some people quite like this approach and it could be argued that it allows the clients to verify that the unit tests are indeed in place and working correctly. For me though they are not a part of the production code and just add unnecessary bloat to it, this is allied to the fact that sometimes test rely on the infrastructure and there may also be a set amount of database interaction which for a live client is a big no no!

Instead I prefer all of my unit tests to be in a single or suite of test projects that are invoked sometime during the build process to verify the quality of the code. Recently we have been retroactively fitting some unit-testing to new functionality within a legacy project (which means that we do not of course have dependancy injection!) and I came up against an issue that we have come up against before but have always cludged our way around. The issue is one of scope, I like to test the validation routines for the business layer in isolation but we never ordinarily make our business layer validation methods public instead relying on the main ‘Update’ method to perform the validation prior to save. I like to call the validation methods in isolation because it means that the tests are more performant which in turn means you can be more thorough and reap the rewards of a more stable and tested application. Ideally I like to make the validation methods private or protected but for the sake of unit testing I will compromise and make them internal, this way they can be invoked from anywhere within the business layer but NOT from outside. OK, now scan back to my first paragraph and you can see where my problem lies… I don’t like unit tests in the dll itself.

Luckily .NET has a solution to this problem in that internal methods may be made visible to named external libraries; thus our unit testing library can invoke the required validation methods without exposing the same methods in the public API. However, all of the examples I have seen for implementing this are very poorly documented and so I thought as an aide memoire for myself, and as a service to the internet at large I would share my experiences.

For the purposes of this discussion I have three projects, the three projects must either ALL be signed or ALL unsigned, no if’s no buts. For the purposes of this discussion I will be using signed assemblies.

  1. MyProject.Business which is where the business rules reside – “C:\My Projects\MyProject.Business”
  2. MyProject.UI which is where the main application user interface resides -“C:\My Projects\MyProject.UI”
  3. MyProject.UnitTests which is where all of my Nunit tests reside – “C:\My Projects\MyProject.UnitTests”

MyProject.Business has the following class defined within it:-

namespace MyProject {
  public class ContactsBusiness {

    public void Update(ContactsDS data) {
       ....... Code...

       ValidateContacts(data);

       ....... More Code....
    }
    internal void ValidateContacts(ContactsDS data) {
       ....... Code...
    }
    private void SomeTopSecretMethod(ContactsDS data) {
       ....... Code...
    }
}
}

Now as things stand the only method visible to the external MyProject.UI and MyProject.UnitTests is the main Update method which will in turn invoke the ValidateContacts method. We now however wish to open this up so that the ValidateContacts method is also visible to the MyProject.UnitTests library but NOT MyProject.UI.

First things first, as I am using signed assemblies I will need the full public key for my business assembly, this can be obtained by opening the visual studio command line and typing the following command:-

sn -Tp "C:\My Projects\MyProject.Business\Bin\MyProject.Business.dll"

This returns the following public key for the assembly:-

00240000048000009400000006020000002400005253413
10004000001000100d3485b9bbad933c83462d897d9121bc93c09
1c396c6f080a53c8812c1855a170038014b21ab10152583a8fe08
c2ea2e5919af8078e97ada5c54f0f403dcb491da323623ad4340a
294862d10440b0ab25746eea9311f0f9b5e2dd7c849ca1135bb65
225131d959a10737c44639303c27e775771d7a4e523f32d14ae31
9041acc9

We now add the following InternalsVisibleTo attribute to the AssemblyInfo.cs fle  (located within the properties folder of the MyProject.Business projects) . If your assemblies are unsigned the public key is not required at all.

[assembly: AssemblyTrademark( "" )]
[assembly: AssemblyCulture( "" )]
[assembly: InternalsVisibleTo("MyProject.UnitTests,PublicKey=0024000004800000940000000602000000240000525341310004000001000100d3485b9bbad933c83462d897d9121bc93c091c396c6f080a53c8812c1855a170038014b21ab10152583a8fe08c2ea2e5919af8078e97ada5c54f0f403dcb491da323623ad4340a294862d10440b0ab25746eea9311f0f9b5e2dd7c849ca1135bb65225131d959a10737c44639303c27e775771d7a4e523f32d14ae319041acc9")]

Note that we are giving the MyProject.UnitTests project (in its entirety) access to all methods and classes marked as internal residing within the MyProject.Business assembly. All private and protected methods are of course unaffected and behave in the same manner. With this in place I can now test the validation methods in isolation allowing us to increase and better target our unit testing meaning that our products can be more thoroughly tested before they even leave the development workbench.