Link here

Link here

Pro ASP.NET MVC 2 Framework

ASP.NET, MVC, Pro ASP.NET MVC 42 Comments »

imageThis week Apress is sending the second edition of my ASP.NET MVC book to the printers. Hopefully this means you can get your hands on physical copies by the end of this month.

The first edition went deep into the details of the MVC Framework, providing both tutorials and reference material. Judging by sales and review scores, it was a success. The second edition:

  • … is thoroughly updated for ASP.NET MVC 2. It explains all the new features, including templating, metadata, validation, asynchronous controllers, areas, HTTP method overloading, strongly-typed input helpers, default parameters, etc., and many are demonstrated in the various tutorials.
  • … is updated to account for .NET 4 and Visual Studio 2010. Even though .NET 4/C# 4 is the preferred technology throughout the book, all the documentation and code accounts for readers using .NET 3.5 as well.
  • … is updated to reflect more recent patterns and best practices. For example, discussions of automated testing apply ideas from Behaviour Driven Development (BDD) where relevant, and tutorials and descriptions now consistently distinguish between view models and domain models.
  • … is updated in light of reader feedback from the first edition. Certain explanations and terminology are overhauled, and the tutorials make use of more effective third-party libraries (e.g., Ninject for Dependency Injection).

This blog post is partly intended to build awareness of the new book, and is partly intended to deal with some of the questions I regularly get by email. So, here are some questions that people frequently ask:

Is this a new book, or an update?

It’s an update of the first edition. The following diagram should clarify what proportions of the book are new, dramatically changed, or just refreshed:

image

Where and exactly when can I get it?

I don’t know the exact date when it will ship; this depends on physical production and distribution schedules that are beyond my knowledge.

  • For printed copies, your best bet is to pre-order with Amazon. Hopefully these will ship around the end of June, but I can’t guarantee it.
  • For the eBook version, keep checking the Apress web site.

There’ll probably be a Kindle version in due course, too.

If I already have the first edition, should I buy the second edition?

If you use ASP.NET MVC regularly - especially if plan to use the new MVC 2 features but haven’t yet learned about them in depth - you may well get a lot out of reading the new edition and seeing what’s the same and what’s new. You may also have colleagues who need a deeper knowledge of the whole MVC Framework, including both v1 and v2 features.

However if you don’t use ASP.NET MVC much and don’t intend to migrate your development to v2, perhaps there isn’t such a strong case for buying an update of a book you already own.

Some readers have asked if they can get a sort of “upgrade” edition which contains only the new material. That wouldn’t really make sense for this book, as the new concepts and practices are applied throughout. I don’t present “old” material followed by “new” material – the whole manuscript is updated as a single coherent guide to ASP.NET MVC 2 from the beginning as I believe this gives the clearest understanding.

What new and updated in the second edition?

There are far too many updates and enhancements in the new edition to describe them all. Here’s a brief outline of the table of contents and roughly how each chapter has changed.

Chapter 1: What’s the Big Idea?

Updated to account for ASP.NET 4, including improvements to WebForms and how this impacts the comparison between the two frameworks. Gives an overview of what’s new in ASP.NET MVC 2. Changed the discussion general software development practices to account for more recent trends.

Chapter 2: Your First ASP.NET MVC Application

Tutorial now accounts for your choice of Visual Studio 2008 or Visual Studio 2010. Uses new ASP.NET MVC 2 features, including empty project template, automatic HTML encoding, and Data Annotations validation. Streamlined the flow of the tutorial to improve readability.

Chapter 3: Prerequisites

Describes newer architectural patterns including MVVM. Discussion of automated testing expanded to cover integration testing as well as unit testing, and demonstrates Cucumber-style BDD testing and explains the tradeoffs between this and traditional unit TDD. Various updates to terminology and explanations.

Chapter 4, 5, 6: SportsStore tutorial

Now accounts for your choice of Visual Studio 2008 or Visual Studio 2010. Improved the code: better project structure, uses Ninject instead of Castle Windsor for DI, has better unit test naming (BDD-style) with a clearer description of the limitations of such testing. Applies the viewmodel pattern and related terminology more consistently.

Adapted the tutorial to benefit from MVC 2 features including optional parameters, metadata, scaffolding, client-side validation, automatic (de)serialization, etc. Some parts of the tutorial now go in a different order to make it easier to follow.

Chapter 7: Overview of ASP.NET MVC Projects

