Wednesday, August 27, 2008

Microsoft recently released the ASP.Net Model View Controller framework (MVC).  It is currently available as Preview 3 and can be downloaded at http://www.microsoft.com/downloads/details.aspx?FamilyId=92F2A8F0-9243-4697-8F9A-FCF6BC9F66AB&displaylang=en

A new MVC project contains a couple sample views and controllers so you can get an idea of the proper syntax to use. 

This article builds on the application created in my last ASP.Net MVC tutorial.  If you have not already done so, please follow the brief states in the previous MVC tutorial before beginning this tutorial

In the last tutorial, we added a model, view and controller to display a list of customers that one can navigate to using a URL formatted as controller/action.  In this article, we will add a new view and controller to an existing MVC project and display details of a single customer using a URL formatted as controller/action/id.  The id is passed automatically to the action method and allows us to filter to a single customer.

1.       Open Visual Studio 2008 and open the TestMVC solution created in MVC Tutorial 2.

2.       Open the Solution Explorer (View | Solution Explorer) and select the Controllers\CustomerController.cs.   Double-click CustomerController to open it in the code editor.

a.       In the CustomerController class, we will create a new action to get the details of a single customer.   

                                                               i.      Add the following private GetCustomer method to the CustomerController class.  In the last tutorial, we wrote methods to retrieve customer 1 and customer 2.  For simplicity, we will get Customer 1 if ID 1 is passed in to our method and Customer 2 if any other ID is passed.

        private Customer GetCustomer(int custID)

        {

            if (custID == 1)

            {

                return GetCustomer1();

            }

            else

            {

                return GetCustomer2();

            }

        }

                                                             ii.      Add an Action method to the CustomerController class to get the details of a customer.  Paste the following code into CustomerController.cs.

        public ActionResult Details(int id)

        {

            Customer cust = GetCustomer(id);

            return View("Details", cust);

        }

                                                            iii.      In the GetCustomer method, we get details of a single customer and return a view.  Unlike the generated code, we explicitly specify which view to return (“Details”) and we pass in some extra data (cust) that the view will consume.

3.       Add a view to the project.

a.       In the Solution Explorer, right-click the Views\Customer folder and select Add | New Item.  The Add New Item dialog displays.

    Figure 1

                                                               i.      Under Categories, select Visual C#\Web\MVC.

                                                             ii.      Under Templates, select  MVC View Content Page.

                                                            iii.      In the Name textbox, enter “Details”.

                                                           iv.      The Select a Master Page dialog displays.  

   Figure 2

1.       Navigate to the Views\Shared folder and select Site.Master.

2.       Click the OK button to add this view content page to the project.

b.      Add visual elements to the View

                                                               i.      If it is not already open, open the Details view by double-clicking List.aspx in the Solution Explorer.  Click the Source tab at the bottom of the editor.

                                                             ii.      Replace the code in Details.aspx with the following

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Details.aspx.cs" Inherits="TestMVC.Views.Customers.Details" %>

<%@ Import Namespace="TestMVC.Views.Customers"%>

<%@ Import Namespace="TestMVC.Models" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

    <div>

        CustID:

        <%=((Customer)ViewData.Model).CustID %><br />

        Name:

        <%=((Customer)ViewData.Model).FirstName %>

        <%=((Customer)ViewData.Model).LastName %>

        <br />

        Address:

        <%=((Customer)ViewData.Model).StreetAddress%><br />

        City:

        <%=((Customer)ViewData.Model).City %><br />

        State:

        <%=((Customer)ViewData.Model).State %><br />

        ZIP:

        <%=((Customer)ViewData.Model).PostalCode%><br />

    </div>

 

</asp:Content>


The above code displays details of a single Customer model object. 

4.       Modify the List view

a.       Open Views\Customers\List.aspx by double-clicking it in Solution Explorer.

b.      Find the <td>&nbsp;<\td> cell tag following the cust.PostalCode cell.  Replace this with the following code.  This generates a hyperlink displaying the text “Details”.  The URL of the hyperlink will have the current controller (“Customer”) the “Details” Action and the ID of the current customer.

<td>

<%=Html.ActionLink("Details", "Details", new { ID=cust.CustID})%>

</td>

5.       Test the application

a.       Save and compile the solution (Build | Build Solution).   Correct any errors you find.

b.  Run the solution (Debug | Start Debugging).  Depending on the port number used by Casini, it should display in your browser with a URL such as
http://localhost:4152/Home

c.       Navigate to the List page by changing the URL to
http://localhost:4152/Customers/List
(Replace the port number if necessary)

d.      You should see a list of 2 customers in your browser.  Each customer should have a hyperlink labeled “Details”. 

    Figure 3

