If you are working through the tutorial from the beginning, you can read starting with the earliest posts first.


Archive for August, 2010

Nerd Dinner Part 2 Discussion and Database Setup Script

Posted in Uncategorized on August 30th, 2010 by matt – 2 Comments

This post is a discussion of Part 2 of the online NerdDinner ASP.NET MVC tutorial.

NerdDinner Part 2 is about setting up the database for future work.

There’s a lot of table creation and data entry. This is all done via the Server Explorer tool inside Visual Studio. If you want the practice setting up your tables and data manually, follow along with the tutorial–it’s carefully laid out with lots of useful screenshots.

If you don’t need the practice and would rather take a shortcut, here’s a script you can use instead: NerdDinner database setup script.  This script will create the Dinners and RSVP tables (including keys), and populate the Dinner table with data matching what we see in the screenshot.

The setup script relies on you creating the NerdDinner.mdf database yourself.  If you want to use the script, be sure you finish the database creation steps of the tutorial (“Creating a new SQL Server Express database”) first.

To apply the script, just run it as a query against your new NerdDinner database.  If you’re not used to running queries, here’s a step by step:

  • Copy the complete text of the setup script to your clipboard.
  • Open Server Explorer (it’s near the top of the View menu in Visual Studio, or you can use Ctrl-W, L).
  • Expand the tree for your new NerdDinner.mdf database so you can see the folders underneath, right click on the database name, and choose New Query.
  • Immediately close the Add Table window that popped up over the query interface.
  • Find the SQL pane in the query interface.  It’s third from the top, and should already have “SELECT FROM” displayed there.
  • Delete the “SELECT FROM” so that the SQL pane is completely blank, and paste in the complete text of the setup script into that pane.
  • Click on the orange exclamation point button shown in the toolbar (or, press Ctrl-R while you have focus in the SQL pane).
  • You’ll get a warning.  Server Explorer has a degraded understanding of SQL, and you’re scaring it.  Don’t worry about the warning, click Continue.  You may notice a delay while the query runs.
  • You should get a message “7 rows affected by last query”.  Close the message, you’re done.

(A special note: to create the INSERT statements used in the setup script, I used a stored procedure called sp_generate_inserts written by Narayana Vyas Kondreddi. If you work with SQL Server, I recommend taking a look at this sp, it’s very handy. Thanks Vyas!)

I didn’t encounter any problems working through Part 2, and there aren’t any code changes from Part 1 to zip up.

In Part 3, we’ll set up an interface to our new tables from our application, and talk about the Model in Model-View-Controller.

NerdDinner Part 1 Discussion and Source Code (continued)

Posted in Uncategorized on August 22nd, 2010 by matt – Comments Off

This post is a continuing discussion of Part 1 of the online NerdDinner ASP.NET MVC tutorial.

In a previous blog post, I talked about URL, Logic, and HTML.  Let’s take a quick look at what happens from that perspective with a simple example from the application–clicking on the About link from the start page.

The URL for the About link is http://localhost:2202/Home/About (your port number is probably different).  When we pass this URL to the web server, it is handled by the routing engine.  We can see the rules for the routing engine in Global.asax.cs–in this case, there is only one rule, a default rule.  It looks like this:

