Send mail to the author(s) E-mail

# Monday, 15 February 2010

Both my web hosters advertised they are hosting on Server 2008, which meant IIS7.  This makes things much easier when publishing an MVC site (to do with routing apparently).  As I’d hosted my sites for years with these providers, they were still on Win2003 (IIS6) boxes.  I just had to ask for an upgrade and it was done.

Upload to IIS7 and it just works!

The first step was to see if routing worked on the default website.. it did!

The next step – to publish up the NerdDinner app I’ve been going through on Rob Conery, and get the database connected live.


The crowd goes wild  - this is live and connecting to a database :-)

Changing Namespace / Solution Name / Project Names

I had lots of namespace errors.. forgot to change default assembly namespace, which meant linq to sql was in the wrong space.  However it is possible to change everything very quickly – solution, project names, directly.  One gotcha was remembering to delete everything on the live server so there weren’t 2 dll’s with the same object names inside..

Changing Default Page to Activity / upload live trick

"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Activity", action = "Index", id = "" } // Parameter defaults

Change controller = “Home” to controller = “Acitivity”

I also implemented the copyifnewer.bat trick for easily going from dev to live which is here:

Run application working live with Create, Read, Update and Delete working.  Also validation, which comes for free in the standard templates.


DropDownList and Postbacks – covered in another post on this site.

Summary Page

I created another link in the master page for menu item:


For the summary page I’m considering a ViewModel approach.

Lets see if a simple new Summary controller will suffice

Got to a stage.. was going to upload to github, but had db connection strings in there which didn’t want in the history.. so looked at rebase in git.. want to make sure before I play too much :-)


Creating a SQL View then Displaying it

Michael came up with an elegant solution which I’m trying.. so creating a SQL View:

SELECT     personid,    
DATEPART(week, date) AS Week,
DATEPART(year, date) AS Year,
SUM(kilometres) AS kilometres,
SUM(hours) AS hours
FROM dbo.Activity
GROUP BY personid, DATEPART(week, date), DATEPART(year, date)

which gives a good summary output:


The aim is to be able to see the summary of each week like this (this is the old webforms version)


linq to sql generated classes off the view.

Michael did it like this:


I’m on this:


Passing Complex Data – Lists within Lists

As each person has data associated to them, a list within a list is good.


public class WeekSummary
public int Personid;
public string Personname;
public List<WeekSummaryData> Persondata;

public class WeekSummaryData
public double? Hours;
public double? Kilometers;
public int? Week;
public int? Year;

Then in the repository:

public IQueryable<WeekSummary> GetWeeklySummary()
var weekSummaries = from p in db.Persons
orderby p.personname
let data = GetWeeklySummaryData(p.personid)
select new WeekSummary {Personid = p.personid,
Personname = p.personname,
Persondata = new List<WeekSummaryData>(data)};
return weekSummaries;

IQueryable<WeekSummaryData> GetWeeklySummaryData(int personid)
var summary = from w in db.weekly_summaries
where w.personid == personid
orderby w.Year , w.Week
select new WeekSummaryData {Hours = w.hours,
Kilometers = w.kilometres,
Week = w.Week,
Year = w.Year};
return summary;

** understand this linq

Then in the controller:

public ActionResult Index()
var summaries = _repository.GetWeeklySummary();
return View(summaries);

and the view:

** understand this rendering

