Archive for the ‘ASP.NET MVC’ category

Knockout – quick asp.net mvc sample

July 5th, 2010

Steve Sanderson has released knockout  – read more here about what knockout is.

Knockout is a JavaScript library that makes it easier to create rich, desktop-like user interfaces with JavaScript and HTML, using observers to make your UI automatically stay in sync with an underlying data model. It works particularly well with the MVVM pattern, offering declarative bindings somewhat like Silverlight but without the browser plugin.

Well, as a fan of his asp.net mvc book (Pro ASP.NET MVC Framework (mvc1) and just recent release of Pro ASP.NET MVC 2 – and please note – knockout isn’t at all associated or tied to asp.net mvc!) – I was quickly wanting to take his editor sample – which was so elegantly put together – and simple show a way to pass json data from a controller action to his sample.

Here is the sample code.

I’m not going to go too much into knockout – simply because Steve’s post and sample page describe it very well.  I do think this is a good follow up to a post a made regarding jTemplates. 

Enjoy!

ASP.NET MVC – jQuery – Json.. Cascading Dropdown

June 30th, 2010

I’m less interested in the ‘cascading dropdown’ part of this post , as I am in demonstrating how json and jquery can be your friends in the asp.net mvc world.

Let’s start by a description of the ‘problem’:  On populating a page, we need to query for a set of companies and display those to the user.  Upon selection of a company, we need to populate another dropdown of the banks associated to that company.  You can fill in the blanks for ‘companies’with ‘banks’ – basically a one to many.  In my situation, I use lazy loading and do not need to pull all the banks in when the page loads.

First let’s look at the ‘onLoad’ of the page via jQuery:
$(function () {
  $("#companies").change(function () {
    LoadBanks($("#companies").val());
    });
  });

I’ve simplified this from the code to show the essentials.  I’m handling the onChange of the companies drop down list, something like this:
Select Company: <%= Html.DropDownList("companies", new SelectList(Model, "Companyid", "Name"), string.Empty)%>
The Model is my list of ‘Company’ objects.  The value is the id and the text is the name.
From the above javascript, you’ll see that when the dropdown item is selected I will be passing the selected value – which is the id – to the LoadBanks function:

function LoadBanks(companyId) {
 $.ajax({
  type: "POST",
  url: BuildUrl("Company/LoadBanks"),
  data: ({ id: companyId }),
  dataType: "json",
  beforeSend: function () {
$.blockUI({ message: "Retrieving Banks..." });   //this is great plugin - 'blockUI'
},
success: function (positivePayBanks) {
  $("#positivePayBanks").find('option').remove();
  $banks = $("#positivePayBanks");
  $.each(positivePayBanks, function (i, bank) {
  if (i == 0) { $("#BankID").val(bank.BankID); }
   $banks.append('<option value="' + bank.BankID + '">' + bank.BankName + '</option>');
  });
$.unblockUI();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
  $.unblockUI();
  var errMsg = "<P>Error Loading: " + XMLHttpRequest.responseText + "<br/>";
  $("#status").html(errMsg).show("slow");
}
});
}

So, what is going on in this call?

type: "POST"
url: BuildUrl("Company/LoadBanks"),   <-- the BuildUrl is just a helper call - basically this is the REST call to the controller/action
data: ({ id: companyId }),   <-- this is the params being sent to the Action.  I'm passing the selected company id
dataType: "json",   <--  I'm saying that the returning data will be json.

Let’s step out of the javascript/html to just show how easy it is to serialize the list of banks to json in mvc:
This isn’t too exciting but here is the controller action for ‘LoadBanks’:

[HttpPost]    <-- I'm requiring this to be a post here
public ActionResult LoadBanks(string id) <--- this id will pick up the id passed in the ajax call above
{
  var positivePayBanks = _companyService.GetBanksByCompanyId(new Guid(id));
  return Json(positivePayBanks);
}

Pretty boring isn’t it?  The simplicity here is appreciate though as mvc includes a JsonResult that will take the list of banks and generate the json!
Here is the select html:

<select id="positivePayBanks" class="required"></select>

The meat here of the post is how we can take that resulting json data and ‘bind’ it to the bank dropdown:

