DatePicker with dynamic DOM Elements

I have been battling with a problem with the date picker. The problem is that when I add new inputs with the DatePicker class they do not behave in the same way as with the document load. The code I was using was:

$(document).ready(function (){
     $("input.datePicker").datepicker();
});

After that I was just trying to rebind the events using the destroy and datepicker methods.  Unfortunately this did not work!  Eventually I found this great stackoverflow answer and since I was cloning the elemtns I had to remove the hasDatePicker to rebind.

$('.date').last().removeClass('hasDatepicker');
$('.date').last().removeAttr('id');
$('.date').last().datepicker();



Hopefully this helps if you have the same problem.


Test Driven Design By Example

We have started using Test Driven Design (hopefully properly) over the last few months and I wanted to share our experiences of it. Before we started using TDD our approach to unit testing was to find a unit of work that we had just completed and write a test to make sure the output of the method was what we expected. The most obvious problem with this is that while we are hoping that the unit test will be testing the method, actually what we were doing was testing the method and everything that used it. So in this case we were testing any service calls, database calls, any other classes and objects that are used in the method.

Looking at how TDD works

The easiest way of understanding what test driven design is, can be achieved by looking at the following diagram: Test-driven development
Please note I have obtained this image from Wikipedia (the article can be found here) To summarize:

  1. Before writing any code to solve the issue:  write a test to test the functionality.  If the test passes then the functionality exists or the test has not been written correctly.
  2. Run the tests to make sure that this does fail.
  3. Write only enough code to make the test pass.
  4. Run all the tests to make sure that the test passes.   All the tests should be run to make sure that the new code does not break the existing tests.
  5. Refactor and clean up the code.

The Role of mocks and stubs

To understand what a mock object is, it is a good idea to see what they do in the context of a unit test.  I have said previously that a bad test is a test that unwittingly tests the objects that the unit of work uses, so databases external classes etc.  A good way of only testing the code in the method would be to create fake objects that return what you expect it to.  This eliminates their influence on the logic by limiting the external factors.  I found a really good answer on stackoverflow on what the difference is between a mock and a stub: answer.

Bad unit test designs

From what I have seen a lot of tests that have been written in the past are integration tests.  An integration test is a test that tests the integration (I know it is obvious, but I still thought I would make it clear) of the system to another system, most often this is used to test the integration of the application being tested and a database.  I am not saying integration tests are a bad thing, what I am saying is that integration tests masquerading as unit tests are a bad thing.  The reason for this is that a unit test should test the small unit of work that the code handles and not the external factors on the method.  These tests make it hard to understand what is being tested and what is not.  The other issue is that they are extremely brittle:  since they rely heavily on external factors, if any of the objects change the test will break.

Benefits of Test Driven Design

  • When you write a test to describe the way a unit of work should work,  it helps you only write code to make the test pass, therefor making sure that there is no creep.
  • With adding of unit tests, the code should be more stable and less prone to bugs.
    • This can be shown by research done by Microsoft entitled Realizing quality improvement through test driven development: results and experiences of four industrial teams.  An except from the conclusion of this paper: “Our experiences and distilled lessons learned, all point to the fact that TDD seems to be applicable in various domains and can significantly reduce the defect density of developed software without significant productivity reduction of the development team. Additionally, since an important aspect of TDD is the creation of test assets—unit, functional, and integration tests. Future releases of these products, as they continue using TDD, will also experience low defect densities due to the use of these test assets”.  This paper can be found at: http://research.microsoft.com/en-us/groups/ese/nagappan_tdd.pdf
  • By using continuous integration and running unit tests when code changes are made, the unit tests can make sure that the changes are not damaging existing functionality.
  • Unit tests can often show that a method or a class has too much responsibility.  This can be seen if it is not clear what the output of a method is or if there is a too many inputs or if a lot is changed inside the method.   Unit test help the developer to think about how the code they are about to write will pass the test and only the test.

Example Of Test Driven Design

In this example I am going to create a Fibonacci Sequence.  To start off I created a project and a test project.

These are the steps I used in my TDD:

In the Test project I created a class called FibonacciSequenceTests.  In the class I created the following test:

public void Test_Find_Fibonacci_Sequence_At_Position_Correct()
{
     //Arrange
     FibonacciSequence fibonacciSequence = new FibonacciSequence();

     //Act
     int sequenceAtPosition = fibonacciSequence.FindFibonacciSequenceAtPosition(8);

     //Assert
     Assert.AreEqual(sequenceAtPosition, 21);
}

This obviously failed since there is no functionality in the solution, so I created the class:

public class FibonacciSequence
{
     public int FindFibonacciSequenceAtPosition(int n)
     {
          int a = 0;
          int b = 1;

          // In N steps compute Fibonacci sequence iteratively.
          for (int i = 0; i < n; i++)
          {
               int temp = a;
               a = b;
               b = temp + b;
          }
          return a;
     }
}



kick it on DotNetKicks.com



Nhibernate Error: Invalid index N for this SqlParameterCollection with Count=N

This error came up this week when I was working with one of the applications we have.  The first thing I tried is using Profiler to see what SQL was being generated.  But the strange thing was that I could not see any Insert statement.

