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


WCF Web Service and JavaScript

Over the last week or so I have been playing around with a simple WCF service to send and receive data from JavaScript using JQuery.  I thought that this would be a lot easier than I found it.  The other interesting thing I found is that a few people seem to have had trouble getting the two to connect and work.  When I set up a standard Service in Visual Studio 2010.  I thought it would be easy.  You would just use the $.ajax to send through the request and wait for an answer from the service.  Now this is probably due to the fact that I am not familiar with WCF, but I thought it would be simple.  Well I found that a few things did not work.  So What I have done is created a simple project based in MVC 3 (not that that even matters,  Since there is only one page on the website), and a service.

So these are my steps to getting JQuery to talk to a WCF service.

Start this off by creating a new project.  It can be Web forms or MVC application.  The application type is not the most important part.  As long as it is a web style project.

Creating the Service

Once you have created a solution, add a new WCF service to the project.

New Service

 

When I created the service, I added it to a service folder to keep it separate from the the rest of the web project,  I find it makes it easy to find if there are any changes that need to be made.  There should three files in the folder, an interface, the svc service and the service code behind.

DISCLAIMER:  I had a lot of issue getting the service to work with the interface.  I found that when I deleted it and just worked with the service it worked.  I am not saying that it will not work with the interface.  I just could not get it to work.  So if anyone has information on how to get it working, please let me know.

So before I started trying to connect the JavaScript to the service I went to the service page to make sure it was working the way I expected.  You should get the following page:

Service Page

I found this useful since any errors will be shown and may save you a lot of hassle before trying to connect the JavaScript.  One thing to note is that you need to have at least one method or operation contract or the service will return an error.  There should be one by default when you create the service.  If you have deleted the interface remember to add the [OperationContract] onto the method before checking to see the service works.

There are some changes needed to make the service work:

  • On the Class definition, add the following [ServiceBehavior(IncludeExceptionDetailInFaults = true)].  This will make sure that if there is any errors, the exception will be sent to the JavaScript.  I found this really useful debugging the errors.
  • [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  • Right click on the Service.svc file and select View Markup.  Add Factory=”System.ServiceModel.Activation.WebScriptServiceHostFactory” in the ServiceHost definition.
  •  

    Connecting With JavaScript

    This was the easiest part for me.  There are two methods that I used here:  The first obviously was JQuery.  I used the $.ajax to call the WCF service.  You can find the JQuery documentation on the Ajax call here : JQuery Page. The Basic format is this:

    $.ajax({
    url: url, //Url of the Service
    type: “POST”,  //Type of ajax call
    data: JSON2.stringify({ value: “value” }),  //Data to send
    processData: true,
    contentType: “application/json”, //Type of data being sent
    timeout: 10000,
    dataType: “json”,
    success: function (response, status) { //Success Callback
    //Do Something cool here

    }
    },
    error: function (request, textStatus, error) { //Error callback
    alert(“An unexpected error occured”);
    }
    }
    );

    The second thing I use is the json library.  This can be found at http://www.JSON.org/. The method I use here is stringify.  This converts a JavaScript object to a Json string.

    JsonP

    I would like to take the time to look into Jsonp.  Normally you are not allow cross domain calls using normal json.  Jsonp stands for json with padding.  The way this works is by wrapping the json response in script tags.  The way this works is that when you call the sever, you add a jsonp at the end of the url i.e. www.url.com?jsonp=callback.  When the server responds to the call, it will wrap the json response in the method call you specified.  So in this example, the response would be callback({ “property” : “valueDefined” });

    When you implement the callback function all you would do is call the callback method in the following way:

    function callback(jsonObject){
    //Do clever stuff here
    }

    BUT be warned.  This can mean that the service can inject malicious code into browser.  So be careful when using this approach.
    kick it on DotNetKicks.com


    Camel case table names in MySQL

    I have been working with Entity Framework 4 and MySQL.  The main problem I have found is that since I am working on a windows server, the table names in the database are all lower case.  This means that when I create the entities in Visual Studio, the classes are all lower case. 

    So I have found this solution:

    There is a setting in the configuration file in the MySQL server directory.  I am using Windows 7 so this was under:

    C:\Program Files (x86)\MySQL\MySQL Server 5.5C:\Program Files (x86)\MySQL\MySQL In this Server 5.5\

    In this directory you will find a file: my.cnf.  This governs how MySQL runs.  You will need to change or add a line to allow camel casing of table names.  Please note that you should read http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html.  This details the changes and how they should be used on different operating systems.  I am only detailing how I got this to work on windows.  If you are running Linux then please go to the link mentioned above to make sure that the change will not affect your system / MySQL instance.

    Steps taken to allow camel casing:

    • Go to Control Panel –> Administrative Tools –> Services
    • Stop the MySQL Service
    • Open C:\Program Files (x86)\MySQL\MySQL Server 5.5C:\Program Files (x86)\MySQL\MySQL In this Server 5.5\
    • Open the my.cnf file as Administrator
    • Add the line lower_case_table_names=2 under the mysqld section.  If this line is there then just change the value to ‘2’.  Make sure that there is only one line there.
    • Go Back to Services and restart MySQL.

    You should be done.  Hope this short guide has helped.