e.      Click the hyperlink next to customer 1.  The URL should change to
http://localhost:4152/Customers/Details/1
and the details of the first customer should display on screen.

    Figure 4

f.        Set a breakpoint in the Details method of CustomerController.cs and refresh the page to step through the code as it executes.

In this article, we added a view and controller to our application and used these to retrieve and display customer details by the Customer ID. 

.Net | ASP.NET | MVC | Tech
Wednesday, August 27, 2008 7:26:29 AM (Eastern Standard Time, UTC-05:00)
 Tuesday, August 26, 2008

There's nothing quite like riding on a bus for 27 hours with a few dozen software developers.

That's exactly what I did last weekend on my way to and from DevLink in Murfreesboro, TN.

The DevLink bus was the result of much hard work by Amanda who did most - if not all - the organizing.

The bus began its odyssey Wednesday night in Grand Rapids, MI before proceeding to Lansing.  When the bus picked me up in Plymouth, MI at 9:15 PM, it had already been traveling for 3 hours.  From there, it rolled on to Toledo, Columbus and Cincinnati (its final southbound stop at 4AM) before proceeding to its final destination in Murfreesboro, Tennessee. 

The first half of the ride was great fun.  I met new people; I reconnected with old friends; and I met people face-to-face with whom I had only communicated electronically.

Event the two times the bus driver got lost couldn't dampen our spirits.  We were having too much fun.

After about 4AM, the trip began to drag.  Everyone was exhausted and the seats were too uncomfortable to allow more than a few minutes sleep at a time.  This was clearly a bus designed for cross-town trips – not cross-country trips.  DVDs provided some entertainment ("The Big Lebowski" and “Office Space” cracked me up) but you can only focus on movies for so long and the acoustics were less than ideal.

We arrived at our hotel worn and weary at 9:30AM Central time, over 13 hours after leaving Plymouth and 16 hours after the bus began its trip. 

24+ hours of sleep deprivation left me physically ill and I spent nearly all of Thursday in bed.

It was good that I did.  The conference began Friday morning and I awoke refreshed and ready to absorb and exchange ideas at what turned out to be an excellent conference.  (You can read more about it here.)

The ride home was an adventure.  Although the conference ended at 6PM, someone decided the bus shouldn't leave town until 9PM so we had to kill a few hours at a restaurant before heading out. 

Although we picked up at least one new traveler on the ride home, we lost a few more.  Some folks booked a flight to Chicago for a Monday business meeting and a couple people elected to rent a car and drive home rather than subject themselves to the length and discomfort of the bus ride.  I was tempted to join them but I stuck with my plan and boarded the bus at 9.

The mood was more subdued on the return trip. We still had some good conversations early in the ride but the environment lacked the energy sparked by seeing people for the first time in months.

About 2AM, I had just begun to drift to sleep when a sound like a jackhammer awakened me suddenly.  I was sitting just above the tire that blew flat traveling 65 miles an hour on I-71 just north of Louisville, KY.  We pulled off the highway in front of a Waffle House in Carrolton, KY and waited 3 hours for the tire to be fixed.  The repair would have taken far less time if the repair guy had not allowed a drunken Waffle House customer to play with the lug nut gun.  He sheared off the bolts on wheel, forcing the repair guy to return to his shop for more parts and weld on new bolts.

Waffle House provided some entertainment.  Corey attempted to start a relationship with one of the waitresses; and the manager tossed out a drunk who wouldn't stop ordering pork chops long after he was told the restaurant was out of pork chops.  Apparently the Carrolton Waffle House is a magnet for drunks at 2AM Saturday night.  Go figure.

We got back on the highway about 5AM so exhausted that even the uncomfortable seats wouldn't prevent a few hours dozing.

I thought things would go quicker after this because the drivers knew the route better, having just driven it 3 days earlier.  Alas, we became lost in northeast Ohio and drove nearly to Cleveland before turning west toward Toledo.

At 12:30 Eastern time - 14.5 hours after leaving the hotel and 17.5 hours after the end of the conference - we pulled into the parking lot in Plymouth.  I was never so happy to see my car and the 40 minute drive home seemed trivial. 

I was scheduled to read aloud at the 12:15 mass in my church and the last minute substitute is probably still angry with me for missing this, but we all arrived safely.