routes.MapRoute(
  "Default",
  "{controller}/{action}/{id}",
  new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

The relevant part of our URL is “/Home/About”–this will be matched against “{controller}/{action}/{id}”.  We come up with a Controller of “Home”, and an action (i.e. function) of “About”.  (Our URL has nothing to match the optional “id” parameter.)  The routing engine will then look for appropriate logic to start processing the web request–a Home controller file, and an About action within that file.

There’s a bit of a trick here. In the pattern above, our controller is called “Home”, but the routing engine will actually look for /Controllers/HomeController.cs.  The engine automatically adds the “…Controller.cs” suffix and proceeds to look for that suffixed file in the /Controllers directory.  This is a convention of ASP.NET MVC, and it is a little confusing at first.

Once ASP.NET has found /Controllers/HomeController.cs, it will look for action “About” (this is a literal match from the URL pattern, nothing tricky here).  There is an action called About, and program flow passes there.  The job of the action is to interpret and process the users request, interacting with the Model if needed, and then move on to generating the HTML.  (Remember that HTML generation uses a View in .NET MVC.)

In this case, the “About” action is rather sparse.  All it does is return View();!  Does it seem like there must be some detail missing here? Yup, there’s more magic hiding within that return View();.  If you look around under the /Views/ folder you’ll find /Views/Home/About.aspx, and that’s the view we use in this action, even though we aren’t asking for it explicitly.  We infer the full name of the view from the controller and action.  Again, this is a .NET MVC convention that you’ll get used to.   (You’re not married to it, either–there are ways to be more explicit if you like.)

All this may seem like an excessive amount of magic, and it certainly is when you’re first getting started.  Just realize that it is magic, and you’re not missing something explicit that you were supposed to understand.  We’ve got 11 more parts of NerdDinner to go–you’ll get used to these conventions, maybe even like them.  (If you want to learn more now, though, here’s a bit longer discussion of how .NET MVC infers controller and view names.)

Looking at our request-and-response above from an MVC perspective, you might have noticed that we’ve interacted with a Controller (/Controllers/HomeController.cs) and with a View (/Views/Home/About.aspx). What about the Model?  Isn’t that important?  Normally, yes, the Model is quite important.  This was an unusually simple request, and we didn’t need a model (or any code, really) to process the About action.  We’ll talk a lot more about the Model soon, starting in Part 3.

Next post we’ll get into Part 2 of NerdDinner, which is basic database setup for the rest of the tutorial.  If you’re new to setting up databases, there’s a nice step by step walkthrough with lots of screenshots that will keep you in a comfort zone.  On the other hand, if you’re already comfortable setting up databases, the manual db setup in Part 2 feels kinda slow and plodding.  Wouldn’t it be nice to have a script to do the setup for you? Stay tuned . . .

NerdDinner Part 1 Discussion and Source Code

Posted in Uncategorized on August 14th, 2010 by matt – Comments Off

This post is a discussion of Part 1 of the online NerdDinner ASP.NET MVC tutorial.

Part 1 gets us up and running using the default site created when starting a new ASP.NET MVC project.

I’m using VS 2010–you don’t have to install MVC specially any more with VS 2010.

Instead of ASP.NET MVC Web Application, I used ASP.NET MVC 2 Web Application.  I did create the unit test project (and you should too).

The authors tell us about the six default directories.  Note that the first 3 are /Controllers, /Models, and /Views.  This might ring a bell–these are the same Models, Views, and Controllers as the MVC pattern describes.

You might notice that the /Scripts directory contains several files that start with “jquery”.  JQuery (link), if you’re not familiar with it, is a javascript library used to make client-side web development a lot easier.  In my old WebForms days, I never would have guessed that Microsoft would bundle someone else’s open source javascript tool into one of their own product releases.  I like it.

The default files do start you off with a placeholder application, and basic user registration and authentication.  The authors don’t quite say “make yourself a user account”, but you should do that.

When you register a user name for the first time, some magic happens behind the scenes and you create a new SQL Server Express database in your app data folder, with credentials for your new user name.  (If you look in Web.Config, under <connectionStrings>, you’ll see an ApplicationServices key defining the database that just got created.)  This new database is part of the Model for your user account.  We’ll talk more about Models later, but a Model basically refers to persistent data (the database) and related logic.  You might already have noticed AccountModels.cs in your \Models folder, but you should also realize that there’s an automagically created database behind that code.

The authors conclude by asking you to run the default unit test suite.  Do this, even though it won’t mean much yet.  It’s good foreshadowing.

I didn’t encounter any errors or surprises in Part 1–everything worked as described without adjustment.  A .zip file containing source code for NerdDinner Part 1 is available here.

Note that I am NOT including the large database files found in the app directory in every zip file.  This means that you can’t just unzip the application and run it.  You’ll need to supply your own database files if you want to run the downloaded source code.  The ones you’ve created for yourself working through the tutorial should be fine.  (If for some reason you really need to download the db files, a zip of the NerdDinner database files is here.)

In the next post, we’ll go over the ideas of URL, Logic, and HTML again using a simple URL from Part 1, and talk a little bit about the some of the (confusing) magic that happens under the hood when you’re coding .NET MVC.

A different start to learning ASP.NET MVC

Posted in Uncategorized on August 8th, 2010 by matt – Comments Off

On the interwebs, there’s already a lot of intros to MVC. What is MVC? Well, MVC stands for Model, view, Controller . . .

Yes, very true and good, and you should have an idea about what the M, V, and C mean. But at least for me, reading about what a Model was didn’t really get my head around what was different about an MVC application. I had to get knee deep in code before it started to make sense. I’m going to try a different angle here and maybe give some other newcomers an easier path up the hill.

Let’s set “MVC” aside for a while and instead talk about these three steps of handling a web request from a browser: the incoming URL, the Logic (yeah, we’re bundling a lot together here), and the HTML or pseudo HTML that defines the look of the final result. Here’s how WebForms ASP.NET handles these, in a simple scenario:

URL: www.asite.com/example.aspx
Logic: example.aspx & example.aspx.cs
HTML: example.aspx

Here, the URL, the Logic, and the HTML structure are all the same thing. They’re all referring to a particular file on your webserver. This seems “natural”–it’s how a site built with static HTML works, and it’s also true in lots of other web programming languages such as PHP and old style ASP.   (Omitting non-standard exceptions.)

But a web app doesn’t have to work like this. The URL, logic, and HTML don’t have to all be tied together into the same file on the web server. And in MVC web applications they aren’t. Instead, you have something like this:

URL: www.asite.com/example/show/
Logic: file /Controllers/ExampleController.cs, class ExampleController, method Show
HTML: /Views/Example/Show.aspx

The URL, the Logic, and the outgoing HTML refer to completely different parts of the application. Let’s talk about each of these as we’ve got them shown above.

URL: You can see the URL ends with a “directory” instead of a “file”. Well, that URL isn’t really pointing to a folder on the web server.   Instead of trying to look for the directory “/example/show”, ASP.NET MVC will give that URL pattern to the “routing engine”.  The routing engine knows how to interpret different URL patterns you expect to see in your application (either via defaults, or your explicit instructions).  Based on its instructions and the URL pattern it receives, the routing engine will pass the request on to a particular method in your application for logical processing.

(What if the user sends an unanticipated URL pattern, and the routing engine doesn’t how to handle it? The user will get a 404 error–it’s the equivalent of asking for a non-existing .aspx file.)

Logic: The routing engine sends us to a particular method of a particular class.   In contrast, WebForms starts our logic in an implied place (e.g. Page_Load of example.aspx.cs).   Here, the URL and routing engine give us an explicit starting place. In the hypothetical example above, our starting place is the method Show() in the class ExampleController. These request handling methods are called “actions” in .NET MVC.

The targeted method, the action, handles the specific details of this user request, and eventually sends back a HTML response to the user. There’s lots of potential detail to get into here–which we’ll ignore for right now. The key idea is that the details of the request are passed to our selected action, the action controls how that request is processed, and eventually the action concludes with a HTML response that is sent back to the user’s browser.

HTML: The way the action concludes with an HTML response follows a particular pattern–an action concludes by returning a “view”.  A view is a special class used to generate HTML. It is basically a HTML template with placeholders. (If you’ve done classic ASP programming, and you look at a .NET MVC view, it will look rather familiar.) The action passes information to the view to complete those placeholders, the view generates a completed, individualized page for the user, and the completed page goes to the web server and back to the user.

(Note that this is a bit oversimplified–actions really return ActionResults, which include other kinds of responses besides straight HTML.  For now, I just want to emphasize that the logic and the HTML of the application are separate from one another.)

Whew!  That’s quite enough for today. In the next couple of posts, we’ll take a look at the first chapter of the NerdDinner application. It’s pretty simple, but there’s a lot of “magic” underlying that simplicity. If you’re like me, that magic is confusing, and worth digging into a little to try to understand what’s happening. Stay tuned.

What’s interesting about ASP.NET MVC:

Posted in Uncategorized on August 1st, 2010 by matt – Comments Off

Another Look at ASP.NET MVC

. . . from the eyes of a newcomer.

I had heard about ASP.NET MVC for a quite a while.  I knew it was out there, I knew it was Microsoft’s MVC answer to the up-and-coming web frameworks like Ruby On Rails and Django.  I had heard Jeff Atwood was building StackOverflow using the .NET MVC beta (was the man crazy?).  I figured someday I’d take a look at it, but it took some interest from a client before I really sat down and started playing with it.  I wondered what my reaction would be . . .

Hey!  This is neat stuff!  Let’s talk about this!

How long has ASP.NET MVC been out now?  Aren’t you a little late to the party?

Well, maybe a little bit.  If you count the beta, .NET MVC has been out for over two years now.  It might seem a little odd to start a “getting to know ASP.NET MVC” blog today.

On the other hand, there are still plenty of coders out there who are right where I was a couple of months ago–mildly curious about .NET MVC, maybe loaded it up once, but haven’t really worked with it.  It might help to have another point of view on getting started, what’s interesting, and what’s confusing.

.NET MVC will have newcomers for a good while yet, so I like to think I’m merely fashionable.

What’s so neat about ASP.NET MVC?

Well, the “classic” answer is .NET MVC gives coders better control over the details of their HTML, CSS, and Javascript, and gets rid of the sometimes-clumsy abstraction layer of Webforms.  It encourages good programming practices like separation of concerns and unit testing, and it plays nicely with what’s new and clever in the wider world of web development (today, JQuery, tomorrow, HTML5).

Much more has been said about this.  Here’s an amusing take (you wouldn’t put a wig on your poor kitty, would you?) and here’s an official take (down toward the bottom).  Or you can google (“ASP.NET MVC” vs Webforms) and read until your eyes are tired.

Another answer is that .NET MVC is just plain fun.  I decided to get familiar with .NET MVC through the excellent NerdDinner tutorial.  Over and over I found myself saying *oh that’s nice*.  (True confessions time, my .NET skills are a little out of date, so some of what sparks my interest is goodies from .NET 3.5 rather than .NET MVC specifically.  But again, I’m probably not alone in this . . .)

What I’d like to do here (NerdDinner, by parts)

I’d like to talk about ASP.NET MVC, and about learning ASP.NET MVC, especially with newcomers to the framework.  If you’re strictly a Webforms guy, or otherwise new to the MVC pattern, it’s kind of a big leap.  There’s a lot to get your head around.

I mentioned the NerdDinner tutorial above–it’s a great tutorial, and a great way to get started learning .NET MVC, but it does have some bugs, and might be a little intimidating in places.  If you get stuck part way through, it’s tricky to compare your work-in-progress to the final, polished version.  So I’ll go through the tutorial chapter by chapter, mention any bugs that are hiding, and provide working source code for that particular stage.  Plus answer (or try to answer) any questions that readers have.

(Note that there is a new, updated NerdDinner 2.0 available, and there’s also a new book to go with it.  It’s got lots of fancy new features and you should check it out and give it a spin.  However, as far as I know, there isn’t a nice chapter-by-chapter version online–so I think the old version 1.0 is still better for a chapter-by-chapter walkthrough.)

Next stop, before I start the NerdDinner walkthrough, I’d like to explain a little bit about MVC web programming, for people who are coming from good old ASP.NET (hint, the M-V-C isn’t the tricky part).  Stay tuned.