Log In
Or create an account ->
Imperial Library
Home
About
News
Upload
Forum
Help
Login/SignUp
Index
Programming ASP.NET MVC 4
SPECIAL OFFER: Upgrade this ebook with O’Reilly
Preface
Audience
Assumptions This Book Makes
Conventions Used in This Book
Using Code Examples
Safari® Books Online
How to Contact Us
I. Up and Running
1. Fundamentals of ASP.NET MVC
Microsoft’s Web Development Platforms
Active Server Pages (ASP)
ASP.NET Web Forms
ASP.NET MVC
The Model-View-Controller Architecture
The Model
The View
The Controller
What’s New in ASP.NET MVC 4?
Introduction to EBuy
Installing ASP.NET MVC
Creating an ASP.NET MVC Application
Project Templates
Convention over Configuration
Running the Application
Routing
Configuring Routes
Controllers
Controller Actions
Action Results
Action Parameters
Model binding basics
Model binding complex objects
Action Filters
Views
Locating Views
Hello, Razor!
Differentiating Code and Markup
Code nuggets
Code blocks
Layouts
Partial Views
Displaying Data
Cleaner access to ViewData values via ViewBag
View models
Strongly typed views
HTML and URL Helpers
Models
Putting It All Together
The Route
The Controller
Controller templates
The View
Authentication
The AccountController
Summary
2. ASP.NET MVC for Web Forms Developers
It’s All Just ASP.NET
Tools, Languages, and APIs
HTTP Handlers and Modules
Managing State
Deployment and Runtime
More Differences than Similarities
Separation of Application Logic and View Logic
URLs and Routing
State Management
Rendering HTML
HTML helpers versus server controls
Partial views versus user controls
Layouts versus master pages
Authoring ASP.NET MVC Views Using Web Forms Syntax
A Word of Caution
Summary
3. Working with Data
Building a Form
Handling Form Posts
Saving Data to a Database
Entity Framework Code First: Convention over Configuration
Creating a Data Access Layer with Entity Framework Code First
Validating Data
Specifying Business Rules with Data Annotations
Required fields
Valid ranges
Custom error messages
Displaying Validation Errors
Summary
4. Client-Side Development
Working with JavaScript
Selectors
Responding to Events
DOM Manipulation
AJAX
Client-Side Validation
Summary
II. Going to the Next Level
5. Web Application Architecture
The Model-View-Controller Pattern
Separation of Concerns
MVC and Web Frameworks
Architecting a Web Application
Logical Design
ASP.NET MVC Web Application Logical Design
Logical Design Best Practices
Physical Design
Project Namespace and Assembly Names
Deployment Options
Physical Design Best Practices
Performance and scalability
Bandwidth and latency
Design Principles
SOLID
The Single Responsibility Principle
The Open/Closed Principle
The Liskov Substitution Principle
The Interface Segregation Principle
The Dependency Inversion Principle
Inversion of Control
Understanding dependencies
Service location
Dependency injection
Picking an IoC container
Using Inversion of Control to extend ASP.NET MVC
Don’t Repeat Yourself
Summary
6. Enhancing Your Site with AJAX
Partial Rendering
Rendering Partial Views
Rendering a “normal” view
Rendering a partial view
Managing complexity with partial views
JavaScript Rendering
Rendering JSON Data
Avoiding JSON hijacking with JsonRequestBehavior
Requesting JSON Data
Client-Side Templates
Reusing Logic Across AJAX and Non-AJAX Requests
Responding to AJAX Requests
Responding to JSON Requests
Applying the Same Logic Across Multiple Controller Actions
Sending Data to the Server
Posting Complex JSON Objects
Model Binder Selection
Replacing the default (fallback) binder
Adorning models with custom attributes
Registering a global binder
Sending and Receiving JSON Data Effectively
Cross-Domain AJAX
JSONP
Making a JSONP request
Adding JSONP support to ASP.NET MVC controller actions
Enabling Cross-Origin Resource Sharing
Summary
7. The ASP.NET Web API
Building a Data Service
Registering Web API Routes
Leaning on Convention over Configuration
Overriding Conventions
Hooking Up the API
Paging and Querying Data
Exception Handling
Media Formatters
Summary
8. Advanced Data
Data Access Patterns
Plain Old CLR Objects
Using the Repository Pattern
Object Relational Mappers
Entity Framework Overview
Choosing a Data Access Approach
Database Concurrency
Building a Data Access Layer
Using Entity Framework Code First
Code First data annotations
Overriding conventions
The EBuy Business Domain Model
Working with a Data Context
Sorting, Filtering, and Paging Data
Summary
9. Security
Building Secure Web Applications
Defense in Depth
Never Trust Input
Enforce the Principle of Least Privilege
Assume External Systems Are Insecure
Reduce Surface Area
Disable Unnecessary Features
Securing an Application
Securing an Intranet Application
Setting up Windows Authentication
Configuring IIS Express
Configuring IIS 7
Using the AuthorizeAttribute
Forms Authentication
AccountController
Authenticating users
Registering new users
Changing passwords
Interacting via AJAX
User authorization
Guarding Against Attacks
SQL Injection
Cross-Site Scripting
Cross-Site Request Forgery
Using ASP.NET MVC to avoid Cross-Site Request Forgery
Summary
10. Mobile Web Development
ASP.NET MVC 4 Mobile Features
Making Your Application Mobile Friendly
Creating the Auctions Mobile View
Getting Started with jQuery Mobile
Enhancing the View with jQuery Mobile
Improving the auctions list with jQuery Mobile’s “listview”
Making the auctions list searchable with jQuery Mobile’s “data-filter”
Switching between desktop and mobile views
Avoiding Desktop Views in the Mobile Site
Improving Mobile Experience
Adaptive Rendering
The Viewport Tag
Mobile Feature Detection
CSS Media Queries
Browser-Specific Views
Creating a New Mobile Application from Scratch
The jQuery Mobile Paradigm Shift
The ASP.NET MVC 4 Mobile Template
Using the ASP.NET MVC 4 Mobile Application Template
Summary
III. Going Above and Beyond
11. Parallel, Asynchronous, and Real-Time Data Operations
Asynchronous Controllers
Creating an Asynchronous Controller
Choosing When to Use Asynchronous Controllers
Real-Time Asynchronous Communication
Comparing Application Models
HTTP Polling
Browser support
Downsides
HTTP Long Polling
Browser support
Downsides
Server-Sent Events
Browser support
Downsides
WebSockets
Browser support
Downsides
Empowering Real-Time Communication
Persistent connections
Hubs
Configuring and Tuning
Managing SignalR connections
Configuring the environment
Summary
12. Caching
Types of Caching
Server-Side Caching
Client-Side Caching
Server-Side Caching Techniques
Request-Scoped Caching
User-Scoped Caching
Session lifetime
Storing session data
Application-Scoped Caching
The ASP.NET Cache
Expiration
Cache dependencies
Scavenging
The Output Cache
Configuring the cache location
Varying the output cache based on request parameters
Output cache profiles
Donut Caching
Donut Hole Caching
Distributed Caching
Distributed caching solutions
Installing Velocity
Administering your memory cluster from PowerShell
Using the cache
Client-Side Caching Techniques
Understanding the Browser Cache
App Cache
Define the manifest
Reference the manifest
Serve the manifest correctly
Local Storage
Summary
13. Client-Side Optimization Techniques
Anatomy of a Page
Anatomy of an HttpRequest
Best Practices
Make Fewer HTTP Requests
Use a Content Delivery Network
Add an Expires or a Cache-Control Header
Set up client caching in IIS
Set up client caching through ASP.NET MVC
Cache busting
GZip Components
Put Stylesheets at the Top
Put Scripts at the Bottom
Defer script execution
Lazy loading scripts
Make Scripts and Styles External
Reduce DNS Lookups
Minify JavaScript and CSS
Avoid Redirects
Remove Duplicate Scripts
Configure ETags
Measuring Client-Side Performance
Putting ASP.NET MVC to Work
Bundling and Minification
Defining bundles
Enabling bundles
Cache busting
Summary
14. Advanced Routing
Wayfinding
URLs and SEO
Building Routes
Default and Optional Route Parameters
Routing Order and Priority
Routing to Existing Files
Ignoring Routes
Catch-All Routes
Route Constraints
Peering into Routes Using Glimpse
Attribute-Based Routing
Extending Routing
The Routing Pipeline
Summary
15. Reusable UI Components
What ASP.NET MVC Offers out of the Box
Partial Views
HtmlHelper Extensions or Custom HtmlHelpers
Display and Editor Templates
Html.RenderAction()
Taking It a Step Further
The Razor Single File Generator
Installing the Razor Single File Generator
Creating Reusable ASP.NET MVC Views
Including Precompiled views in an ASP.NET MVC web application
Creating Reusable ASP.NET MVC Helpers
Unit Testing Razor Views
Summary
IV. Quality Control
16. Logging
Error Handling in ASP.NET MVC
Enabling Custom Errors
Handling Errors in Controller Actions
Defining Global Error Handlers
Customizing the error page
Logging and Tracing
Logging Errors
Simple try/catch handler
Overriding Controller.OnException()
Custom error filters
ASP.NET Health Monitoring
Summary
17. Automated Testing
The Semantics of Testing
Manual Testing
Humans are error prone
Computers are more efficient
Manual testing takes time
Automated Testing
Levels of Automated Testing
Unit Tests
Atomic
Repeatable
Isolated/Independent
Fast
Integration Tests
Acceptance Tests
User acceptance testing
What Is an Automated Test Project?
Creating a Visual Studio Test Project
Creating and Executing a Unit Test
Testing an ASP.NET MVC Application
Testing the Model
Focus on the positive
Protect against the negative
Test-Driven Development
Writing Clean Automated Tests
Duplicate code
Naming
Testing Controllers
Testing data access logic
Refactoring to Unit Tests
Mocking Dependencies
Manually creating mock objects
Using a mock framework
Testing Views
Testing application logic in the browser
Code Coverage
The Myth of 100% Code Coverage
Developing Testable Code
Summary
18. Build Automation
Creating Build Scripts
Visual Studio Projects Are Build Scripts!
Adding a Simple Build Task
Executing the Build
Building in Visual Studio
Building from the command line
The Possibilities Are Endless!
Automating the Build
Types of Automated Builds
Creating the Automated Build
Continuous Integration
Discovering Issues
The Principles of Continuous Integration
Maintain a single source repository
Automate the build
Make your build self-testing
Have everyone commit to the mainline frequently
Every commit should build the mainline on an integration machine
Keep the build fast
Test in a clone of the production environment
Make it easy for anyone to get the latest executable
Everyone can see what’s happening
Automate deployment
Summary
V. Going Live
19. Deployment
What Needs to Be Deployed
Core Website Files
“bin-deploying” ASP.NET MVC libraries
Static Content
What Not to Deploy
Databases and Other External Dependencies
What the EBuy Application Requires
Deploying to Internet Information Server
Prerequisites
Deploying the ASP.NET MVC Framework assemblies
Creating and Configuring an IIS Website
Publishing from Within Visual Studio
Copying files with MSBuild
Executing database scripts with MSBuild
Deploying to Windows Azure
Creating a Windows Azure Account
Creating a New Windows Azure Website
Publishing a Windows Azure Website via Source Control
Summary
VI. Appendixes
A. ASP.NET MVC and Web Forms Integration
Choosing Between ASP.NET MVC and ASP.NET Web Forms
Transitioning a Web Forms Site to ASP.NET MVC
Adding ASP.NET MVC to an Existing Web Forms Application
Copying Web Forms Functionality to an ASP.NET MVC Application
Integrating Web Forms and ASP.NET MVC Functionality
User Management
Cache Management
Many, Many More!
Summary
B. Leveraging NuGet as a Platform
Installing the NuGet Command-Line Tool
Creating NuGet Packages
The NuSpec File
Using the NuGet command-line tool
Using the NuGet Package Explorer
Generating the NuGet Package from a NuSpec File
Specifying token values
Setting the version
The Anatomy of a NuGet Package
Content
Assemblies
Tools
Types of NuGet Packages
Assembly Packages
Tool Packages
Meta Packages
Sharing Your NuGet Packages
Publishing to the Public NuGet.org Package Repository
Using the NuGet.org package upload wizard
Using the NuGet command-line tool
Host Your Own Package Repository
Using a filesystem repository
Hosting a NuGet Server repository
Tips, Tricks, and Pitfalls
Pitfall: NuGet Does Not Solve “DLL Hell”
Tip: Use Install-Package -Version to Install a Specific Package Version
Tip: Use Semantic Versioning
Tip: Mark “Beta” Packages with Prerelease Version Markers
Pitfall: Avoid Specifying “Strict” Version Dependencies in Your NuSpec Files
Tip: Use Custom Repositories to Control Package Versions
Tip: Configure Your Continuous Integration Builds to Generate NuGet Packages
Summary
C. Best Practices
Use the NuGet Package Manager to Manage Dependencies
Depend on Abstractions
Avoid the New Keyword
Avoid Referring to HttpContext Directly (Use HttpContextBase)
Avoid “Magic Strings”
Prefer Models over ViewData
Do Not Write HTML in “Backend” Code
Do Not Perform Business Logic in Views
Consolidate Commonly Used View Snippets with Helper Methods
Prefer Presentation Models over Direct Usage of Business Objects
Encapsulate if Statements with HTML Helpers in Views
Prefer Explicit View Names
Prefer Parameter Objects over Long Lists of Parameters
Encapsulate Shared/Common Functionality, Logic, and Data with Action Filters or Child Actions (Html.RenderAction)
Prefer Grouping Actions into Controllers Based on How They Relate to Business Concepts
Avoid Grouping Actions into Controllers Based on Technical Relation
Prefer Placing Action Filters at the Highest Appropriate Level
Prefer Multiple Views (and/or Partial Views) over Complex If-Then-Else Logic That Shows and Hides Sections
Prefer the Post-Redirect-Get Pattern When Posting Form Data
Prefer Startup Tasks over Logic Placed in Application_Start (Global.asax)
Prefer Authorize Attribute over Imperative Security Checks
Prefer Using the Route Attribute over More Generic Global Routes
Consider Using an Antiforgery Token to Avoid CSRF Attacks
Consider Using the AcceptVerbs Attribute to Restrict How Actions May Be Called
Consider Output Caching
Consider Removing Unused View Engines
Consider Custom ActionResults for Unique Scenarios
Consider Asynchronous Controllers for Controller Tasks That Can Happen in Parallel
D. Cross-Reference: Targeted Topics, Features, and Scenarios
Index
About the Authors
Colophon
SPECIAL OFFER: Upgrade this ebook with O’Reilly
Copyright
← Prev
Back
Next →
← Prev
Back
Next →