success: function (positivePayBanks) {   <--- 'positivePayBanks' is the returning json data
  $("#positivePayBanks").find('option').remove();     <--- this clears it each time, as it will continue to just append if I don't first remove it!
  $banks = $("#positivePayBanks");
  $.each(positivePayBanks, function (i, bank) {    <--- the beauty of jQuery here is a nice foreach statement
   if (i == 0) { $("#BankID").val(bank.BankID); }    <-- I'm actually forced to set the id of the selected bank or the form post doesn't catch it.
   $banks.append('<option value="' + bank.BankID + '">' + bank.BankName + '</option>');   <-- append the results to the select
  });
$.unblockUI(); //unblock the UI
}

I left the blockUI in this sample because I want to remind those using ajax, that there is no control over the latency on the network – so rather than leave the user wondering what just happened, this gives a visible indicator.
For those new to Json, the part I like the best here is that jQuery will deserialize the json data into the ajax result:
(success: function (positivePayBanks))
Since this is a list of banks, we can use jQuery to loop through each one and it is represented as a bank object, which allows for the ‘bank.BankID’ and ‘bank.BankName’
Just as a finishing note, it is possible to just return a partialview with a Html.DropdownList , etc..  - however, by using Json , it greatly decreases the transmission over the wire.  Json is a perfect medium for keeping the data minimal, and as you can see it goes hand in hand with frameworks like jQuery.
One piece of this I do not like, is how I needed to then set the selected bankId to a hidden field.  I was able to get the value passed into the form collection on form post naturally.  If anyone has a trick for that- let me know  :)
PS. I’m still looking for a good WordPress application to run on MacBook

ASP.NET MVC with jTemplates – Part I

May 20th, 2010

One of my goals in web development is to continue to look to use json to transmit data vs. using partial views.  Obviously by transmitting json data, the payload is going to be much more efficient.

I’m going to break this out into two parts :

Part I is going to cover the basics to using jTemplate with jQuery within an asp.net mvc environment.

Part II is going to take this concept and apply it to a nice looking jQuery plugin ‘grid control’ called  DataTables

Let’s look at what the final result will be:

image

Let’s address the server side pieces first:

I’m going to create a new Model class ‘Person’:

public class Person
    {
        public string ID { get; set; }
        public string FirstName { get; set; }
        public string Email { get; set; }
    }

Using the default asp.net mvc created project type, I’ll just a hook into the the Home controller to display the table in the index page.  To do this, I’ll need to add another action with some sample data that will be called from the page via ajax:

 

 [HttpPost]
 public JsonResult GetData()
 {
      IList<Person> people = new List<Person>
        {
          new Person {ID = "1", FirstName = "Anne", Email = "anne@domain.com"},
          new Person {ID = "2", FirstName = "Amelie", Email = "amelie@domain.com"},
          new Person {ID = "3", FirstName = "Polly", Email = "polly@domain.com"},
          new Person {ID = "4", FirstName = "Alice", Email = "alice@domain.com"},
          new Person {ID = "5", FirstName = "Martha", Email = "martha@domain.com"}
        };
      return Json(people);
}

The ‘return Json(people)’ will return the list in json format – which you can see in the above Firebug screenshot ‘response’. 

So that is basically it for the server side.

The first step in the views is to add the references to the javascript files.  Since I’m using the site.master I’ll add it there, so that it’s available to other views as well:

image 

(For production, you will want to use the compressed/min files instead)

I also add a new ContentPlaceHolder in the head of the site.master:

<asp:ContentPlaceHolder ID="HeadContent" runat="server" />

This way on the views, I can put any scripts in the head tags as well.

In the Index.aspx page we can finish this functionality:

1. add the scripts to the head of the view:

<asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server">
    <script type="text/javascript">
        $(document).ready(function () {
        $.ajax({
                type:"POST",
                url: "<%= Url.Action("GetData") %>",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data){
                    $("#jTemplateDemo").setTemplate($("#templateHolder").html());
                    $("#jTemplateDemo").processTemplate(data);
                }
            });
        });
    </script>
</asp:Content>

To review this (we could use a $.getJSON as well) – on the page ready function I’m going to make an ajax call back to the ‘GetData’ action.  This is defined in the ‘url:’ parameter.

In this case there are no parameters being passed so the data is left blank (this is best practice to include “{}” when blank).  It is possible to use a REST url as well with parameters.

We define out contentType (using $.getJSON) would do this automatically.

Lastly, we provide an ‘onSuccess’ function – the ‘data’ will contain the returning Json from our action call.  The next two calls use the jTemplate API to merge the Json data to the templated html, as shown below.

2. add the template to the view:

<script type="text/html" id="templateHolder">
    <table border="1">
    <tr>
        <th>
            First Name
        </th>
        <th>
            Email
        </th>
    </tr>
    {#foreach $T as record}
        <tr>
            <td>
                {$T.record.FirstName}
            </td>
            <td>
                {$T.record.Email}
            </td>
        </tr>
    {#/for}
</table>
</script>

<div id="jTemplateDemo">
</div>

 

One thing to keep in mind is to put this html in the script tag.  Alternatively you could load this template from another file as well.

With this approach we have created a very lightweight approach to passing data from the server to the client – the binding to the template occurs on the client.  If we used partial views, the binding process would occur on the server and transmit the payload with the html, increasing it’s size.  The lightweight json approach is critical especially in our ajax calls

Next post we’ll take this table and convert it into a ‘DataTable’.

I have included this code for your review – download here

Moving to JSON with Client Side Templating for Views

April 10th, 2010

I was Google ‘Buzzing’ today on this and figured I’d post the same here :

My new frontier in asp.net mvc (and hopefully asp.net 4) will be implementing templates and moving to a more rich client ‘json’ experience vs. partials views.

couple of resources:

http://www.west-wind.com/Weblog/posts/509108.aspx

http://weblogs.asp.net/dwahlin/archive/2009/04/17/minimize-code-by-using-jquery-and-data-templates.aspx

http://weblogs.asp.net/dwahlin/archive/2009/05/03/using-jquery-with-client-side-data-binding-templates.aspx

http://starterkit.jsonfx.net/

http://jbst.net/

The Telerik MVC controls use JSON I think behind the scenes.  They have source code – I am interested in evaluating that as well. (I’m using their controls, I mean evaluate as in see the source and how they implement their controls with JSON – in particular their grid control)

What you might appreciate here is that you could, in theory, use this approach as your view for any backend framework.

Also, I know ExtJS has some rich controls, they are all Json related, I think Phil Haack had an article on using mvc with ext.

Basically, today, if you add for example, an item to a ‘grid’, I go behind the scenes, add it – then redisplay the grid.  In these approached, you’d literally just append a row to the grid instead.  Very interesting.   The value is going to be less traffic, as partial views create more traffic.

I see this as well:
ASP.NET AJAX And Client-Side Templates by Dino Esposito:
http://msdn.microsoft.com/en-au/magazine/cc546561.aspx

The HTML Message Pattern by Dino Esposito:
http://msdn.microsoft.com/en-au/magazine/cc699560.aspx

Of course, this all assumes you opt for a rich experience with jSON/jQuery vs. something like Flex or Silverlight  :)

Telerik Extensions 1.0 Released for MVC

March 10th, 2010

Telerik has released their extensions for asp.net MVC .  I’ve used these extensions for a few projects and I really like the way they are setup.  These extensions are a set of html helpers for asp.net mvc 1.0 (and 2.0).

These controls are provided free as open source.  From the release notes:

1. New controls: TreeView, NumericTextBox components, Calendar, DatePicker

2. New Features: Grid grouping, editing and localization

3. Uses JQuery 1.4.2

Be sure to read the release notes to see all the functionality these controls provide.

Learn more (including demos).

Fantastic Friday – Links, thoughts and more…!

December 4th, 2009

Happy Friday to you  :)   I’m looking forward to my employer’s (Strategic Data Systems) Christmas party tommorow night.  It’s always a fun time.

SquareUp by Twitter

http://squareup.com/
Twitter founder formally unveils ‘Square’ project  – this is pretty cool I think – the ability to have “mobile-payments”.  

Here is a description:

The Square hardware is a small, inexpensive card reader that plugs into the audio jack of a compatible device, including a mobile phone (it’s starting with the iPhone and currently has job postings up for BlackBerry and Android engineers). It processes credit card payments, geotags their locations on a map, and e-mails a receipt to the buyer.

I think it’s a great idea – pretty cool stuff. 

Visual NHibernate Beta

At first I thought this might be ‘free’  :)   But it’s not.  However, I must say, it’s looking very nice.  Based on some NH google lists the developer(s) are very responsive to adding features and bug fixes.  That was good to see.  One of the ‘complaints’ that I hear sometimes about NHibernate (vs. like EF, L2S, or commercial ORMs) is that it’s complex to get up and running if your not familiar with how mapping files, etc… work.   So Visual NHibernate provides a visual designer and mapping tool for creating and editing NHibernate projects.

Ryan Cromwell – Castle Windsor

Not sure if I blogged on this before (yeah… I know I can search…) but I really like working with Castle Windsor’s Inversion of control container.  Ryan Cromwell (fellow contractor at Strategic Data Systems) provides a couple of good blog posts on it’s usage.  I was recently asked about factory facility for Windsor, and I was able to refer that person to Ryan’s post (see ‘Injecting WCF Channel as Dependency..’ below)