<% foreach (WeekSummary weekSummary in Model) {
<% foreach (WeekSummaryData weekSummaryData in weekSummary.Persondata) { %>
<th><%=Html.Encode(weekSummaryData.Week) + "/" + Html.Encode(weekSummaryData.Year) %></th>
<%=Html.Encode(weekSummary.Personname) %>
<% foreach (WeekSummaryData week in weekSummary.Persondata) { %>
<td><%=Html.Encode(week.Hours) + "hrs" %><br /><%=Html.Encode(week.Kilometers) + "kms" %></td>
<% } %>


refactor code with an interface for testing

unit test do



tooling to help make form crud websites faster…

reproting tooling


| | # 
# Thursday, 11 February 2010

While pair programming with some great developers I asked the question:  How would you refactor this project (the running project website).

When both of the guys I paired with suggested that it would be smart to move to MVC and to use an ORM, I listened.

After downloading ASP.NET MVC version 1.  I’ve been working through the tutorial from Rob Conery: (about 80mins)

Creating a New MVC Project

Ctrl Shift N

Linq to SQL


going to use Membership for login / users.

In models, add new item: LINQ to SQL

drag on the two tables


Original table name was dinners.  The class is called dinner

Renamed NerddinnerDataContect to DB, and context namespace to Nerddinner

however Entity Namespace to Nerddinner.Model – which didn’t work!  I left it blank.

Adding a Controller

The default Index controller

var db = new DB();
var dinners = db.Dinners;
return View(dinners);

Adding a View

right click inside method in controller

Create strongly-typed view

View content – code gen nice.

Tooling figured out which is the primary key (as linq to sql)


ModelBinders - Add

When creating a new Dinner, we use ModelBinders.. mvc looks at the Object and sees if it can bind to the linqtosql.

Could have used the existing FormCollection, but this is easier!

If ModelState.IsValid   .. nice.


And by changing the Html.ValidationMessage


Editing Data

In the controller:

public ActionResult Edit(int id)
var db = new DB();
var dinner = db.Dinners.SingleOrDefault(x => x.DinnerID == id);
return View(dinner);

This is another way of expressing the above:

public ActionResult Edit(int id)
var db = new DB();
//var dinner = db.Dinners.SingleOrDefault(x => x.DinnerID == id);
var dinner = (from a in db.Dinners
where a.DinnerID == id
select a).SingleOrDefault();

return View(dinner);

<% gator tags

Other view engines – Spark or nHaml


So we’ve built scaffolding.


We want /dinners to the be root of the site.

Routing is the thing that listens for URL’s and passes them to a controller.

eg Dinner / Edit /5

eg { controller} / {action} / {id}

To change to be /dinners as the route in global.asax

static public void RegisterRoutes(RouteCollection routes)

"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {controller = "Dinner", action = "Index", id = ""} // Parameter defaults

We changed from Home to Dinner above.



public ActionResult Delete(int id)
var db = new DB();
var dinner = (from a in db.Dinners
where a.DinnerID == id
select a).SingleOrDefault();

return RedirectToAction("Index");

are wired up on the view:

<% using (Html.BeginForm("delete", "dinner")) {%>
<%=Html.Hidden("id",Model.DinnerID) %>
<input id="Submit1" type="submit" value="delete" />
<% } %>

We are not using any authentication to stop people doing this at the moment. For that we need:

public ActionResult Delete(int id)
var db = new DB();

Testing / Repository Pattern

Because the controller has database connection inside of it, this isn’t good from a testing point of view, so we’re going to refactor this out.

Speed would be a problem with lots of tests, as would not knowing what is in the database.

Created an IDinnerRepository interface:

public interface IDinnerRepository
IQueryable<Dinner> FindAllDinners();
Dinner GetDinner(int id);
void Add(Dinner dinner);
void Update(Dinner dinner);
void Delete(Dinner dinner);
void Save();

Then a SqlDinnerRepository that implements this, where the constructors calls the DB:

public class SqlDinnerRepository : IDinnerRepository
DB db;

public SqlDinnerRepository()
db = new DB();

public IQueryable<Dinner> FindAllDinners()
return db.Dinners;

public Dinner GetDinner(int id)
var dinner = (from a in db.Dinners
where a.DinnerID == id
select a).SingleOrDefault();

return dinner;

Then in the Dinner Controller:

public class DinnerController : Controller
IDinnerRepository _repository;

public DinnerController()
_repository = new SqlDinnerRepository();

// this will be the one that the test uses
public DinnerController(IDinnerRepository repository)
_repository = repository;

// GET: /Dinner/
public ActionResult Index()
//var db = new DB();
//var dinners = db.Dinners;
var dinners = _repository.FindAllDinners();
return View(dinners);

The plan is that we will make up something that implements IDinnerRepository when testing to make our life easier.


Made: FadinnerkeDinnerRepository

Made: DinnerControllerTests

Ctrl R T – Run tests

Found error in test code:

 //var data = result.ViewData.Model as IList<Dinner>; // this didn't work.. hmmmmmmm.
var data = result.ViewData.Model as IEnumerable<Dinner>;


Made a test that dinners should only return dates that are today or later:

public void Index_Should_Return_Dinners_For_Today_Or_Later() {
// Arrange
var controller = new DinnerController(new Fakes.FakeDinnerRepository());

// Act
//ViewResult result = (ViewResult) controller.Index();
var result = controller.Index() as ViewResult;

// Assert
var data = result.ViewData.Model as IEnumerable<Dinner>;

Failed the test, then wrote the code which was in the DinnerController:

var dinners = _repository.FindAllDinners().Where(x=>x.EventDate >= DateTime.Now);


Lambda expressions

var dinners = _repository.FindAllDinners().Where(x=>x.EventDate >= DateTime.Now);


Presentation Model Pattern or View Model

45min into Rob’s video.

| | # 

No error.  Just closes when using ASP.NET MVC

then onto:

Have tried the one above, which seems to work so far.

[Edit] it didn’t.. so now I’m trying this:

Something still weird as locking up when loading assemblies (looks like resharper)  am trying resharper5 beta2 to see if that helps (haven’t got correct license).  I can get around lockup by deleting dlls from bin and obj.

| | # 
# Wednesday, 03 February 2010

When using a shared hosting provider, and only have access to 1 MSSQL database, it is possible to have 2 different web applications hanging off the same database.

The users seem to be different, however the roles are across all applications.

In VS2008, press the hammer and world icon:  as long as the web.config is pointing to the live database, you can change the live data.


And if you’ve a different project eg


You can do the same thing and connect to the same live database.


Here are roles from 2 different webapps.  Coach and runner;  then administrators, power users, and users.

App_Data Database

This was useful when sending the code to others, so they don’t have to manually make a new database.

<add name="LocalSqlServer" connectionString="Data Source=.\SQLEXPRESS;Integrated Security=True;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;User Instance=True"  providerName="System.Data.SqlClient" />

| | # 
# Tuesday, 02 February 2010

This helped me a lot understanding how various components worked in my application:


Some obvious omissions included no regex validation on time edit/add.

| | # 

Great video tutorial on:

Nice look and feel, however can’t find the source for the graphics.

Click the little hammer and world to bring up the Web Site Administration Tool.

Click show all to view the ASPNETDB.MDF

By Default it puts it in an MDF file in App_Data which is a SQL Express powered db.


Use Forms Authentication:


Enable Roles (groups of users):


Add some roles:


On Default.aspx, Anonymous Template:


Forgot password:




Protecting a directory:


My spike showed exactly how all this works.


To get this to work live however (my hosting company doesn’t like me uploading MDF files!).. I need to put the tables into my database.  So, can use Database Publishing Wizard, or now it is included in VS2008.




So this just created tables/views/SP’s in a new db – I used Membership1 as a test db.

Upload the tables after dumping out the SQL to a text file and got the following errors:

Msg 468, Level 16, State 9, Procedure aspnet_UsersInRoles_AddUsersToRoles, Line 45
Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation.

Easiest way was to look at the script and search for all occurrences of:

COLLATE SQL_Latin1_General_CP1_CI_AS

and replace with nothing.


Need to tell the current membership provider where the data store is.


       <remove name=”LocalSqlServer”/>

        <add name="LocalSqlServer" connectionString="Data Source=DAVEXPLAPTOP;Initial Catalog=membership1;Persist Security Info=True;User ID=runuser1;Password=runuser1" providerName="System.Data.SqlClient" />


| | # 
# Thursday, 28 January 2010

Am using publish web.. and automated build script so web.config is correct for dev and live.  Needs to be a Web Application, and not a Web Site.

Differences between Web Sites and Web Applications

Also if doing more than one pre-build call need to do this:

call "$(ProjectDir)copyifnewer.bat" "$(ProjectDir)web.config.$(ConfigurationName)" "$(ProjectDir)web.config"
call "$(ProjectDir)copyifnewer.bat" "$(ProjectDir)LoggedIn\web.config.$(ConfigurationName)" "$(ProjectDir)LoggedIn\web.config"

Also I got an error in dev, where my debugging wasn’t working properly.  Had to tick debug info to full here.


to do – possibly abstract out the connection string settings (and anything else dev/live specific) into another file, so the actual Web.config can be changed by VS easily.

In Visual Basic the interface is slightly different however it is in there!

| | # 

Spikes are great.. aim to try things very fast to prove things work. KISS!  These are all on

Hello World

Web Application, view it locally, view it on live server.

Locally is fine.  For live I’m on a shared server, and have to remember to create a new virtual directory (clicking Web Directory below)


Setup VS to publish the site (in Build menu).. use this syntax:

to avoid having to type in password each time!


Alt B H enter, to publish to live site quickly.

Connect to the Database

print something on the screen from the SQL Server..locally:

Aim is to print off a list of Persons:


Simplest way to do this is:


Put on a grid and wire it up:

Publish live, and it wont be able to find the correct connection string:


Went into web.config and commented out the local one, and put in another for the live server.

<!--<add name="RunConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Run;Persist Security Info=True;User ID=runuser1;Password=runuser1"  providerName="System.Data.SqlClient" />—>

    <add name="RunConnectionString" connectionString="Data;Initial Catalog=mateer;Persist Security Info=True;User ID=mateeruser;Password=secret"  providerName="System.Data.SqlClient" />

Its also useful to be able to connect to the remote database directly:  My host makes you open its firewall rules a week at a time from here: or



The SqlDataSource data source control represents data in an SQL relational database to data-bound controls. You can use the SqlDataSource control in conjunction with a data-bound control to retrieve data from a relational database and to display, edit, and sort data on a Web page with little or no code.

However this bypassing the tiered approach, and is essentially putting all logic in the webpage!

In Project Run I ended up using ObjectDataSource (to connect to the underlying architecture allowing me to use data Web controls such as GridView, DetailsView or DataList).  Picture from:


<asp:SqlDataSource ID="PersonsDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:RunConnectionString %>" 
        SelectCommand="SELECT [personid], [personname] FROM [Person]">


Changing the header titles, colours

Sorting and paging work as data is into a loosely-typed DataSet.

Could use a DataReader (instead of a DataSet on the SqlDataSource) which is simpler, but no sorting, paging.

Add / Edit / Delete – Need to add those into the SqlDataSource.  Very easy to make Edit and Delete.


Harder to make an insert.. see here for ‘workaround’ and discussion:


Provides greater flexibility – render using templates.  This will emit a <table><tr><td> syntax.



Renders nothing other than what you tell it.



View one record at a time, and very easy to get a new record.  Built in paging.



Same as details but less rigid layout.


3.5.. provides more control over markup.  Easy insert




new in 3.5 too.  The First, Previous, Next, Last control.


Enabling split view vertically.. very cool.



| | # 
# Wednesday, 27 January 2010

This is a series of posts about an existing fun project of mine which I’ve decided to refactor,to see how

  • Elegant I can make the code
  • Example of the ‘journey’ of refactoring
  • Working with other great programmers.

Project Run started a few years ago when myself and Pete were training for the St James Race.  This is all real, and we completed the race!

Elevator Pitch

Runners can record their training online. The coach can easily see their recorded training, and can make notes. It will be motivational and competitive for the runners to see what they have done. It will show how long to go before the event they are training for.



Stories / Requirements

Star * means most important stories that will be developed in version 1.

1) *Dave is a runner. He goes to the website logs in, and enters in the run he has just done. Twice round Hagley Park. 13kms. Took 1:20. Perceived effort - Steady

2) *Pete is a runner. He has just done a Port Hills run. 1:30. Uphill sections were Moderate to Mod Hard. Flat and downhill were Steady.

3) *Chris is the coach. He goes to the website, logs in. Then looks at Dave and Petes past weeks activity. He makes overall notes for both of them. He makes specific notes for Dave.

