Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Saturday, May 29, 2010

Test driving the TekPub ASP.Net MVC2 Starter Site

I like starter sites… we use one I put together at work (I called it BlankSolution).  They make it really fast to get up and running on a new project, AND to carry over improvements and best practices from project to project.  They are also great for learning.

Rob Conery released an MVC 2 starter site recently which looks really interesting.  Go check it out to see all the goodies it includes… then come back here to read about my experience using it to build up a real project (the NCharlie Task Board of course!)

Here we go, step by step (I’m following Rob’s blog post announcing the 0.5 release):

1. Download the bits from CodePlex, extract the zip and open the solution.  Screeeech… error opening in VS 2008.  Something about a bad pointer in the Web.csproj file to MSBuild “v10.0” WebApplicationTargets.  A quick edit to the csproj file (changed v10.0 to v9.0) fixed that (I won’t be forking the starter project for fixes if I find them… just want to see how quickly I can get up and running tonight.)

2. Set up the app to use SubSonic (the ORM tool Rob wrote).  Using Subsonic is a “for now” choice, to quickly build up the database from POCO domain classes.

- Global.asax.cs needs one change, on line 135.  Change “SiteEFSession” to “SubSonicSimple”.

- SubSonicSimple.cs needs one change, on line 18, add the name of the connection string the app will use, “SiteData”.

- The Web.config file doesn’t need to change, as long as your local database instance name is “SQLEXPRESS”.

3. Add a new Class Library project to the solution to hold the domain classes.  I called it “Core”.  Make sure to add the “Core” project to the “Web” project’s references.

(Side note: If you read through the comments on Rob’s getting started post, he ripped some guy a new one for suggesting he put his domain entities in a separate project, and add separate “Model” classes that map between the Core and the UI… so proceed at your own risk!)

- Add the domain classes:

Domain-objects

4. Modify HomeController.cs:

- Add ISession as a private, injected member.

- Grab all the Board records from the database, ordered by Board name, and paged