Eventually I found the cause of the error.  I had added some properties to the nhibernate mapping file:

<property name="property1" type="String(100)" column="property1" />
<property name="property2" type="String(100)" column="property1" />
<property name="property3" type="Int32" column="property1" />
<property name="property4" type="Int32" column="property1" />

I had missed the fact that I had pointed them to the same field in the table.  So the Xml should have been:

<property name="property1" type="String(100)" column="property1" />
<property name="property2" type="String(100)" column="property2" />
<property name="property3" type="Int32" column="property3" />
<property name="property4" type="Int32" column="property4" />

I would assume you would get the same error for fluent nhibernate.


HTML5: The New Frontier

Introduction

The intention of this post is to look at the changes in HTML5.  HTML5 is the next revision of the language that is generally used to write content on the web.  The new version of HTML has been compiled by The World Wide Web Consortium (W3C).  The W3C is (in their own words) “an international community where Member organizations, a full-time staff, and the public work together to develop Web standards”.  The new version of HTML boasts a number of new features that are useful.

Overview of features

HTML5 has made a number of fundamental changes to the structure of the mark-up that is written.  This can be seen in the new elements to denote the sections of the document.  Previously they would be the same element, i.e. a <div> element.  Now there are elements for each section.  With the new section elements, there is the canvas tag which allows rendering of 2D shapes on the page.  These are not the only exciting new element, the addition of audio and video as well as offline storage allow the developer to bring the site alive without the use of third party plug-ins.

New Tags

Lets begin with the new tags.  W3C has introduced a number of new tags that allow the programmer to be able to embed music, video and graphics without the use of flash or Silverlight.  Lets take a look a few of those tags and their usage and function:

Canvas Tag:
The canvas tag is used for rendering graphics on a page.  The way you would draw on the canvas is to define a canvas object in the HTML, then define and draw the objects in JavaScript. Have a look at the sample:
HTML:

<canvas id=”canvasArea" width="500" height="500">

JavaScript:

<script>
//The following script will create a 2D grey rectangle on the canvas element
$(document).ready(function(){
var canvas = document.getElementById('canvasArea');
var context = canvas.getContext('2d');
context.fillStyle = '#909090';
//fillRect(x-pos, y-pos, width, height)
context.fillRect(0,0,80,100);      }
});
</script>

Audio Tag:
The Audio tag defines and audio stream that can played in the browser.  The audio tag allows a number of different formats.  The following displays the use of the audio tag:

<audio controls="Audiocontrol">
<source src="SourceFile.mp3" type="audio/mp3" />
</audio>

 

Local Storage
Local storage has long been used to applications to track and store information when a user is on the website. This has traditionally been stored in cookies. Before this
Google release Google gears which promised to store information on the client using an installed application on the users machine. HTML 5 storage works on the client
browser without any 3rd party application. To use it you would need to write JavaScript to fetch and store values in the following ways:

//Make sure nothing has been stored
if(localStorage && !localStorage.Storage)
{
localStorage.Storage = "Store This";
document.write("<p>Storing Value: " + localStorage.Storage + "</p>");
}
//Write value to html
document.write("<p>Stored Value: " + localStorage.Storage+ "</p>");
//Refresh to view the sequence of events.

There is a limit on the amount of data that you would be able to store. There is a specification from W3C (link) on storage but it does not specify the limit. It looks as if it may be around 5mb, but this may vary. To make sure you don’t cause an error if the limit has been reached use the following script:

//Making sure the limit has not been reached
try {
        localStorage.setItem('Storage', 'value');
    } catch (e) {
          if (e == QUOTA_EXCEEDED_ERR) {
               //Do some error handling
        }
    }

Here are some use operations for interacting with local storage:

//Making sure the browser supports localstorage:
if (typeof(localStorage) == 'undefined' ) {
    alert('Your browser does not support HTML5 localStorage. Try upgrading.');
}

//removing an item from local storage:
localStorage.removeItem('Storage');

//Adding an item: (name, value)
localStorage.setItem('Storage', 'value');

Geolocation:
With the growing use of smart internet enabled phones, geolocation can help a site to provide rich information to the user. This can be overlayed with a map service like bing or google to display any number of useful ideas. To use the geolocation feature in HTML5 is very easy:

$(document).ready(function(){
    LoadGeolocation();
});  

function LoadGeolocation() {
    navigator.geolocation.getCurrentPosition(GeolocationPosition);
}  

function GeolocationPosition(position){
    var lat = position.coords.latitude;
    var lon = position.coords.latitude;
}

 

Conclusion

As we have seen there are some exciting features in the new version of HTML 5. I am sure that they will lead to an improved user experience. Have fun.

kick it on DotNetKicks.com


Exclusive access could not be obtained

I have come across this issue a number of times when an unknown process is using the database when I am trying to restore it.

I solved this by using the following query to find the process Id:

SELECT spid, loginame, login_time, program_name
FROM [master]..sysprocesses
WHERE DBID=DB_ID(‘DatabaseName’)

Then to kill it, you would use:

Kill id — eg kill 52