4) *Dave logs in and is proud to see he has completed this weeks training goals of 40km and 10 hours.

5) *Pete logs in and sees that his progress has improved because 4 weeks ago he did 40kms and was ‘Tired’ at the end of the week. Yet this week he has done 60kms and is feeling good.

6) *Dave logs in and puts in that he did 2 hours of mountain biking covering 30kms.

7) *Pete logs in and puts in 1 hour of Yoga.

8) *Dave logs in and adds in the 10mins of stretching he did to the run he just entered

9) *Dave logs in and makes a mess of things, and wants to delete todays run, which he puts in as 2009.

10) *Dave adds in a note to a previous day about running with food. He likes leppin and is going to try other stuff.

11) *edit

12) *Chris goes to website and has forgotten his password. The system sends a new one to his email account.

13) Chris logs in and easily alters the training plan for Pete and Dave.

14) Dave logs in and puts his max heart rate in, average, max speed, average and time in each training zone.

15) Dave uploads data using his watch to the website.


Was 2 weeks.  This included working with a great designer (Nora).

UI Design

Working from paper sketches, where the design goal was simplicity, therefore only 2 real pages to the site.  Nora does Photoshop mockups..


Architecture / Methodology

.NET2 Webforms hosted on a shared cheap hosting solution.

SQL Server2005

TDD Test first then write code - nUnit.

Controls used (I wanted to know how much comes out of the box in .NET, and how much I could leverage).. used these as a  result of successful spikes (see below)

  • Membership
  • Login / Password recovery
  • Master Pages
  • Data Grid
  • Repeater
  • Validation
  • Menu builder
  • Themes

2 Tiers:


Source control was Subversion, now I’ve moved to GIT.

Spikes (UI)

Here is a snapshot of the code right now before I do any more refactoring:

To remind myself how these front end UI controls work… going to create new blog post for these spikes.

Spikes (BLL/DAL)

Used TDD as much as possible to drive features

Development Process

Project timeline – used a word document

Bug tracking – word document.

Got code live as soon as possible, and to ‘clients’ as soon as possible for feedback.

| | #