Strategy Pattern with Castle Windsor (he includes a sample project – thanks Ryan!)

Registering WPF “Views” with Windsor Fluent API

Injecting a WCF Channel as Dependency via Windsor – this shows off the Factory facility for Windsor.

By the way – a plug for Ryan:  He is our TFS specialist and can help setup, provide guidance, etc… for TFS.  If your looking for someone to do that for you – he is definitely the man to get!  I should add, he is a heck of a WPF programmer as well – he does some really fine work!

MVC Turbine – Plugin for ASP.NET MVC

http://mvcturbine.codeplex.com/

From CodePlex:

MVC Turbine is a plugin for ASP.NET MVC that has IoC baked in and auto-wires controllers, binders, view engines, http modules, etc. that reside within your application. Thus you worry more about what your application should do, rather than how it should do it.

This is very good to see from my perspective.  One of the features I really enjoyed while experimenting with Grails was how easy it was to have everything injected under the covers without needing to get into the weeds (in Grails case – Spring).  MVC Turbine offers this same functionality for the ASP.NET MVC programming.

Turbine is not exclusive to a particular IoC container.  Here is a feature list:

Features

  • Visual Studio 2008 Solution Templates for IoCs
    • Ninject
    • Castle Windsor
    • StructureMap
    • Unity
  • New runtime framework that allows extensibility
    • Blades (components) that are auto-registered and loaded at runtime.
    • Introduced the Core Blades to setup the basic runtime of an MVC application:
      • MvcBlade — wiring for MVC related components (Controllers, View Engines, etc).
      • WebBlade — wiring for System.Web components (IHttpModule, etc.).
      • RoutingBlade — wiring for the IRouteConfigurator implementation.
    • RotorContext that works with the Blades to setup the runtime.
  • Auto-registration of View Engines (VE)
  • Auto-registratrion of MVC Filters to support constructor injection.
    • Added new InjectableFilter attribute to associate a filter to an action.
    • Added support for IActionFilter, IAuthorizationFilter, IErrorFilter and IResultFilter
  • InferredViewResult handles inferred actions and reports HTTP 404 for missing actions.
  • Works with ASP.NET MVC in Mono

 

Service Orientation Requires Data Orientation

More and more the conversations are around SOA.  This one article at InfoQ stuck out to me regarding ‘service data’

Most of today’s SOA literature and implementations concentrate on defining business aligned services and rarely discuss the role and impact enterprise data has in the context of SOA

 

How to Uninstall – or make Message Stop loading up on Windows 7?

How to uninstall/remove Messenger on Windows 7 ?    My dad just got a new computer with Windows 7.  Anytime he starts it up, it wants him to sign in to Messenger.  He doesn’t use Messenger, and doesn’t want to use Messenger. 

What I find irritating is there isn’t any ‘don’t show this on startup’ or ‘turn this off’ within the Messenger pop-up.  At best you have to go out to the internet and start looking for hacks or ways to turn this off.

Microsoft – I don’t mind if you want to promote your own chat program in your OS, but please be kind enough to make it easy to turn off for non-computer expert users. 

Caliburn SL Nav Walkthrough/Intro

I’ve blogged in the past regarding ‘Caliburn’ by Rob Eisenberg.  Just a reminder:

Designed to aid in the development of WPF and Silverlight applications, Caliburn implements a variety of UI patterns for solving real-world problems. Patterns that are enabled by the framework include MVC, MVP, Presentation Model (MVVM), Commands and Application Controller.

Rob is in the process of ‘releasing various starter kits/samples for Caliburn’.  His first sample just recently released is :

Silverlight Navigation Walkthrough

Using jQuery to Scroll Just in Time for Paging Records..like Bing

Rob Conery blogs about using jQuery to scroll down a list of records with ‘just in time scrolling’ for paging.  Pretty cool – I have seen this feature used in different application.  I suspect this will become the defacto standard in paging lists.  Check out his how to here.

TFS Offline

Quote of the day… ‘Don’t work offline’.  I’ll keep the source of that quote unnamed, but I did think it was rather funny.  I hope TFS improves it’s offline capabilities.  This is very reminiscent of Visual SourceSafe – which I really didn’t like much.  SVN, Git, etc… all have pretty good offline capabilities.   While we are at it – I do hope TFS also integrates with explorer so if you edit a file outside of studio that it picks it up.  (Maybe you can, but I haven’t seen it).