Updated to account for ASP.NET MVC 2’s two project template options (empty and non-empty), and for changes in the core ASP.NET 4 platform regarding configuration and deployment.

Chapter 8: URLs and Routing

Now covers areas – reasons for using them, setting them up, their impact on routing, how to avoid common problems, how to unit test their routing configuration. Explains how .NET 4 changes where the routing code lives and how ASP.NET MVC 2 deals with controller namespaces. Many smaller changes.

Chapter 9: Controllers

The 1st edition’s “Controllers” chapter is now split in two – this first chapter now covers introductory topics – receiving input data with parameter binding etc, producing output with action results etc., unit testing.

Has many changes to account for ASP.NET MVC 2, such as its enhancements to TempData. Also describes .NET 4 features – using optional parameters (and how these differ from ASP.NET MVC 2’s parameter defaults), using “dynamic” as a model type, etc. Expands the coverage of unit testing, demonstrating 5 ways to make mocking controllers easier.

Chapter 10: Controller Extensibility

The 1st edition’s “Controllers” chapter is now split in two – this second chapter now covers more advanced topics – custom filters, method selectors, controller factories, etc.

Updated to reflect changes in the ASP.NET MVC 2 request-processing pipeline, new built-in filters, HTTP Method Overriding, etc. Adds (a lot of) coverage of asynchronous controllers – not just how to use them, but how to measure their impact and avoid common misconfiguration problems.

Chapter 11: Views

Goes into detail about how automatic HTML encoding works. Coverage of HTML helper methods expanded for ASP.NET MVC 2 (there’s now over 50 helpers, and that’s before you even start counting all their different overloads). Explains new ways to render partials.

Chapter 12: Models

Most of this massive chapter is totally new, and goes into great detail about metadata, templating, and validation. Covers how the built-in templates work, creating custom ones, using HTML field prefixes, implementing custom metadata sources, consuming metadata, custom validation providers, custom client-side validation, doing all this inside a multi-tier architecture, etc.

The explanation of model binding and value providers is significantly updated to account for the new architecture in ASP.NET MVC 2.

Chapter 13: User Interface Techniques

This new chapter inherits UI-related material from various parts of the 1st edition book, including wizards, CAPTCHAs, child actions, master pages, open-source view engines, custom view engines. All updated to match ASP.NET MVC 2, of course.

Chapter 14: Ajax and Client Scripting

Updated various aspects of the code and explanations to account for new framework features, and to make things work with more recent versions of IE. Expanded the coverage of JSON data services, including security issues and ways to handle cross-domain requests. Some recommendations are updated to account for client-side performance considerations(browser’s rendering pipeline, CDNs, etc).

Chapter 15: Security and Vulnerability

Mostly the same as in the first edition. Shows an alternative tamper-proofing mechanism using MVC 2 code, plus describes JavaScript string encoding and its relation to script injection. Various code changes to fit in with ASP.NET MVC 2.

Chapter 16: Deployment

Radically restructured chapter – now all organized with step-by-step guides and checklists for each targeted IIS version, so now you only have to read the material relevant to you. Covers new deployment options, including combinations of .NET 3.5 SP1, .NET 4, Server 2003, Server 2008, Server 2008 R2, Server 2008 R2 Core, shared hosting, classic/integrated pipeline mode, etc. Accounts for many changes to these deployment environments since the 1st edition, including IIS 7.5-specific issues

Clearer explanations of various IIS request-processing mechanisms. A new section describes VS2010’s improved publishing and packaging mechanisms, config file transforms, etc.

Chapter 17: Using ASP.NET Core Platform Features

Mostly the same as in the first edition. Updated to account for ASP.NET MVC 2, IIS 7.5, with tweaks to code and explanations. Information about configuration APIs moved from Deployment chapter into this chapter.

Chapter 18: Migrating Existing Applications to ASP.NET MVC 2.0

Various updates relating to .NET 4 / VS2010 / ASP.NET MVC 2, including how to upgrade Web Forms applications to support MVC, using routing when combining MVC with Web Forms (both on .NET 3.5 and .NET 4), ways you can use Web Forms server controls with postbacks in MVC 2, should you wish to.

New section describes upgrading from ASP.NET MVC 1 – using automated tooling, doing it manually, a post-upgrade checklist, workarounds for potential problems.

OK, enough details

Of course, there are other ASP.NET MVC 2 books in the pipeline too. No doubt you’ll enjoy and benefit from any of them.