public class HomeController : Controller {
private ISession _session;

public HomeController(ISession session)
{
_session = session;
}

public ActionResult Index(int? page) {
var boards = _session.All<Board>().OrderBy(x => x.Name);
var list = new List<Board>(boards);

return View(list);
}
 

5. Control-F5 to build and run the site… it builds, but:



Error-screen


6. I had some problems.



- First, my SQL Server instance is version 2005… Rob’s Site.mdf file in the App_Data folder is v655 (2008 I think), and it would not open.  I created a new “SiteData” blank database on my local instance, modify the connection string in Web.config, and tried again.  Same beautiful error screen I got before.


- Second (I looked in the Event Viewer for this exception), I found this in the exception detail:


Exception information:
    Exception type: InvalidOperationException
    Exception message: Can't decide which property to consider the Key - you can create one called 'ID' or mark one with SubSonicPrimaryKey attribute

…so, I added an “ID” property to by Board class, and tried again.  Error screen.

- This time the “Index.aspx” view is expecting the model to be “Web.Model.User”, and I’m passing it a list of Board entities to choke on… that makes sense.  So I changed the “Inherits” directive at the top of Index.aspx to expect IList<Core.Domain.Board>, and removed the one “EditorFor” statement on line 35, and…

Starter-home 



It’s alive!  It took me almost 2 hours to follow Rob’s getting started post to this point… I didn’t get to the part about switching SubSonic out for EF or LinqToSql.  I’ll leave that, and making this into an actual Task Board, for next time.

Saturday, April 10, 2010

NCharlie Task Board – MVC Version

It’s unfortunate that paid work has to take precedence over fun blog projects like this… but that’s life!  I have an hour or so tonight, so I’m jumping back in to this task board project.

UI.Mvc-project-tree

Last time (February, ‘10!) I wrote about the Webforms implementation of the task board.  That was a good exercise for me, because I’ll be able to take many of the patterns and tools from that little project directly into my “for pay” projects, which are still all Webforms.

This MVC version will take up more than one post; I will try to keep the posts a bit shorter, and I want to record the implementation details with enough depth that I’ll be able to use these notes later to quickly ramp up my team on MVC projects when we get there.

This (image at right) is the initial project tree from Solution Explorer.  You can see some of the same elements from the Webforms version (AutoMapper, StructureMap, a Master page, an NHibernate configuration file and TransactionBoundaryModule that implements the “Session per Request” pattern for data access operations.)  This UI.Mvc project references the same “Core” project that the Webforms project references.

To quickly get started with the “Model-View-Controller” pattern in this project, I created the TaskBoardController class and added one ActionResult method named “Index”:

public ActionResult Index()
{
var board = new Board("My hard coded test board", 1, 1);
var column = new Column("Col1", board);
var task = new Task("task1", column);

var model = new[] { Mapper.Map<Board, BoardViewModel>(board) };
return View(model);
}



You can see it just creates a new, hard-coded task board entity, maps it to the BoardViewModel class, and returns it.



To quickly create a View page that will accept this ActionResult, I right-click on the method name “Index” and choose “New View”:



add-view-context-menu



This brings up the Add View wizard, in which I can create a new ASPX view file that is strongly typed to my BoardViewModel class, uses the Master page for my project, and puts in some initial code to display the data:



add-view-wizard



I chose “List” as the View content type, because that selection assumes I will be returning an enumerable list of models, and puts a “foreach” loop into the ASPX page (I’ll use that code later as I build up the task board… where I used the ASP Repeater control in the Webforms project, I’ll use “foreach” to create the correct HTML in this MVC view page.  This is pure code-generated quick and dirty programming… which I think is dangerous if you don’t use it correctly, but valuable for quickly understanding the ingredients in an MVC web app and getting started with a screen quickly.  Even though this view of the BoardViewModel doesn’t look anything like a task board yet, I think it is useful as an exercise:



code-generated-view



To see the generated code, check out the HTML in the Index.aspx file that creates this view.  I tagged this code in source control as “MVC quick start”.  Next, I’ll do things right and create some tests that define a set of actions and expected behavior for the TaskBoardController.

Sunday, February 14, 2010

Resurrecting NCharlie

We delivered some software at my day job last week that has been keeping me pretty busy for the past few weeks.  To celebrate, I am revving up the NCharlie project again to buzz out some things I picked up in Austin last month.

I’ve already spent some time integrating StructureMap, Automapper, and Fluent NHibernate into a task manager Webforms application that uses the patterns I learned last month in bootcamp.  Here’s what I’ve got so far:

NCharlie-TaskBoard

We’ve been using a “task board” like this at work to move our development tasks through to deployment.

I know, the CSS needs some work… but the thing is working!  Here’s what I’ve done so far:

  1. Started a new blank solution for NCharlie in Visual Studio 2008.
  2. Added .Net 3.5 projects for the Core NCharlie project, a Webforms UI project, an MVC UI project (using ASP.Net MVC 2 RC 2), Integration and Unit Test projects.
  3. I put the blank NCharlie starter project (no entities, tests, views… just the architecture) into a branch tagged ncharlie-starter.

As of tonight, the version in the trunk of the NCharlie repository matches the starter project.  My plan is to build it up using a branch per feature, and blog about it as I go.  I plan to mirror the functionality using Webforms and the MVC framework.  I think it will be a good way for me to cut my teeth on MVC, plus it will be interesting to compare the two when it is done.

Friday, January 15, 2010

MVC Bootcamp takeaway

I just finished three days of Headspring MVC bootcamp training with Jimmy Bogard.

Impressions:

Great training, I would highly recommend anything these guys offer. I enjoy a fast pace, hands on (lots of programming exercises) style of training, and that's what I got. Jimmy is a good teacher... I already knew that, since I've been reading his blog for the past year or so and I've picked up a lot a good pointers to things that help me in my work. He is also a good communicator teaching in front of a room full of diverse programmers. If you are new to MVC like I am, this course is great for introducing concepts that may be new to web forms programmers... but like the MVC book that Jimmy co-authored, the class goes way beyond the introduction by showing how they leverage some of the features in MVC (ActionFilters and ResultFilters, HtmlTemplates, Model binding and validation...) to build applications quickly that are easier to maintain. We used the release candidate of ASP.Net MVC 2 in class.

Takeaway:

We use ASP.Net web forms at work, and I don't think we will change to MVC in the near future. Maybe at some point in the next year - I'm not sure yet. I knew that going into this class, but I also hoped I would learn about valuable patterns and tools that we can use right now (yes, even in web form development) that will make us go faster or that will make our apps easier to maintain. My hopes were not dashed... here is my list of "valuables" (this list is more for me and my team... but if someone else gets something out of it, great!):
  1. Model Binding - this seemed magic to me at first, and comes for free in the MVC framework. When a form posts to the server, the action method ("event handler" for us web form devs) that accepts the post takes the payload in as a parameter... which is already mapped to a model class. No tedious "model.FirstName = txtFirstName.Text" code to write. This would be nice to have in our work... there may already be something similar in web form development that I just don't know about. If not, I don't think it would be much work to write some convention-based code that does this type of work for us.
  2. ViewModel validation using property attributes - we write a lot of repetitive code that validates email addresses, phone numbers, department numbers, etc. It would be nice to be able to put an attribute on a property in our ViewModel class (for example, "[EmailAddress]" and have the form post automatically check these for us.
  3. Html builders - the RC version of ASP.Net MVC 2 has helper methods like "Html.EditorFor(x => x.FirstName)" which spit out the label, text box, and validation message element for a property called "FirstName" on a view model. We do something similar with user controls for our pages... but we could do a lot better, and the implementation in MVC gives me some ideas. MVC 2 even has an "Html.EditorForModel()" method that will render the entire collection of form controls needed for a particular view model. Handy!
  4. Use an IoC container like StructureMap - we have been using poor man's dependency injection for a few months now, but we need to step it up and use the factory pattern to do the heavy lifting for us... if a presenter/controller class needs an IPersonRepository, get it from the factory. Stop explicitly injecting it when the controller is requested.
  5. Use AutoMapper to map domain models to view models. Jimmy is right, mapping code is tedious to write.
  6. Move to NHibernate. I've been gently moving our team away from classic data access layers with ADO.Net for the past year. We use a really simple, in-house ORM that I wrote (yes, I know... I re-invented the wheel - but it seemed the best way to transition) that reduces the number of stored procedures per project by ~90%. It is time to go all the way, so we can realize the performance, maintainability, and code-quality benefits NHibernate will bring.
  7. Lighten up our presenter/controller classes. These are still pretty heavy in our team... something Jimmy showed us, and I will be looking up in CodeCampServer, was using the Strategy pattern to execute commands when a form requests something. For example, a form posts to the server and needs to save data... CodeCampServer uses an "ExecuteCommand" method to pass the ViewModel payload, and the domain entity type, to another class that handles the work of mapping and persisting.

I'm sure I am forgetting something... I took good notes though that I'm sure will be printed and worn out over the next months. Thanks for a great class Jimmy!