Monday, July 25, 2011

Reshaper 6 JavaScript Support

JavaScript support in Resharper 6 is absolutely amazing. I was playing around with KnockOutJS and was surprised to find intellisense. Even Ctrl + p worked to show the signature of a JavaScript function. If you do alot of JavaScript I highly recommend Resharper 6.

Sunday, July 24, 2011

Visual Studio 2010 JScript Editor Extensions

Install it. Enough said.

Monday, July 19, 2010

NHibernate Detached Criteria is not Reusable

While working on a paging feature for our application I discovered that the NHibernate detached criteria is not reusable. My goal was to create a single call to a repository using one detached criteria. The Idea was to reuse the detached criteria to perform two queries. One query to retrieve the total number records. The second query to retrieve a list of items for the specified page number and number of records per a page.

On the repository we have the following method.
QueryResult<T> FindBy(DetachedCriteria query,int pageNumber,int numberOfItemsToDisplay);

The QueryResult returned from the repository has a total and the items for the requested page.
public class QueryResult<T>
    {
        public int TotalNumberOfItems { get; private set; }
        public IEnumerable<T> Items { get; private set; }

        public QueryResult(int totalNumberOfItems, IEnumerable<T> items)
        {
            TotalNumberOfItems = totalNumberOfItems;
            Items = items;
        }
    }

Here is my implementation of FindBy. I had a few helper methods but removed them to fully illustrate the problem.
   public QueryResult<T> FindBy(DetachedCriteria query, int pageNumber, int numberOfItemsToDisplay)
        {
            var pageIndex = pageNumber - 1;
            var firstResult = 0;

            if (pageIndex != 0)
                firstResult = pageIndex * numberOfItemsToDisplay;

            ICriteria executableQuery = query.GetExecutableCriteria(CurrentSession());
            executableQuery.SetProjection(Projections.RowCount());

            var count =  executableQuery.UniqueResult<int>();

            query.SetProjection(null);
            query.SetResultTransformer(CriteriaSpecification.RootEntity);

            var items = FindBy(query.SetFirstResult(firstResult).SetMaxResults(numberOfItemsToDisplay));

            return new QueryResult<T>(count,items);
        }

The confusing part
ICriteria executableQuery = query.GetExecutableCriteria(CurrentSession());
Calling getExecutableCritieria returns an ICrtieria object. One would think that the criteria object does not have a connection to the detached query object. Calling the code below should not change the detached criteria.

executableQuery.SetProjection(Projections.RowCount());
var count =  executableQuery.UniqueResult<int>();
The quick fix is to set the projection to null and reset the result transformer.

//Reset
query.SetProjection(null);
query.SetResultTransformer(CriteriaSpecification.RootEntity);

//Excute new query
var items = FindBy(query.SetFirstResult(firstResult).SetMaxResults(numberOfItemsToDisplay));

In Summary
I find the behaviour of the detached criteria object to be somewhat odd. It might just be a misunderstanding on my part but the API led me to believe that the ICriteria object had no relationship to the detached query. The coupling between the ICriteria object and detached criteria was a big surprise. If I were to ask I bet the NHibernrate/Hibernate team or even Oren Eini could provide me with an explanation.

Sunday, July 18, 2010

Razor View Engine for Asp.Net MVC and More

Microsoft has done it again. They are releasing a new view engine for Asp.Net MVC code named Razor. Even more impressive is the fact that you will be able to use more than one view engine in your application. This means that you can develop an application using the web forms view engine, spark and razor. To learn more head over to Scott Gu's blog. The new view engine is slated to be released with the next version of Asp.net MVC.

In other news Microsoft is working on two other products: IIS Express and SQL Server Compact Edition 4. With IIS Express you can have a full featured web server that does not require administrative privileges. This is wonderful news for the security conscious developer with a locked down machine(for example this guy). IIS Express unlike the built-in web server in visual studio will support SSL and url rewriting. From what I can tell it will do pretty much anything IIS 7 does. According to the Gu it will be released as an patch for Visual Studio 2010 later in the year. All versions of Visual Studio in the future will be shipped with IIS Express.