UPDATE  I’ve been corrected that TFS does provide explorer integration with the  TFS power tools.

(My only response though… I was told this has been around since 2005… seems almost 5 years later this would be an installation option for TFS for Visual Studio ?  Guess you just have ‘know’ this is available – lol)

Google Docs

I am setting up my ‘Google’ realm of Wave, Gmail, Docs, Reader, etc… so far… I’m loving it.  Just recently I received an email with Excel spreadsheet.  Opened it up in Gmail, which prompted to use Google docs !  Worked out great.  And to share that document with my wife, I didn’t have to forward that document around.  Just share it exclusively to her.  All stored up securely on the Google cloud.

I did notice in the Excel to Google Doc conversion that lookups aren’t exactly the same, so it didn’t properly convert the lookup lists.  I hope they fix that.   I really see the world approaching of using this approach more and more.   With the cloud storage, feature rich word processor, spreadsheet and slide creation capability… who needs an expensive desktop copy of Office!

Steve’s Final ‘Thoughts of the Day’ – (or rather ‘Stirring the ORM Pot in the .NET world…’)

Douglass Starnes has a series on different data model approaches with asp.net mvc, showing how to setup them up and use them.

In part II of the series he makes this comment: 

In the ASP.NET MVC space I see three ORMs being used most commonly.  By far the favorite outside of Microsoft is NHibernate.  Inside of Microsoft there are two competing offerings: LINQ to SQL and Entity Framework.

This view/perspective – is it a correct one ?  Is Microsoft competing against NHibernate OSS .NET projects created by it’s own community ?  Or is Microsoft just giving more options ?  Microsoft doesn’t need to include NHibernate in any of it’s products – too many legal traps I’m sure.  What if it didn’t create it’s own ORM and merely demo’d features using NHibernate in it’s examples ?  I’m all for competition to make products better, but in this case, is MS having 2 ORM’s that are catching up in functionality, but still lagging behind NHibernate and other .NET ORM’s in the market a wise thing ?  Is that how you see it ?  I went to use EF in a project, but because it didn’t handle an ‘append only’ with ‘hilo’ id generation – and because it wasn’t poco based – where the entities are the domain objects – it was finally deemed impossible to use.  Meanwhile, we prototyped NHibernate and were able to implement everything needed in the Legacy system.  Personally, I want to pick the best of breed, not pick something just because of ‘who’ makes it.  

I don’t want to distract from his series, but that comment seems to be a prevailing one in the .net community.   What I wonder is ‘doesn’t Microsoft understand that is how it will be perceived’ – and if so… is their position to outdo the products, or do they consider this a core piece of the .NET framework to provide ORM solutions ?

I keep pointing to jQuery and ASP.NET MVC – they provide jQuery in the project templates for ASP.NET MVC.   How does that compare to including NHibernate support – or even just promoting it without including it ? 

Personally I can think of 3 examples of where they could make a difference:

1. Provide a Linq provider just like they did for EF and L2S (yes, there are Nhibernate linq providers in work – there is a basic one available now)

2. Provide a NHibernate DomainService out of the box for RIA.NET

3. Provide support for NHibernate out of the box for ADO.NET Data Services.

All three could be extensions that are referenced but included in each release.

Craftsmanship Dilemma:

Last thought… I was told to just ‘get something done’ basically… hack it.  No tests, no real design, just get it done now.  Do you think that is ok ?  How does that compare to craftsmanship ?  I don’t think I have to craft the perfect 100% solution, but how it gets built – ie. with a test, with some design/OO principles in place – shouldn’t we push back a bit to not just create ‘junk’ ?  I am noticing this trend in many industries.  Just ‘build the car’, doesn’t have to last, we need it cheap and now to compete.  At what point does quality matter ?  How would you feel if the rollercoaster your going to ride is built with that mentality?  Or the bridge ?  Or the airplane ?  Or how about the breaks on your car?  Why isn’t software engineers able to defend their craft in these situations ?  I guess it’s all about the $$$  ?  There is ‘agile’ … then there is ‘craftsmanship’…

 

Well, that is enough for the day – everyone have a great weekend!

Super Tuesday!

November 17th, 2009

One of my coworkers recommend combining some posts together than one a bunch of ‘one offs’ of links or news of interest.

I’ve accumulated a set of links, thoughts, experiences, etc… over the last few days (I’ve been busy). 

New Sharp Architecture Release