Was the bus ride a success?  Would I do it again?  Would I take a bus to a distant location with dozens of others like me?  I've decide that, if I can be promised a more comfortable seat, I will do it the next time it's offered.  Everything else was easily tolerable and I did enjoy the fellowship that came with such a long ride with like-minded people.  I even got a few job leads from the conversations I had on the two rides (I am between jobs for those who don't know).

If you go on such a trip, my only advice is

  1. Be prepared for anything
  2. If the Waffle House waitress in Carrolton, Ky tells you they are out of pork chops, shut up and order the hash browns. 

Note: Click here to see more photos from DevLink and the famous bus ride.

Tuesday, August 26, 2008 10:38:58 AM (Eastern Standard Time, UTC-05:00)
 Monday, August 25, 2008

People attend conferences for many different reasons.  Some come for the content of the lectures; some come to meet and hear well-known speakers; some come to meet and network with others in the industry; some come to see old friends.

Me, I come for all those reasons.  At DevLink last week in Murfreesboro, TN, I experienced all those things and more. 

But I also experienced something new.  I had heard of Open Spaces in the past but had not experienced them.  At DevLink, Open Spaces were promoted heavily as a different way of exchanging ideas.  I was curious and gave it a try.

An Open Space event consists of developers sitting together roughly in a circle in a room and they exchange ideas with one other.  A topic is picked in advance by the group but the conversation is not limited to that topic.  If the conversation drifts from the assigned topic and the group remains engaged, this is perfectly all right.  The important thing is that ideas are exchanged and the group remains passionate about the conversation.

And I heard a great deal of passion at the DevLink Open Spaces that I attended.

During the event, I attended 3 Open Spaces sessions plus the planning session (where topics were picked) and the wrap-up session (where the group reviewed the open spaces of the previous 2 days).  In each session I attended, I heard bright people sharing great ideas.  Sometimes we argued and sometimes we were in violent agreement but I enjoyed it all. 
In a session on Service Oriented Architecture, I argued earnestly that, due to the costs of SOA, support from the top was necessary for SOA to succeed within any organization.  Most of the other loud persons in the group insisted that newer tools such as WCF had lowered the cost of SOA sufficiently that a strong grass roots effort could drive SOA in an organization.  By the end of the session, I think we had all learned something and moved a little toward understanding the others' side.

I did attend a few traditional sessions in which a speaker stands in front of a classroom and delivers a lecture to an audience that is mostly passive.  Richard Campbell and Carl Franklin were two of the speakers at this conference and I have long been a fan of their .Net Rocks podcast, so I made a point to attend a lecture by each of them.  Both were good sessions but they were easily topped by Joe Wirtley who gave an excellent talk on WPF.  It was excellent because it focused on building a business application, rather than the eye candy that clutters so many WPF presentations.

Overall the conference was a great success.  It drained me of energy but it fired me up at the same time.

And I haven't even told you about the 28 hours I spent riding a bus with a few dozen techno-geeks.  Or the flat tire that left us stranded in Carrolton, KY for 3 hours at 2AM.  But that’s another story.

Note: Click here to see more photos from DevLink

Monday, August 25, 2008 10:49:27 PM (Eastern Standard Time, UTC-05:00)
 Friday, August 22, 2008

Microsoft recently released the ASP.Net Model View Controller framework (MVC).  It is currently available as Preview 3 and can be downloaded at http://www.microsoft.com/downloads/details.aspx?FamilyId=92F2A8F0-9243-4697-8F9A-FCF6BC9F66AB&displaylang=en

A new MVC project contains a couple sample views and controllers so you can get an idea of the proper syntax to use. 

In this article, we will add a new model, view and controller to an existing MVC project. 

1.       Open Visual Studio 2008 and create a new MVC project.  For information on how to create a new MVC project, see http://www.davidgiard.com/2008/08/18/TheASPNetMVCSampleAppDemystified.aspx

2.       Open the Solution Explorer (View | Solution Explorer) and select the Models folder.

3.       Add a Model to the project

a.       Right-click the Models folder and select Add | Class.  The Add New Item dialog displays.
Figure 1
    Figure 1

                                                               i.      At the Name textbox, enter “Customer”.

                                                             ii.      Click the OK button to create a Customer class.

b.      The Customer class opens in the class editor.  This class will contain a few public properties that help describe a customer object.  Add the following code to the Customer class.

    public class Customer

    {

        public int CustID { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string StreetAddress { get; set; }

        public string City { get; set; }

        public string State { get; set; }

        public string PostalCode { get; set; }

    }

4.       Add a Controller to the project

a.       In the Solution Explorer, right-click the Controllers folder and select Add | New Item.  The Add New Item dialog displays.
Figure 2
    Figure 2

                                                               i.      Under Categories, select Visual C#\Web\MVC.

                                                             ii.      Under Templates, select MVC Controller Class.

                                                            iii.      In the Name textbox, enter “CustomerController”.

                                                           iv.      Click the Add button to create the CustomerController class and open it in the class editor.

b.      In the CustomerController class, we will create some actions.  Each action will instantiate one or more Model objects and display them in a view object. 

                                                               i.      Add the following statement at the top of the CustomerController class. 

using TestMVC.Models;