SQL Server Compact Edition 4 is another cool product that will work with Asp.Net MVC. SQL CE doesn't require any installation. It's as simple as dropping a few dlls in the bin of your application. When your application starts SQL CE is loaded into memory and when the application stops it is unloaded. Even better is the ability to easily upgrade from SQL CE to SQL server express, SQL server or  even SQL Azure. This means that you can start an application with SQL CE and then upgrade when your application grows beyond the limitations of SQL CE. Visual Studio 2010 will also feature support for SQL CE. It might just be me but Visual Studio is starting to become a one stop shop for everything, and I like it. Fortunately SQL CE does not support stored procedures. Stored procedures are evil so no big deal there. It's also important to mention that you do not have to change any code to work with SQL CE. It should be as easy as changing your connection string.

Monday, April 5, 2010

10038 Jolly Jumper Solution

Here's my Jolly Jumper solution. It was accepted by UVA online judge. It may not be the best solution but at least its readable.

My Algorithm is designed to fail quickly. As it calculates each sequence number it checks against three simple rules

  1. The sequence(n) number cannot be 0
  2. The sequence(n) number cannot be equal or greater than the input(numbers in my code). If there are 4 numbers then the sequence should contain the numbers 1,2,3
  3. There cannot be duplicates.
My solutions took 0.304 seconds to execute. Compared to the best, my solution is rather slow. The best solutions were written in C++ and ANSI C. Their run time was a flat 0. It would be rather interesting to see if  I could get an even faster run time. The only problem is that I'm using Java which is going to be slow from the get go. On the bright side I am one of 9546 users that have solved this problem.

My solution came as a result of refactoring. My original solution did not fail early. Instead it gathered all sequence numbers, sorted a list and then checked that it had the correct numbers. My original solution had an execution time of about 0.36 well my new solution executed at about 0.304. Although my solution isn't the fastest's I do enjoy its readability.

The problem can be found here

Sunday, April 4, 2010

Algorithms Book Club

Well the book club I am a member of is at it again. This time our book club is tackling Algorithms in all its fun and glory... The book we are reading is "The Algorithm Design Manual" by Stenven S. Skiena.

Our first session covered the wonders of big O notation (asymptotic Notation). I'm happy to say that complexity is growing linearly at O(n)... but some days I swear its like O(n!).

Our second session covered big O again...

Our third session uncovered the mysteries of data structures.

Our next session is perhaps more ambitious. We are going to step into the arena and knockout a few algorithms.

The Arena: http://uva.onlinejudge.org/

My Weapon of Choice: Java

The Problems:

Jolly Jumpers (Solved)
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&categor
y=12&page=show_problem&problem=979


Where's Waldorf?(Unsolved)
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&categor
y=12&page=show_problem&problem=951


Crypt Kicker(Unsolved)
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&categor
y=10&page=show_problem&problem=784


Crypt Kicker II(Unsolved)
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&categor
y=31&page=show_problem&problem=791

Sunday, March 14, 2010

Happy Pi day!!!

Other than being Pi day it's also Mr. Einstien's birthday!

Friday, November 13, 2009

Reset Visual Stuido Environment

For some reason or another my esc key stopped working in visual studio. To make things worse I never made a copy of my environment settings. Without a copy of my default settings I thought that I would have to reinstall or repair visual studio. I was completely and utterly doomed. However, thanks to a quick search, I found that visual studio can be reset back to its default settings through the command line:

devenv /resetsettings

MSDN Documentation

Wednesday, November 11, 2009

Functional Testing Reinvented

For the last few months our team has been using ruby and RWebSpec for functional testing. The only problem with this type of testing is that it's very brittle. The slightest change to an html element name or even renaming a view can cause our tests to fail. We have been actively searching for a better solution without any results. At least until NOW.

Jimmy Bogard recently hosted a screencast called "UI Testing". From the looks of it, the Jimmster has solved our brittle functional testing problem. Using watiN, gallio and most importantly designing for testability our functional tests can be less fragile. It's actually no different than test driven development. The first thing that you learn with test driven development is that you have to design for testability. If your interested in making your legacy code more testable I suggest giving Michael Feathers book "Working Effectively with Legacy Code" a read. As Michael puts it, all code is legacy code.