http://devlicio.us/blogs/billy_mccafferty/archive/2009/11/12/s-arp-architecture-1-0-2009-q3-with-nhibernate-2-1-1-ga-released.aspx

Basically Sharp Architecture is about as close as you can currently get to a Spring/Hibernate MVC architecture in .NET.  My last project used several pieces of Billy’s previous ‘NHibernate Best Practices’ that I retrofit for asp.net mvc.  Then, Billy helped put together Sharp Architecture!

A snippet of what Sharp Architecture is at the wiki:

Pronounced "Sharp Architecture," this is a solid architectural foundation for rapidly building maintainable web applications leveraging the ASP.NET MVC framework with NHibernate. The primary advantage to be sought in using any architectural framework is to decrease the code one has to write while increasing the quality of the end product. A framework should enable developers to spend little time on infrastructure details while allowing them to focus their attentions on the domain and user experience. Accordingly, S#arp Architecture adheres to the following key principles:

  • Focused on Domain Driven Design
  • Loosely coupled
  • Preconfigured Infrastructure
  • Open Ended Presentation

 

SpringSource updated to 2.2.1 includes new GSP Editor

I updated my SpringSource (STS) – (see more below about STS + Grails)
The update to 2.2.1 is here: http://www.springsource.org/node/2172

Grooy and Grails Random Thought

As a very well done project for building web applications…what is it’s popularity out in the world?  Are companies afraid of it?  Take NHibernate in the .NET world, in spite of it’s best of breed position, companies would rather use less to not use open source (the ‘it’s not from MS position’).  Is Groovy and Grails popular out there ?  If you do Grails/Groovy development – ping me please – let me know where your at, how you like it, etc… I’d like to see if it’s made much of a dent out there!

What I’m reading: ‘Grails in Action’ : Some Thoughts While Reading

 
Shout out to Manning for this e-book, love their setup, easy to purchase, prices are fair, many up and coming books on topics you don’t see in the mainstream yet!

Chapter 1 – good start.  Steps through the creation of a sample grails app.  Covers the basic commands.  Only issue I had was using the ‘file db’ – so I setup Grails to run on MySQL, which was a good exercise.  Tests still run in memory, which is good.  Final part was using prototype with taglibs to do some simple ajax.  I like how it starts by not bogging down into details, but getting something up and running.    

Highlights:

  • convention over configuration
  • removal of much of the xml configuration
  • testing built in.
  • Domain focus, code generated is clean and ‘pojo’.
  • Built in common functionality ie. prototype.
  • Good helper support with tablibs.

Chapter 3

…Chapter 2 was a nice overview of Groovy.  I’m now moving on to ‘Modeling the domain’:
This chapter covers
â–  What GORM is and how it works
â–  Defining domain model classes
â–  How domain classes are saved and updated
â–  Techniques for validating and constraining fields
â–  Domain class relationships (1:1, 1:m, m:n)

STS and Grails

http://www.grails.org/STS+Integration
Nice setup I’m using, shows how to create or import an existing Grails project into the workspace

I like the way that Grails provides integration tests as part of the framework that automatically handle transactional rollbacks.

I like the integration that STS does provide for Grails.  But I do think doing the work from the command line is faster and more efficient.  After adding new items, just refresh the Eclipse project and it’s there.  This is especially good for quickly running tests.

Grom

One thing I see in other frameworks (ie. asp.net mvc) is the concentration on views and controllers.  Whereas in Grails, I think the pattern all starts with the domain model.  Generate the model which has what I would call ‘built in DAO support’.  GROM makes life easier  :)

Validation

Grails validation is very well done, it’s built on a ‘constraints’ model with a built in validation DSL.  From Grails in Action:

static constraints = {
        userId(size:3..20, unique:true)
        password(size:6..8)
        homepage(url:true, nullable:true)
    }

This says ‘userid must be unique (in db) and be between 3 to 20 characters long’  – nice eh?

 

Software Craftmanship Manifesto


Did some pair programming last couple of days.. it was fun to say ‘whoa, this needs a new class here!’, refactor, make it more readable, etc… Must have been the next day I was shown this manifesto.  The only part that is still missing is the testing part, although some of the code is using legacy code that doesn’t lend itself well to testing… nevertheless, there is a real sense of accomplishment and success in writing code when there is craftsmanship put into it… so this manifesto is spot on!

http://manifesto.softwarecraftsmanship.org

 

How to start agile development in your team:

http://weblogs.asp.net/rosherove/archive/2009/11/16/how-to-start-agile-development-in-your-team.aspx