Now Published: Pro ASP.NET MVC Framework (Apress)

MVC, Pro ASP.NET MVC 68 Comments »

image At last! Physical copies of my book have finally reached the public. I’ve been writing, tweaking, fixing, expanding, and polishing this since February 2008, following every preview release of ASP.NET MVC. Now it all reflects the final RTM version.

The design goal for this book is to give you, the reader, the most practical and detailed guide to virtually everything that ASP.NET MVC does. If you want to become your company’s expert on how this stuff really works – how to bend it to your will, how to apply best practises, and what limitations you’ll have to overcome – then I hope this is the book for you.

Download a sample chapter - an introductory tutorial that shows how to build a simple data-entry application with ASP.NET MVC.

Of course, other MVC books will become available over the next few months. I’ll look forward to reader feedback about how these compare.

To give you a feel for what’s covered, here’s the table of contents:

Part 1: Introducing ASP.NET MVC

CHAPTER 1 : What’s the Big Idea?

A Brief History of Web Development
Traditional ASP.NET
What’s Wrong with Traditional ASP.NET?
Web Development Today
Web Standards and REST.
Agile and Test-Driven Development
Ruby on Rails
Key Benefits of ASP.NET MVC
Model-View-Controller Architecture
Extensibility
Testability
Tight Control over HTML
Powerful New Routing System
Built on the Best Parts of the ASP.NET Platform
.NET 3.5 Language Innovations
ASP.NET MVC Is Open Source
Who Should Use ASP.NET MVC?
Comparisons with ASP.NET WebForms
Comparisons with Ruby on Rails
Comparisons with MonoRail

CHAPTER 2 : Your First ASP.NET MVC Application

Preparing Your Workstation
Creating a New ASP.NET MVC Project
Removing Unnecessary Files
How Does It Work?
Rendering Web Pages
Creating and Rendering a View
Adding Dynamic Output
A Starter Application
The Story
Linking Between Actions
Designing a Data Model
Building a Form
Handling Form Submissions
Adding Validation
Finishing Off

CHAPTER 3 : Prerequisites

Understanding Model-View-Controller Architecture
The Smart UI (Anti-Pattern)
Separating Out the Domain Model
Three-Tier Architecture
Model-View-Controller Architecture
Variations on Model-View-Controller
Domain Modeling
An Example Domain Model
Entities and Value Objects
Ubiquitous Language
Aggregates and Simplification
Keeping Data Access Code in Repositories
Using LINQ to SQL
Building Loosely Coupled Components
Taking a Balanced Approach
Using Inversion of Control
Using an IoC Container
Getting Started with Automated Testing
Unit Tests and Integration Tests
The Red-Green Development Style
New C# 3 Language Features
The Design Goal: Language Integrated Query
ExtensionMethods
Lambda Methods
GenericType Inference
Automatic Properties
Objectand Collection Initializers
Type Inference
Anonymous Types
Using LINQ to Objects
Lambda Expressions
IQueryable<T> and LINQ to SQL

CHAPTER 4 : SportsStore: A RealApplication

Getting Started
Creating Your Solutions and Projects
Starting Your Domain Model
Creating an Abstract Repository
Making a Fake Repository
Displaying a List of Products
Removing Unnecessary Files
Adding the First Controller
Setting Up the Default Route
Adding the First View
Connecting to a Database
Defining the Database Schema
Setting Up LINQ to SQL
Creating a Real Repository
Setting Up Inversion of Control
Creating a Custom Controller Factory
Using Your IoC Container
Creating Automated Tests
Configuring a Custom URL Schema
Adding a RouteTable Entry
Displaying Page Links
Styling It Up
Defining Page Layout in the Master Page
Adding CSS Rules
Creating a Partial View

CHAPTER 5 : SportsStore: Navigation andShopping Cart

Adding Navigation Controls
Filtering the Product List
Defining a URL Schema for Categories
Building a Category Navigation Menu
Building the Shopping Cart
Defining the Cart Entity
Adding “Add to Cart” Buttons
Giving Each Visitor a Separate Shopping Cart
Creating CartController
Displaying the Cart
Removing Items from the Cart
Displaying a Cart Summary in the Title Bar
Submitting Orders
Enhancing the Domain Model
Adding the “Check Out Now” Button
Prompting the Customer for Shipping Details
Defining an Order Submitter IoC Component
Completing CartController
Implementing the EmailOrderSubmitter