On a separate note our team has also been struggling with deciding how to integrate functional testing into our sprint. One idea that we have is to create a set of acceptance criteria for each story. The acceptance criteria would then be confirmed through our functional tests. Therefore, a story can only be marked as complete if it passes all acceptance criteria.

Click here to view Jimmy's awesome screencast.

Tuesday, November 10, 2009

MVC 2 Preview 2 Client Side Validation

Every once in a while early adoption has a way of making a simple process painful. What makes matters even worse is the lack of documentation. Several times during the spiking process I found myself second guessing whether I was at fault or I found a bug. 

First here's an awesome walk through of how to use MVC client side validation. That's right, it's just a blank page at the moment.



Validating on the Server Side 


ASP.MVC 2 Preview 1 introduced DataAnnotations to validate a presentation model on the server side. After decorating your model with DataAnnotations validating the presentation model is taken care of by the DefaultModelBinder.

For example, I created a car presentation model class that ensures the make and model are both required and the string length can be no more than 100 characters. I also added a validation to ensure that the year is between 1900 and 2011.


  public class Car
        {
            [DisplayName("Make")]
            [Required]
            [StringLength(100)]
            public string Make { get; set; }
  
            [DisplayName("Model")]
            [Required]
            [StringLength(100)]
            public string Model { get; set; }
            [Range(1900,2011)]
            public int Year { get; set; }
        }
 The create action can now ask the ModelState if it is valid. If the ModelState is not valid you can redisplay the view with errors.


        public ViewResult Create(Car car)
        {
            if (ModelState.IsNotValid())
                return View(car);
            CreateCarCommand.Execute(car);

            return View("Success");
        }



        public static class ModelStateDictionaryExtensions
        {
            public static bool IsNotValid(this ModelStateDictionary subject)
            {
                return !subject.IsValid;
            }
        }
On the view you can display errors in a validation summary or place the errors next to the offending html control.
Validating On The Client Side (MVC 2 Preview 2)


As great as server side validation is, client side validation is the icing on the cake. In the spirit of re-usability DataAnnotations can be reused on the client side. Here is an snippit from ASP.MVC 2 preview 2 release notes:


"The model validator provider class exposes validation metadata to the browser in the form of JSON-serialized metadata that can be consumed by a client-side validation library. The provider class allows you to use other client validation frameworks by writing an adapter that processes the JSON metadata and calls into the alternate client validation library.
ASP.NET MVC Preview 2 includes the jQuery validation library and a client-side validation adapter for that library. The adapter supports the following DataAnnotations namespace validation attributes:
·         StringLengthAttribute
·         RequiredAttribute
·         RegexAttribute
·         RangeAttribute                                                                 
                                                             " 
The only kicker is that this is a preview and far from perfect.

To enable client side validation you only need a few things:
  1. A call to Html.EnableClientSideValidation();
  2. Three javascript files
    1. jquery core
    2. jquery validate
    3. and MicrosoftMvcJqueryValidation.JS
  3. A lucky rabbit's foot...
Actually it really wasn't that hard to get going and I imagine it will be allot easier in future releases. Heres a list of a few bugs and annoyances.
  1. Html.BeginForm and Html.EndForm do not work as pointed out on Hadi Hariri's blog. Since it does not implement IDisposable.

  2. Html.BeginForm does not seem to generate any JSON or JS needed to validate on the client. I have no Idea why this will not work since it does implement IDisposable..

  3. So far only Html.BeginForm with out generics works but you can still do some cleaver things to keep things strongly typed.

  4. Once I had my application up and running I noticed the javascript validations were not firing when I was tabbing over the input boxes. They only started to work after clicking submit.

  5. If you plan on doing server side validations there seems to be an odd side effect. At least I think it's an odd side effect. I have a view that requires one of the inputs to be validated on the server side. I achieved this by creating a custom validation attribute. Upon returning to the view you are presented with a input box that is colored red and has text explaining the error. Once entering text into the input the textbox returns to normal and the red text disappears. Since the error resides from the server side I would expect the error message to not disappear. I'm still deciding if this is odd behavior or not.
Overall I'm happy with the first release of client side validation for Asp.net MVC. Now that I've had a taste of client side validation in ASP.Net MVC I'm ready to try other validation frameworks.