Thanks to Roy Osherove, as my current client was recently asking it’s team ‘are we agile’… From the link above:

    1. start doing daily stand up meeting
    2. start doing automated builds
    3. start working in pairs on relatively complicated problems
    4. start doing code reviews
    5. start showing visible progress
    6. start trying to show demos every two or three weeks
    7. start learning unit testing
    8. learn how to code better, design better
    9. start doing TDD

As a company, there are maybe 2 items here, as a team, more like 50% ?  I will say this: more and more it’s about the culture.  Happens everywhere, even on ESPN radio there was talk about the ‘culture’ on a team in the NFL, take a so-so quarterback, joins a new team, with a different culture, and he does well…(Denver Broncos) take a star on one team, move him into another culture… and he struggles…(Chicago Bears). 

More work needs to be done to promote a new culture in companies.  How to ‘sell’ to upper management who doesn’t seem to care ‘how’ you do it, as long as you go it… vs.  technical people in a company that totally reject anything new.   Where I’m at now, every new idea is really rejected, the company is fine with it’s ‘it was made here’ approach, but it is already showing it’s age and it’s big, bulky and hard to move it forward.  Some work was done to add some domain driven design concepts, add some tests, etc…  In the end… culture… If you haven’t watched ‘Pimp My Architecture’– watch it! 

Here is a related article from InfoQ:

Tips to Select a Pilot Project for Agile Adoption (InfoQ) :

One of the most important factors which influences the success of Agile adoption is the set of learnings derived by applying Agile to a pilot project. These learnings significantly influence the organization to go ahead with Agile or fall back to their usual process. This places a lot of emphasis on the selection of the pilot project. A wrong type of pilot could end up aborting, which would be a poor advertisement for the new process.

and

An engaged business sponsor can help the team if it needs to push against entrenched business processes, departments, or individuals. The time and energy of a business sponsor are critical to the success of the project…all these factors become meaningful with a strong team. Hence, choosing the right team is a precursor to all the above factors.

It takes a “strong/right” team with a mindset to embrace the agile methodology.  They later become the flag bearers for other projects within the organization.  

NServiceBus – Web Asynchronous Publishing


nservicebus includes an async pages sample.  Publishing a message asynchronous to a queue and it returned back to the page.  Get 2.0 beta – and learn how nservicebus works.  This brings to mind a lunch conversation today..SOA isn’t just ‘web services’ – there is much more to it.  NServiceBus helps provide a message based architecture.   

ie. Command Query Pattern

The command service publishes messages about changes to data, to which the query service subscribes. When the query service receives such notifications, it saves the data in its own data store which may well have a different schema (optimized for queries like a star schema). The query service may also keep all data in memory if the data is small enough.

Learn More

TCP Sockets, Chat Program

Don’t ask about this one.  I am working on some port listener code for a flying sim hobby I enjoy.

Good start …

Building a Chat Server

Building a Chat Client

… by the way… Groovy does it better  :)

s = new Socket("localhost", 8283)
s << "Groovy Rocks"
s.close()
 

(reference : http://gallemore.blogspot.com/2008/01/socket-client-for-groovy.html and Groovy Sockets: http://pleac.sourceforge.net/pleac_groovy/sockets.html)

 

asp.net mvc 2 beta released at PDC


http://haacked.com/archive/2009/11/17/asp.net-mvc-2-beta-released.aspx

Here are some highlights of what’s new in ASP.NET MVC 2.

    * RenderAction (and Action)

    * AsyncController

    * Expression Based Helpers (TextBoxFor, TextAreaFor, etc.)

    * Client Validation Improvements (validation summary)

    * Add Area Dialog

    * Empty Project Template

I hope to see some ‘grails like’ command line scaffolding and richer domain class support in upcoming versions.   In my post there, Phil says ‘Version 3’… so.. stay tuned!

I’m really glad to see Microsoft continuing this project, it’s a breath of fresh air – I have a 1-1/2 year project that is using it and I never grow tired of the technology part of it.   

LifeCycle Data Services (LDS)

 

Huh?  :)   This is one a bit out of my normal range, but I was curious about an InfoQ article talking about Flex/Flash/AIR, etc… and one of the tools they are making is LDS.   LDS is about domain modeling.

And so the way it works is that, we have a model that becomes the centre of the universe, if you want, of the server-side developer and you create a model that represents your data. You can create it from scratch or you can introspect the database as a starting point

…