CHAPTER 6 : SportsStore: Administrationand Final Enhancements

Adding Catalog Management
Creating AdminController: A Place for the CRUD Features
Rendering a Grid of Products in the Repository
Building a Product Editor
Creating New Products
Deleting Products
Securing the Administration Features
Setting Up Forms Authentication
Using a Filter to Enforce Authentication
Displaying a Login Prompt
Image Uploads
Preparing the Domain Model and Database
Accepting File Uploads
Displaying Product Images

Part 2: ASP.NET MVC in Detail

CHAPTER 7 : Overview of ASP.NET MVC Projects

Developing MVC Applications in Visual Studio
The Default MVC Project Structure
Naming Conventions
The Initial Application Skeleton
Debugging MVC Applications and Unit Tests
Using the Debugger
Stepping into the .NET Framework Source Code
Stepping into the ASP.NET MVC Source Code
The Request Processing Pipeline
Stage 1: IIS
Stage 2: Core Routing
Stage 3: Controllers and Actions
Stage 4: Action Results and Views

CHAPTER 8 : URLs and Routing

Putting the Programmer Back in Control
Setting Up Routes
Understanding the Routing Mechanism
Adding a Route Entry
Using Parameters
Using Defaults
Using Constraints
Accepting a Variable-Length List of Parameters
Matching Files on the Server’s Hard Disk
Using IgnoreRoute to Bypass the Routing System
Generating Outgoing URLs
Generating Hyperlinks with Html.ActionLink
Generating Links and URLs from Pure Routing Data
Performing Redirections to Generated URLs
Understanding the Outbound URL-Matching Algorithm
Generating Hyperlinks with Html.ActionLink<T> and Lambda Expressions
Working with Named Routes
Unit Testing Your Routes
Testing Inbound URL Routing
Testing Outbound URL Generation
Further Customization
Implementing a Custom RouteBase Entry
Implementing a Custom Route Handler
URL Schema Best Practices
Make Your URLs Clean and Human-Friendly
Follow HTTP Conventions
Search Engine Optimization

CHAPTER 9 : Controllers and Actions

An Overview
Comparisons with ASP.NET WebForms
All Controllers Implement IController
The Controller Base Class
Receiving Input
Getting Data from Context Objects
Using Action Method Parameters
Invoking Model Binding Manually in an Action Method
ProducingOutput
Understanding the ActionResult Concept
Returning HTML by Rendering a View
Performing Redirections
Returning Textual Data
Returning JSON Data
Returning JavaScript Commands
Returning Files and Binary Data
Creating a Custom Action Result Type
Using Filters to Attach Reusable Behaviors
Introducing the Four Basic Types of Filters
Applying Filters to Controllers and Action Methods
Creating Action Filters and Result Filters
Creating and Using Authorization Filters
Creating and Using Exception Filters
Bubbling Exceptions Through Action and Result Filters
The [OutputCache] Action Filter
Other Built-In Filter Types
Controllers As Part of the Request Processing Pipeline
Working with DefaultControllerFactory
Creating a Custom Controller Factory
Customizing How Action Methods Are Selected and Invoked
Testing Controllers and Actions
How to Arrange, Act, and Assert
Testing a Choice of View and ViewData
Testing Redirections
More Comments About Testing
Mocking Context Objects

CHAPTER 10 : Views

How Views Fit into ASP.NET MVC
The WebForms View Engine
View Engines Are Replaceable
WebForms View Engine Basics
Adding Content to a View Template
Five Ways to Add Dynamic Content to a View Template
Using Inline Code
Why Inline Code Is a Good Thing in MVC View Templates
Understanding How MVC Views Actually Work
Understanding How ASPX Templates Are Compiled
Understanding ViewData
Rendering ViewData Items Using ViewData.Eval
Using HTML Helper Methods
The Framework’s Built-In Helper Methods
Creating Your Own HTML Helper Methods
Using Partial Views
Creating a Partial View
Rendering a Partial View Using Server Tags
Using Html.RenderAction to Create Reusable Widgets with
Application Logic
What Html.RenderAction Does
When It’s Appropriate to Use Html.RenderAction
Creating a Widget Based on Html.RenderAction
Sharing Page Layouts Using Master Pages
Using Widgets in MVC View Master Pages
Implementing a Custom View Engine
A View Engine That Renders XML Using XSLT
Using Alternative View Engines
Using the NVelocity View Engine
Using the Brail View Engine
Using the Spark View Engine
Using the NHaml View Engine

CHAPTER 11 : Data Entry

Model Binding
Model-Binding to Action Method Parameters
Model-Binding to Custom Types
Invoking Model Binding Directly
Model-Binding to Arrays, Collections, and Dictionaries
Creating a Custom Model Binder
Using Model Binding to Receive File Uploads
Validation
Registering Errors in ModelState
View Helpers for Displaying Error Information
How the Framework Maintains State in Input Controls
Performing Validation During Model Binding
Moving Validation Logic into Your Model Layer
About Client-Side (JavaScript) Validation
Wizards and Multistep Forms
Verification
Implementing a CAPTCHA
Confirmation Links and Tamper-Proofing with HMAC Codes

CHAPTER 12 : Ajax and Client Scripting

Why You Should Use a JavaScript Toolkit
ASP.NET MVC’s Ajax Helpers
Fetching Page Content Asynchronously Using Ajax.ActionLink
Submitting Forms Asynchronously Using Ajax.BeginForm
Invoking JavaScript Commands from an Action Method
Reviewing ASP.NET MVC’s Ajax Helpers
Using jQuery with ASP.NET MVC
Referencing jQuery
Basic jQuery Theory
Adding Client-Side Interactivity to an MVC View
Ajax-Enabling Links and Forms
Client/Server Data Transfer with JSON
Fetching XML Data Using jQuery
Animations and Other Graphical Effects
jQuery UI’s Prebuilt User Interface Widgets
Implementing Client-Side Validation with jQuery
Summarizing jQuery

CHAPTER 13 : Security and Vulnerability

All Input Can Be Forged
Forging HTTP Requests
Cross-Site Scripting and HTML Injection
Example XSS Vulnerability
ASP.NET’s Request Validation Feature
Filtering HTML Using the HTML Agility Pack
Session Hijacking
Defense via Client IP Address Checks
Defense by Setting the HttpOnly Flag on Cookies
Cross-Site Request Forgery
Attack
Defense
Preventing CSRF Using the Anti-Forgery Helpers
SQL Injection
Attack
Defense by Encoding Inputs
Defense Using Parameterized Queries
Defense Using Object-Relational Mapping
Using the MVC Framework Securely
Don’t Expose Action Methods Accidentally
Don’t Allow Model Binding to Change Sensitive Properties

CHAPTER 14 : Deployment

Server Requirements
Requirements for Shared Hosting
IIS Basics
Understanding Web Sites and Virtual Directories
Binding Web Sites to Hostnames, IP Addresses, and Ports
How IIS Handles Requests and Invokes ASP.NET
Deploying Your Application
Copying Your Application Files to the Server
Using Visual Studio ’s Publish Feature
Making It Work on Windows Server /IIS 6
Making It Work on IIS 7
Making Your Application Behave Well in Production
Supporting Changeable Routing Configurations
Supporting Virtual Directories
Using ASP.NET’s Configuration Facilities
Controlling Compilation on the Server
Detecting Compiler Errors in Views Before Deployment

CHAPTER 15 : ASP.NET Platform Features

Windows Authentication
Preventing or Limiting Anonymous Access
Forms Authentication
Setting Up Forms Authentication
Using Cookieless Forms Authentication
Membership, Roles, and Profiles
Setting Up a Membership Provider
Using a Membership Provider with Forms Authentication
Creating a Custom Membership Provider
Setting Up and Using Roles
Setting Up and Using Profiles
URL-Based Authorization
Data Caching
Reading and Writing Cache Data
Using Advanced Cache Features
Site Maps
Setting Up and Using Site Maps
Creating a Custom Navigation Control with the Site Maps API
Generating Site Map URLs from Routing Data
Internationalization
Setting Up Internationalization
Tips for Working with Resource Files
Using Placeholders in Resource Strings
Performance
HTTP Compression
Tracing and Monitoring
Monitoring Page Generation Times
Monitoring LINQ to SQL Database Queries

CHAPTER 16 : Combining MVC and WebForms

Using WebForms Technologies in an MVC Application
Using WebForms Controls in MVC Views
Using WebForms Pages in an MVC Web Application
Adding Routing Support for WebForms Pages
Using ASP.NET MVC in a WebForms Application
Upgrading an ASP.NET WebForms Application to Support MVC
Getting Visual Studio to Offer MVC Items
Interactions Between WebForms Pages and MVC Controllers
Site Meter