There is a new plugin that you add on top of Flash Builder: that is the Model Designer. The process that I just described here is actually done within Flash Builder in a kind of a visual way; so we have a visual model editor. In that model, it’s more than what you typically do in a pure data model – you can add constraint and validation rules, you can specify things that typically you would have to specify again and again in view components

…

Once you create your model, you deploy the model and basically you don’t have to write server side code because, based on the model, we have enough to really provide a persistence layer

Nothing new here right..? Well, what caught my eye was that they are using Hibernate (my bff) !!!  So, even Adobe is hopping into the mix here :)

Behind the scenes, this is implemented using Hibernate – the persistence layer is provided by Hibernate – and then we also do some code generation on the client side, again the value objects and the service proxies. The key point is that the foundation for that is still the data management service

There you have it.  Now if we can just get Microsoft to embrace NHibernate and see the light…  :)

And last…. but not least… I saved the best for last:

Slashdot post: ‘Less than Free’

 

On the day that Google announced its new service, the stock in the two companies that had controlled the market for map data, Garmin and TomTom, dropped by 16% and 21%, respectively. (Those companies had bought Google’s erstwhile map-data suppliers, Tele Atlas and NavTeq, in 2007.)

Read more about ‘the strategy behind Google’s releasing turn-by-turn mapping for free…’ .  Wow.

Error Logging Modules and Handlers for ASP.NET (Webform/MVC)

June 6th, 2009

I just implemented ‘Elmah’ for my ASP.NET MVC project.   I’m using the SQL logging feature (a script comes with the download).  A sample with asp.net webforms comes with the download.

I followed Darrell Mozingo’s blog post here http://darrell.mozingo.net/2009/02/19/elmah-with-aspnet-mvc/ for setting it up with asp.net mvc.

Additionally I used Dan Swatik’s excellent post on integrating Elmah  using the controller/action  ‘HandleError’ attribute to customize the HandleError attribute (see ‘Action Filtering in Mvc Applications’)

ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.

Once ELMAH has been dropped into a running web application and configured appropriately, you get the following facilities without changing a single line of your code:

  • Logging of nearly all unhandled exceptions.
  • A web page to remotely view the entire log of recoded exceptions.
  • A web page to remotely view the full details of any one logged exception.
  • In many cases, you can review the original yellow screen of death that ASP.NET generated for a given exception, even with customErrors mode turned off.
  • An e-mail notification of each error at the time it occurs.
  • An RSS feed of the last 15 errors from the log.

Check out the Elmah Wiki writeup by Simone Busoli for a good overview of the features.

Basically I signal all my errors (using a custom Exception object) to Elmah to help assist in an easy way to write errors to SQL, send emails out, and provide a rss feed of the errors.   (I am still using Log4Net, but might just convert everything to Elmah)

This is a ‘must have’ for an asp.net application.

ASP.NET xVal Library with DataAnnotations

May 17th, 2009

Recently I setup a new asp.net mvc application.  After reading Steve Sanderson’s new book – in which he refers to his xVal library, I figured I’d take a look at it.

The main features of the xVal library is it’s ability to apply validation that executes on the server side, as well as the ability to apply client side validation using the same technique.  This is quite powerful.

On the client side, you can use the native asp.net MS library, or jQuery. 

On the server side, there are also options available: DataAnnotations, Castle Validators, or even further, you can write your own IRulesProvider and attach rules programmatically.

I won’t go into ‘how’ to use the library, as Steve has given a great walk through here: xVal – a validation framework for ASP.NET MVC

The second part is the DataAnnotations – which I was glad to have investigated some of Silverlight 3 to understand the concept.  As mentioned in this post by Brad Wilson (DataAnnotations and ASP.NET MVC), “in .NET 3.5 SP 1, the ASP.NET team introduced a new assembly named System.ComponentModel.DataAnnotations…”

I think the real value here is this ‘buddy class’ concept that lets you use validation attributes on code generated classes, ie. Linq to SQL/Entity Framework.  Basically you can add attribute metadata to the generated classes in partial classes.  An example of this can be found here, Integrating xVal Validation with Linq-to-Sql

This is very powerful, in particular how the xVal library gives a developer several options to help apply validation to the model classes.

Great stuff  :)

Maarten Balliauw on ASP.NET MVC Best Practices

May 6th, 2009

Maarten Balliauw shares some best practices on ASP.NET MVC

  • Use model binders where possible
  • Be careful when using model binders
  • Never re-invent the wheel
  • Avoid writing decisions in your view
  • Don’t do lazy loading in your ViewData
  • Put your controllers on a diet
  • Compile your views

Thanks Maarten