Nothing Special   »   [go: up one dir, main page]

Test Drive ASP NET MVC 1st Edition Jonathan Mccracken Download PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 64

Full download test bank at ebookmeta.

com

Test Drive ASP NET MVC 1st Edition Jonathan


Mccracken

For dowload this book click LINK or Button below

https://ebookmeta.com/product/test-drive-asp-net-
mvc-1st-edition-jonathan-mccracken/

OR CLICK BUTTON

DOWLOAD EBOOK

Download More ebooks from https://ebookmeta.com


More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Test Drive ASP NET MVC 1st Edition Jonathan Mccracken

https://ebookmeta.com/product/test-drive-asp-net-mvc-1st-edition-
jonathan-mccracken-2/

ASP NET Core MVC 2 0 Cookbook Effective ways to build


modern interactive web applications with ASP NET Core
MVC 2 0 1st Edition Engin Polat

https://ebookmeta.com/product/asp-net-core-mvc-2-0-cookbook-
effective-ways-to-build-modern-interactive-web-applications-with-
asp-net-core-mvc-2-0-1st-edition-engin-polat/

Introduction to the Development of Web Applications


Using ASP Net Core MVC Synthesis Lectures on Computer
Science Razvan Alexandru Mezei

https://ebookmeta.com/product/introduction-to-the-development-of-
web-applications-using-asp-net-core-mvc-synthesis-lectures-on-
computer-science-razvan-alexandru-mezei/

ASP NET Core Security 1st Edition Christian Wenz

https://ebookmeta.com/product/asp-net-core-security-1st-edition-
christian-wenz-2/
ASP NET Core 6 Succinctly Dirk Strauss

https://ebookmeta.com/product/asp-net-core-6-succinctly-dirk-
strauss/

Ultra Fast ASP NET Building Ultra fast and Ultra


scalable Web Sites Using ASP NET and SQL Server 1st
Edition Richard Kiessig

https://ebookmeta.com/product/ultra-fast-asp-net-building-ultra-
fast-and-ultra-scalable-web-sites-using-asp-net-and-sql-
server-1st-edition-richard-kiessig/

ASP NET Core in Action Second Edition Andrew Lock

https://ebookmeta.com/product/asp-net-core-in-action-second-
edition-andrew-lock/

Pro ASP NET Core 7 MEAP 10th Edition Adam Freeman

https://ebookmeta.com/product/pro-asp-net-core-7-meap-10th-
edition-adam-freeman/

Building ASP NET Web Pages with Microsoft WebMatrix 1st


Edition Steve Lydford

https://ebookmeta.com/product/building-asp-net-web-pages-with-
microsoft-webmatrix-1st-edition-steve-lydford/
Test-Drive ASP.NET MVC

Jonathan McCracken

The Pragmatic Bookshelf

Raleigh, North Carolina Dallas, Texas


Many of the designations used by manufacturers and sellers to
distinguish their products are claimed as trademarks. Where those
designations appear in this book, and The Pragmatic Programmers,
LLC was aware of a trademark claim, the designations have been
printed in initial capital letters or in all capitals. The Pragmatic
Starter Kit, The Pragmatic Programmer, Pragmatic Programming,
Pragmatic Bookshelf and the linking g device are trademarks of The
Pragmatic Programmers, LLC.

Every precaution was taken in the preparation of this book. However,


the publisher assumes no responsibility for errors or omissions, or
for damages that may result from the use of information (including
program listings) contained herein.

Our Pragmatic courses, workshops, and other products can help you
and your team create better software and have more fun. For more
information, as well as the latest Pragmatic titles, please visit us at
http://www.pragprog.com.

The team that produced this book includes:


Editor:

Susannah Davidson Pfalzer

Indexing:

Seth Maislin

Copy edit:

Kim Wimpsett

Layout:

Steve Peter

Production:

Janet Furlow

Customer support: Ellie Callahan

International:

Juliet Benda

Copyright © 2010 Pragmatic Programmers, LLC.

All rights reserved.

No part of this publication may be reproduced, stored in a retrieval


system, or transmit-ted, in any form, or by any means, electronic,
mechanical, photocopying, recording, or otherwise, without the prior
consent of the publisher.

Printed in the United States of America.

ISBN-10: 1-934356-53-0
ISBN-13: 978-1-934356-53-1

Printed on acid-free paper.

P1.0 printing, June 2010

Version: 2010-6-28

Contents

Acknowledgments

Preface

10

What Makes ASP.NET MVC Special? . . . . . . . . . . . . . . .

10

Why Test-Driven Development? . . . . . . . . . . . . . . . . . .

12

Who Should Read This Book? . . . . . . . . . . . . . . . . . . .

13

What’s in This Book? . . . . . . . . . . . . . . . . . . . . . . . .

13

What’s New in ASP.NET MVC 2.0? . . . . . . . . . . . . . . . .

14

Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . .
16

Fundamentals

17

Getting Started with ASP.NET MVC

18

1.1

How ASP.NET MVC Works . . . . . . . . . . . . . . . . .

18

1.2

Installing MVC . . . . . . . . . . . . . . . . . . . . . . . .

21

1.3

MVC in Five Minutes: Building Quote-O-Matic . . . . .

24

Test-Driven Development

31

2.1
TDD Explained . . . . . . . . . . . . . . . . . . . . . . .

31

2.2

Test-Driving “Hello World” . . . . . . . . . . . . . . . . .

36

II Building an Application

42

Getting Organized with MVC

43

3.1

Time Management with GetOrganized . . . . . . . . . .

43

3.2

Reading Data . . . . . . . . . . . . . . . . . . . . . . . .

45

3.3

Creating a To-Do . . . . . . . . . . . . . . . . . . . . . .

56

3.4
Deleting: Creating an Action Without a View . . . . . .

62

3.5

Updating: Marking a To-Do as Complete . . . . . . . .

66

CONTENTS

Working with Controllers

71

4.1

Creating Topics . . . . . . . . . . . . . . . . . . . . . . .

72

4.2

Using the FormCollection and TempData Objects . . .

77

4.3

Adding a Little Color with jQuery . . . . . . . . . . . . .

80

4.4
Controllers Talking to Controllers . . . . . . . . . . . .

87

Managing State and Files with Controllers

93

5.1

Enabling Filters and Results with Controllers . . . . .

93

5.2

Logging In . . . . . . . . . . . . . . . . . . . . . . . . . . 100

5.3

Testing Routes in MVC . . . . . . . . . . . . . . . . . . . 109

5.4

Storing Information in Memory . . . . . . . . . . . . . . 109

5.5

Manipulating Files . . . . . . . . . . . . . . . . . . . . . 119

Enhancing Views with HTML Helpers and Master Pages

127

6.1
Making Our Site Presentable with HTML Helpers . . . 128

6.2

Building a Custom HTML Helper . . . . . . . . . . . . . 135

6.3

Simplifying Page Layouts with Master Pages . . . . . . 139

6.4

Adding Validations Using ModelStateDictionary . . . . 143

6.5

Replacing Web Controls with Advanced HTML Helpers

146

Composing Views with Ajax and Partials

151

7.1

Working with Ajax . . . . . . . . . . . . . . . . . . . . . . 152

7.2

Finding It in a Snap with Autocomplete . . . . . . . . . 157

7.3

Using Partials to Reduce Duplication . . . . . . . . . . 161

III Integrating with Other Frameworks


171

Persisting Your Models

172

8.1

MVC’s Next Top Model: NHibernate . . . . . . . . . . . 173

8.2

Using the Repository Pattern . . . . . . . . . . . . . . . 174

8.3

Mapping with Fluent NHibernate . . . . . . . . . . . . . 177

8.4

Creating and Reading Records . . . . . . . . . . . . . . 179

8.5

Editing Models . . . . . . . . . . . . . . . . . . . . . . . . 183

8.6

Deleting Records . . . . . . . . . . . . . . . . . . . . . . 185

8.7

Additional ORM Data Relationships . . . . . . . . . . . 186

Integrating Repositories with Controllers


188

9.1

Fixing the NHibernate Session Inside MVC . . . . . . . 189

9.2

Using Inversion of Control with the IControllerFactory

192

9.3

Injecting Repositories into Controllers . . . . . . . . . . 197

9.4

Creating a Custom Action Filter

. . . . . . . . . . . . . 200

Report erratum

this copy is (P1.0 printing, June 2010)

CONTENTS

9.5

Linking NHibernate and MVC Validations . . . . . . . . 203

9.6

Preventing Performance Problems with Profiling . . . . 206

10 Building RESTful Web Services


210

10.1 Use SOAP or Take a REST Instead? . . . . . . . . . . . 210

10.2 Creating a Web Service . . . . . . . . . . . . . . . . . . . 213

10.3 Publishing to Blogger . . . . . . . . . . . . . . . . . . . . 220

IV Security and Deployment

228

11 Security, Error Handling, and Logging

229

11.1 Applying Additional Security . . . . . . . . . . . . . . . 230

11.2 Using an Action Filter to Handle Errors . . . . . . . . . 238

11.3 Using Logging to See What Went Wrong . . . . . . . . . 241

11.4 Checking for a Pulse with ASP.NET Health Monitoring

245

12 Build and Deployment

247

12.1 Automating Builds . . . . . . . . . . . . . . . . . . . . . 247

12.2 Using MSBuild to Automate the Build . . . . . . . . . . 249

12.3 Deploying to Production . . . . . . . . . . . . . . . . . . 259

Bibliography
268

Index

270

Report erratum

this copy is (P1.0 printing, June 2010)

Acknowledgments

Just like a movie, a book couldn’t happen without the support of


many

others who don’t appear on the front cover.

I’d like to thank my publishers, Dave and Andy, who not only
provided

the opportunity for me to write this book but who also have
published

and written some of my favorite technical books. They also assigned

me a talented and dedicated editor, Susannah Pfalzer. She’s been my

guide throughout this journey, and without her encouragement and

constructive feedback, the text would not be where it is today.


Thanks,

Susannah!

Thanks to Clinton Begin and Mike Mason for providing role models of

how a developer at heart can turn into an author. I’d like to thank
the crew of ThoughtWorks University XII—Sumeet Moghe, Krishnan

Nair, Deepthi Chandramouli, Michael Aguilar, Deepali Pawar, and Rixt

Wiersma—who all helped me get started on writing this book. Also,

thanks to all the men and women at ThoughtWorks Canada who


pro-

vide me with the opportunity every day to work alongside such


passion-

ate software professionals.

I also had some in-depth reviewers who helped shape the code and

tutorials of this book. These included David Cameron, my long-time

friend who also taught me how do debug Pascal back in the sixth
grade

and worked through the code in this book line by line; Scott Muc, a

developer whose tenacity helped give more form to Part III of the
book;

John Finlay, a programmer who reviewed this book while simultane-

ously explaining to me why the Hadron Collider will not cause Earth

to be sucked into a massive black hole; Radu Muresan, the Roma-

nian who taught me English grammar; and Jennifer Smith, a fellow

ThoughtWorker whose detailed comments gave me a ton of ideas


for

improvement.
ACKNOWLEDGMENTS

Several other reviewers also gave their feedback at different parts of


this project. I’d like to thank Puneet Goyal, Ted Neward, Siva
Pinnaka, Paul

Reimer, Ravi Kumar Pasumarthy, Xingrui Pei, Jeff Cohen, Joe Poon,

Ellen Flookes, and Sharan Karanth.

A huge thanks go to my family for supporting me through this


endeavor.

To my wife, Niki Rickhi, who cheered me on at every step. Niki, you


are

the most amazing person I know. To my dad, Jock McCracken, who

himself became an author a few years ago and has always


supported

me in following my own dreams. I’d also like to say a special thanks


to

DK Sing, for all your guidance and wisdom.

My final thanks is to you, the reader, who I hope enjoys the book as

much as I enjoyed writing it. May it help you along your adventures
in

ASP.NET MVC, TDD, and beyond.

Jonathan McCracken, April 2010

jon@nexicon.ca
Report erratum

this copy is (P1.0 printing, June 2010)

If at first the idea is not absurd, then there is no hope for it.

Albert Einstein

Preface

It’s testable. It’s lightweight. It’s open source. It’s . . . Microsoft?


Yes, ASP.NET MVC is an open source web application framework
created by

Microsoft to cater to the needs of agile software developers. Since its

official release in early 2009, it has been downloaded by almost 1


mil-

lion developers, and it is rapidly being adopted by many


organizations

because of its efficient development model. Simply put, it’s C# on


the

Web done right.

With this book’s test-driven approach to ASP.NET MVC, you’ll gain


the

cutting-edge skills to build your next web application and become a

more agile developer in the process.

What Makes ASP.NET MVC Special?

Microsoft offers two web presentation frameworks: ASP.NET Web


Forms
and ASP.NET MVC. ASP.NET itself is the common set of libraries and

features that both ASP.NET Web Forms and ASP.NET MVC work on
top

of. This supports customers’ existing needs with the older ASP.NET

Web Forms and their future needs with ASP.NET MVC. Although

ASP.NET MVC shares many of the same underpinnings of ASP.NET, it

overcomes its brother’s weaknesses. ASP.NET MVC was designed


using

the latest innovations and lessons learned on how to build web


appli-

cations. This adds up to big productivity improvements for your


teams.

Here’s what ASP.NET MVC offers that ASP.NET Web Forms doesn’t.

Full Control Over Markup

If you’ve ever developed an ASP.NET Web Forms website, you’ll


know

what a struggle it is to build a site for anything other than Internet

Explorer. This is partly because ASP.NET Web Forms was designed

for intranet applications where a single browser could be more easily

mandated. For most companies, supporting only one browser isn’t


an

WHAT MAKES ASP.NET MVC SPECIAL?


11

option anymore. Many companies are focusing on enabling their


part-

ners and customers to perform their work through web applications,


so

they need to support multiple browsers.

The Achilles’ heel of ASP.NET Web Forms is its bloated HTML. It gen-

erates complex markup through a string of embedded web and user

controls. ASP.NET MVC comes to the rescue with a much simpler


solu-

tion. Its default view engine, which is confusingly named the Web
Forms

view engine, gives you full control over your markup. No more
strange

id tags with $ and underscores in them. This pays off when dealing
with

client-side scripting such as JavaScript. You’ll find out more about


the

Web Forms view engine in Chapter 7, Composing Views with Ajax


and Partials, on page 151.

Testability

A web application framework that has out-of-the-box testing saves


you
a lot of time. Most developers building ASP.NET Web Forms
applications

had to use their own design patterns, such as Model-View-Presenter

(MVP), to accomplish this. For developers who don’t know much


about

unit testing, it’s less obvious how to approach testing. ASP.NET MVC

solves this with a clear way to test your code. I’ll be focusing on this

point heavily throughout the book to walk you through how to write
a

well-tested ASP.NET MVC application.

Convention Over Configuration

Following convention saves time. ASP.NET MVC’s timesaving conven-

tions keep you out of configuration files, and some conventions give

you added benefits, such as search engine optimization. For exam-

ple, in ASP.NET MVC, URLs to your site become more readable by

engines. Instead of http://yourblog.com/Blog/Entry.aspx?id=108 in


ASP.NET

Web Forms, ASP.NET MVC can do much better, such as


http://yourblog.

com/Blog/Entry/108/MVC-Makes-Search-Engines-Happy. You can


achieve the same thing with ASP.NET Web Forms, but it’s less
straightforward.1
With ASP.NET MVC, you get it for free. You’ll see more of these
conven-

tions throughout Part II, “Building an Application.”

Extensible Architecture

Striking a balance between conventions and extensibility is tricky for

web frameworks. If too many conventions are prescribed, they can

1.

http://weblogs.asp.net/scottgu/archive/2009/10/13/url-routing-with-
asp-net-4-web-forms-vs-2010-and-net-4-0-series.aspx

Report erratum

this copy is (P1.0 printing, June 2010)

WHY TEST -DRIVEN DEVELOPMENT?

12

restrict you from extending the framework when you need to do so.

The opposite is also true: if no conventions are set, then your team
has

to continue to reinvent the wheel.

ASP.NET MVC strikes a pretty good balance. It comes with a


powerful

default view engine but makes it easy to extend or create your own.

You’ll learn about this in Section 6.2, Building a Custom HTML


Helper, on page 135. ASP.NET MVC has a feature called action filters
that you can extend to provide helpful features such as transaction
support.

You’ll tackle this in Section 9.4, Creating a Custom Action Filter, on


page 200. Because ASP.NET MVC’s architecture has a single point of
creation for all the controllers, you can extend it with dependency
injection. Dependency injection decouples object behaviors, or, more
specif-

ically, the implementation of those behaviors. We pass the behavior


to

the constructor, effectively “injecting” it into the object. You’ll see


how to do this in Section 5.1, IControllerFactory: Where Controllers
Are Born, on page 98.

Finally, ASP.NET MVC isn’t tied to any single persistence framework

(see the Joe Asks. . . on page 19 for more on persistence


frameworks).

In fact, it doesn’t come bundled with one at all. This leaves room for

you to choose the right tool for the job. In this book, you’ll be using

NHibernate, one of the most popular open source persistence frame-

works. You’ll see how to use NHibernate in Chapter 8, Persisting


Your Models, on page 172.

Why Test-Driven Development?

Test-driven development (TDD) is a simple programming technique


that

drives your development by starting with a failing unit test. It’s


quickly becoming a standard practice on projects because TDD helps
you feel
more confident about your code. If you’ve never used TDD before,
then

Chapter 2, Test-Driven Development, on page 31 will show you how.

With TDD, you’ll spend much more time coding and much less time

fiddling around with the debugger.

The other key advantage to this method is that it helps you learn a

framework faster. Tests, when they pass, confirm that you’ve written

a bit of code correctly, and you can even dig into the tests that the

framework offers. Because ASP.NET MVC is open source, you’re free


to

browse all of its unit tests to help you gain an even better
understand-

ing of it.

Report erratum

this copy is (P1.0 printing, June 2010)

WHO SHOULD READ THIS BOOK?

13

And if you’re a seasoned test-driven developer who’s embarking on

learning ASP.NET MVC, this book will be your guide on how and
what

to test.
Who Should Read This Book?

This book was written for two audiences: Microsoft developers and

non-Microsoft developers. The goal for both is the same: to learn


how

to build an ASP.NET MVC application based on development best

practices.

For Microsoft developers with a long history of building applications

using Microsoft frameworks, the emphasis on TDD might be


unfamiliar

to you. Almost all the code examples in this book have been written

with TDD and are explained so that you can understand both how
the

tests work and how the ASP.NET MVC code works. Also, you’ll learn

about some tools and open source projects that can save you time
when

developing your ASP.NET MVC applications.

For non-Microsoft developers, you’ll find the methods of testing


famil-

iar, but learning the language and the framework will be your
primary

focus. Although this book assumes a basic knowledge of the C# lan-

guage, each tutorial explains line by line what the code is doing and
why it is important.

Although you can develop VB .NET web applications with ASP.NET

MVC, all the samples in this book are written in C#. If you’re
comfort-

able reading C# and translating for yourself, then you’ll be fine using

this book as your guide to ASP.NET MVC.

What’s in This Book?

Part I of this book shows you how to build an ASP.NET MVC


application

and introduces you to the TDD approach.

Part II focuses on building a sample application. You will work


through

test-driving core components of ASP.NET MVC, as well as other


essen-

tial frameworks that integrate with it. In Chapter 7, Composing


Views with Ajax and Partials, on page 151, you will focus on working
with jQuery.

Part III builds on the same application but introduces how to work
with

other frameworks. The database access in ASP.NET MVC is flexible,


and

Report erratum

this copy is (P1.0 printing, June 2010)


WHAT’S NEW IN ASP.NET MVC 2.0?

14

you’ll find out about NHibernate in Chapter 8, Persisting Your


Models, on page 172. Also, you’ll learn how to use the Castle
Windsor container in Chapter 9, Integrating Repositories with
Controllers, on page 188. To integrate with other applications, you’ll
also learn how to create Representational State Transfer (REST) web
services in Chapter 10, Building RESTful Web Services, on page 210.

Part IV focuses on deployment, something that many of us struggle

with. Chapter 12, Build and Deployment, on page 247 is dedicated


to this subject. You’ll also learn about nonfunctional requirements in

Chapter 11, Security, Error Handling, and Logging, on page 229.

To get the most out of this book, it’s highly recommended that you
code

through the problems while reading. Not only will this help you learn

the concepts of the framework and experience the subtle differences


in

each test, but, more important, you’ll master the test-driven


discipline.

This is a skill you’ll take with you to every language you program in.

Whether you are programming in C#, Java, or Ruby, knowing how to

write tests will help you write high-quality code in shorter periods of

time.

What’s New in ASP.NET MVC 2.0?


Since version 1.0 of ASP.NET MVC was released in March 2009, the

development team in Redmond has been working tirelessly at


improv-

ing the framework in the 2.0 release. More evolutionary than revolu-

tionary, these changes make view and model development easier.


Let’s

talk quickly about the new features.

Strongly Typed HTML Helpers

These new helpers reduce errors at compile time as well as the


number

of lines of code in your views. The helper methods are an improve-

ment over checking properties at runtime. For example, we’d do this


in

ASP.NET MVC 1.0 to render a textbox for a person:

Html.TextBox("Name" );

This standard Html helper renders a textbox. It’s linked to the Name

property of the model so that when it’s filled out, the model itself is

updated. In ASP.NET MVC 2.0, you do it like this:

Html.EditorFor(person => person.Name);

Report erratum

this copy is (P1.0 printing, June 2010)


WHAT’S NEW IN ASP.NET MVC 2.0?

15

Here the EditorFor( ) renders a textbox for the Person model and
checks

for the presence of the Name property at compile time. Compile-


time

checking alerts you early to typos that break your code. It also helps
if you rename properties of models that are referenced in views.

Html.EditorFor<Person>(person => person);

EditorFor( ) can also check for all the properties of the Person and
render them all for editing. In this case, the lambda expression we
pass is the

whole model, not just a single property. You’ll get to use the
DisplayFor( ) helper methods in Section 1.3, MVC in Five Minutes:
Building Quote-OMatic, on page 24.

Templated Views

Templated views build on what strongly typed view helpers allow us


to

do. With ASP.NET MVC 2.0, you can now create generic view
templates

that let you postpone customizing views. This works well for
prototyping

applications, such as when your pages need just enough information

to get feedback from your customer to know whether you’re on the


right track. Building your own templates is as simple as creating a

view under the View/Shared directory named after the controller’s


action.

Instead of creating a view per model to show or create details,


ASP.NET

MVC can fall back on your templated views. You’ll look at this feature

in Section 4.3, Adding Thoughts with Templated Views, on page 83.

Data Annotations

Data annotations are a way to mark up your models with validation

rules. For example, if you wanted to make sure that a user’s name
was

no longer than twenty-five characters, you could add this attribute:

[StringLength(25, ErrorMessage="Invalid Length" )]

public string Name {get; set;}

The attribute StringLength specifies a length of a maximum of


twenty-

five, and the ErrorMessage value will be the message you display to
the

user if they input a name that is too long or short. You’ll see more of

this in Section 6.4, Adding Validations Using ModelStateDictionary,


on page 143.

Other Features
Areas, asynchronous controllers, and Html.RenderAction( ) are other
use-

ful new features in ASP.NET MVC 2.0. Because they’re more


advanced

or specialized, they won’t be covered in this book. Areas extend the


way

Report erratum

this copy is (P1.0 printing, June 2010)

ONLINE RESOURCES

16

files are organized in an ASP.NET MVC project and are aimed at


larger

web applications (see Phil Haack’s blog2 for a tutorial on how to use

them). Asynchronous controllers are for long-running tasks that can

be run in parallel. Finally, Html.RenderAction( ) provides a more


efficient way for HTML to be written to the response.

Online Resources

At the website for this book, http://pragprog.com/titles/jmasp, you’ll


find the following:

• You’ll find the source code for all the snippets used in this book,

including the full codebase for the sample application from Parts

II and III. You can find the final solution in the GetOrganizedFinal
folder when you unzip it.

• You’ll find an errata page, where you can post errors you find in

the current edition.

• You’ll find a discussion forum where you can communicate with

me and other ASP.NET MVC developers directly.

In addition, once you get to the end of the book, Section 12.3,
That’s All, Folks, on page 267 will give you some additional online
resources to sites where you can further your learning.

Feel free to use the source code in your own applications. However,

keep in mind that not all the examples in the book are fit for
production code, because some are there to help you learn only. If
you’re reading

the ebook version of this book, you can download and play with the

code by clicking the little gray rectangle before the code listings.

Let’s get started with a high-level overview in Chapter 1, Getting


Started with ASP.NET MVC, on page 18, where we’ll build a simple
web application. Following that, in Chapter 2, Test-Driven
Development, on page 31,

we’ll learn the basics of this more efficient form of development.


With

that knowledge, we’ll be able to tackle building a full-featured end-


to-

end sample application for the rest of the book.

2.
http://haacked.com/archive/2010/01/12/ambiguous-controller-
names.aspx

Report erratum

this copy is (P1.0 printing, June 2010)

Part I

Fundamentals

To know an object is to lead to it through a context which the world


provides.

William James

Chapter 1

Getting Started

with ASP.NET MVC

In this chapter, you’ll get your feet wet by exploring the basics of the

ASP.NET MVC framework. You’ll find out how ASP.NET MVC works

differently than traditional ASP.NET. You’ll also learn how to install

MVC and the related software you’ll need for the rest of the book.

Finally, you’ll get hands-on and build a single page web application

called Quote-O-Matic.

Let’s start by exploring what makes ASP.NET MVC such a powerful


web

development tool.
1.1 How ASP.NET MVC Works

ASP.NET MVC represents a simpler, more testable framework for


devel-

oping web applications in Microsoft .NET.

When people reference the acronym MVC, they are most likely
referring

to the software design pattern. Model-View-Controller is a user inter-

face design pattern that separates display, data, and flow of control

into different objects (MVC was documented in Design Patterns: Ele-

ments of Reusable Object-Oriented Software [GHJV95] under the


name Observer). The view represents the screen and user input, the
controller

acts to coordinate the input/output from the view, and the model is
the

data structure that is passed between the two. The pattern helps
sepa-

rate the display, interaction, and data logic.

HOW ASP.NET MVC WORKS


19

Joe Asks. . .

What Is a Persistence Framework?

Generally speaking, a persistence framework is a library used

to simplify accessing and storing information. In practice, this

means how we write our code to communicate with the

relational database management system (RDMS). The cur-

rent trend in the industry is to use object-relational mapping

(ORM) persistence frameworks. These are abstract things such

as tables, columns, and rows, and they allow us to work pri-

marily with objects. Popular open source ORMs for .NET include

NHibernate and iBATIS.NET. Microsoft also provides both the

Entity Framework and LINQ to SQL as supported ORMs that can

easily work with MVC. In this book, we’ll use NHibernate since

it’s one of the most mature ORMs for .NET.

In ASP.NET MVC, the pattern is slightly different. Every request is

served by a controller; for example, http://localhost/ShoppingCart


will be directed to the ShoppingCartController. The controller then
makes some

changes to the model and selects a view to display. The model for
the
example is the ShoppingCart itself, and it contains information about

stuff you’d like to buy. The view then renders with the contents of

the model. In ASP.NET MVC, views are .aspx pages that contain
HTML

markup mixed with server-side coding. For our example, the default

view in the shopping cart example is Index.aspx.

In Section 1.3, MVC in Five Minutes: Building Quote-O-Matic, on


page 24,

we’ll implement this basic flow for a sample application. Refer to Fig-

ure 1.1, on the following page, which shows a typical MVC flow
working together as a user visits the Quote-O-Matic home page.

From here on, we’ll use the short form MVC to refer to ASP.NET MVC

for the rest of the book. If we need to talk about the design pattern

itself, we’ll say so specifically—otherwise, assume we’re talking about

ASP.NET MVC.

First, the user types a URL into the browser and hits the Enter key.

This creates a request to the web server that invokes the HomeCon-

troller’s default action, Index( ). The controller then calls the logic
within

Report erratum

this copy is (P1.0 printing, June 2010)


HOW ASP.NET MVC WORKS

20

! User Types in

URL

Index.aspx

(View)

% Renders

Home Controller

Quote Page

" Asks for a

Random

Quote

Quote

# Sends Information

(Model)

Back to Controller

Figure 1.1: ASP.NET MVC requests are serviced by controllers. The


con-

troller interacts with a model and then renders a view.

the Quote class, which is the model in this example. The Quote will
return a random quote to the HomeController. Finally, the controller
ren-

ders the default view, which is the Index.aspx file. The user sees the
page display in the browser.

For those familiar with ASP.NET Web Forms, there is a small learn-

ing curve when it comes to the way the programming model works
in

MVC. For example, ASP.NET Web Forms tries to mask the fact that

we are dealing with HTTP, a stateless communication protocol. It


does

this through the abstraction known as web controls and code-


behind.

This leads to stateful information being stored in something known


as

view state. MVC gets rid of view state and employs a more stateless

architecture.

With these MVC basics in mind, let’s move on to installing MVC so


that

you can see it in action.

Report erratum

this copy is (P1.0 printing, June 2010)

INSTALLING MVC

21
MVC on the Web

The MVC design pattern is in extensive use by other web frame-

works such as Rails, J2EE, Struts, Waffle, Django, and ErlyWeb,

to name a few. Microsoft’s ASP.NET MVC framework is a logi-

cal and major improvement over the open source MonoRail

project, which also uses the MVC design pattern.∗ ASP.NET MVC

has improved on Monorail’s view engine, has more persistence

layer options, and has official Microsoft support. Phil Haack (the

guy who helped prototype ASP.NET MVC) and his team have

taken the best of these frameworks and applied them to the

development of ASP.NET MVC.

∗.

http://www.castleproject.org/MonoRail/

1.2 Installing MVC

You need the following software to develop applications in MVC:

• .NET Framework 3.5 with Service Pack 1 or newer

• Microsoft Visual Studio 2008 Service Pack 1 or newer

• ASP.NET MVC 2.0

The following software, although not required, is highly


recommended
Another random document with
no related content on Scribd:
change this painful subject, she fell into a shy silence—which was
only broken at last by Mr. John himself.
“No, Lettie, I have not been always idle, and I have need,” said the
roused man; “and when I hear a little thing like you speaking about
work, and helping to keep a house, it makes me think shame of
myself, Lettie. You and your sisters, that might be so different,
working for your bread—and me this way!”
“Ay, but Miss Jeanie and Miss Aggie work more than we do,” said
Lettie, simply.
For always it is the angel from heaven, miraculous and strange, and
not the daily revelations of Moses and the prophets, which these
bewitched natures think will rouse them. Miss Jeanie and Miss
Aggie, with all their little vanities, had hearts sincere in this point, and
full of gracious unconscious humility. They never reminded the idler,
that they worked for him; never thought that they were pinched and
restrained, in the ostentations they held so dear, because “Johnnie”
hung a burden on their hands; never speculated, indeed, on the
question at all, nor dreamed of giving reasons to themselves for the
spontaneous natural impulse, which made this self-sacrifice
unawares. And he himself never realized it either; but he was struck
with the devotion of Martha and her household. This, unusual,
strange—a thing he did not see every day—moved him; the other
had scarcely occurred to him when Lettie spoke.
They left Glasgow the next day; for neither Agnes nor Rose could
bear to remain in this house, so familiar to them of old; and they did
not return to Mrs. Rodger’s on their way home; but when Miss Aggie
married the lumbering lodger, and came to be settled on the other
side of the Firth, at Alloa, and received her sister as a visitor, Miss
Jeanie made a pilgrimage to Allenders, and told them, with tears in
her eyes, that Johnnie, now a clerk with a Port Dundas merchant,
had said to her, that she should never want while he had anything,
and had given her money to buy the expensive unsuitable upper
garment she wore. Poor Miss Jeanie, with her vanities and
simplicities, never discovered that he owed her gratitude; but for
these words of kindness she was tearfully grateful to him.
The month at Ayr passed very quietly. In this winter weather Uncle
Sandy’s little company of workers could no longer visit the leafless
garden; and though there was sometimes a great fire made in the
kitchen, and a special lamp lighted for them, yet their own fireside,
the old man thought, was the most suitable place for them now. So
the family were almost perfectly alone; left to compose themselves
into those quiet days which were but the beginning of a subdued and
chastened life. And Uncle Sandy did for them now, what Martha was
wont to do through the terrible time which preceded Harry’s death.
He read to them sometimes;—sometimes he was himself their book
and reader; and from his long experience, the young hearts, fainting
under this great sorrow, learned how many trials life can live through,
and were unwillingly persuaded that the present affliction would not
kill them, as they sometimes hoped it might; but must lighten,
perhaps must pass away. But they clung the closer to their sorrow,
and defied the very chance of returning gladness; and Agnes cut
away the curls of her bright hair, and said she would wear this
widow’s cap her whole life through; and Rose grew sick at sounds of
laughter, and believed she would never smile again.
CHAPTER XX.

A gloomy piece this morning with it brings;


The sun for sorrow will not show his head.

romeo and juliet.


It was December, cold and dreary, when the family returned to
Allenders. Their very return was a renewal of the first sorrow to both
themselves and Martha. They came, and Harry was not there to
welcome them; they had never before felt so bitterly his absent
place; they came, but Harry came not with them—and Martha’s very
voice of welcome was choked with her anguish for the dead.
There had been much discussion with Uncle Sandy, whom they
were all anxious to induce to return to Allenders, and remain with
them there. The old man did not consent. Reluctant as he was to be
separated from them now, his own old house and neighbourhood
were parts of his gentle nature. He could not leave them—could not
relinquish his universal charge of “the bairns,” nor deprive his young
embroiderers of the air and sunshine, to which no one else might
think of admitting them. So Uncle Sandy brought his charge to
Glasgow, and bade them an affectionate farewell, promising a yearly
visit to Allenders; but he could not give up his little solitary home.
They settled immediately into the monotonous and still order of their
future life. Martha’s room, where there were few things to suggest
painful remembrances, they made a little work-room; and here
Agnes and Rose sat by the window at their work, and Lettie and her
little companion learned their lessons, and laboured with varying
industry—now enthusiastic—now slack and languid, at the
“opening,” in which they were soon skilled. And Martha, returning
wearied from business out of doors, or in the library, came up here to
take off her outer wrappings, and begin to the other labour which
called for her. And Lettie on the carpet, and Katie on her little stool,
kept up a running conversation, which sometimes gave a passing
moment of amusement to the sadder elder hearts; and little Harry
played joyously, beguiling his sad young mother into momentary
smiles; and the baby began to totter on his little feet, and make
daring journeys from the arms of Martha into his mother’s; and
gradually there grew to be a certain pensive pleasure in their
evening walk, and they roused themselves to open the window,
when the little Leith steamer shot past under the trees; and every
day filled itself with its own world of duty, and passed on—slowly, it is
true—but less drearily than at the first.
No one grudged now, nor mixed ill-feeling in the emulation with
which neighbouring agriculturists watched the fields of Allenders.
Something of fear and solemn awe startled the very labourers in
these fields when Martha passed them, assiduous and diligent in all
the work she set herself to do. They were not afraid of her—she did
not impress them with more than the respect which they gave
willingly as her right; but there was something solemn in a
representative of the dead—a person living, as it seemed, but to
carry out the thoughts and wishes of another who had passed away.
The stir and thrill of renewed and increased industry came again
upon Maidlin Cross. It was true they had no model cottages yet, but
the land lay marked out on the other side of the cross, where Harry’s
new houses were to be; and Armstrong thought Miss Allenders had
answered him almost fiercely, when he proposed to plough this land,
and enclose it in a neighbouring field. No—it was Harry’s will those
houses should be built, and built they must be, when justice and right
permitted; and it soon came to be known in Maidlin, where Harry in
his careless good-humour had promised anything without bestowing
it, that it needed but a hint of this to Martha to secure the favour. And
the works went on steadily and prosperously, and with a wise
boldness Martha drew upon Mr. Buchanan’s thousand pounds.
Armstrong, no longer driven to the sad alternative of doing nothing,
or acting on his own responsibility, became emboldened, and was no
longer afraid to be now and then responsible; and Allender Mains
became a great farm-steading, and began to send off droves to
Stirling market, and Falkirk tryste, and was managed as the cautious
Armstrong never could have managed it, had all this gainful risk and
expenditure been incurred for himself.
And on the Sabbath days when they leave the church—Agnes in
her widow’s weeds leaning on Martha’s arm, and Rose leading the
children—they turn aside to a little space railed off from the wall,
where moulders the mossed gravestone of the old Laird of Allenders,
and where the gowans and forget-me-nots grow sweetly under the
spring sunshine upon Harry’s breast. His name is on a tablet of white
marble on the wall—his name and age—nothing more. They go
there silently—almost as it seems involuntarily—towards their grave,
and stand in silence by the railing, visiting the dead, but saying
nothing to each other; and after a little while, as silently as they
came, the family go away. Nor do they ever allude to this visit,
though the custom is never broken through—it is something sacred,
a family solemnity, a thing to be done in silence.
And the ladies of Nettlehaugh and Foggo do not disdain now to call
on Mrs. and Miss Allenders, nor even Miss Dunlop, though she
stands upon her dignity, and has heard a secret whisper that these
hands she condescends to shake, work at her collars and
handkerchiefs, and earn bread by their labour. But at the end of the
dining-room beside Cuthbert’s window, some preparations were
begun long ago for the erection of that conservatory which Miss
Dunlop recommended to Harry—and to her mother’s consternation,
Miss Dunlop makes cool inquiries about it, and presumes they do not
intend to carry it out now. Martha answers with a blank gravity which
she has learned to assume, to cover the pang with which she
mentions his name, that other more important wishes of Harry’s have
to be carried out before she can come to this; but that what he
intended shall be done without fail, and that it only waits a suitable
time. “They say that Heaven loves those that die young,” says
Martha, with a grave simplicity, “yet the dead who die in their youth
leave many a hope and project unfulfilled—and few have been so full
of projects, and had so little time to work them out.”
This is all—but Miss Dunlop, bewildered and conscience-stricken,
dares scarcely speak again of the fickle weakness of poor Allenders,
and all his vain, magnificent aspirations, and efforts to be great. She
has a vague impression that she has blundered in her hasty estimate
of poor Harry, and that it was indeed because his sun went down at
noon that none of his great intentions ripened into success—for no
one ventures to prophesy failure to Harry’s purposes now.
And Cuthbert comes when he can spare a day—comes to bring
them news of the far-away world whose vexed and troubled
murmurs they never hear, and to receive with affectionate sympathy,
all they tell him of their own plans and exertions. Cuthbert is admitted
to the work-room, and takes out Agnes and Rose to their nightly
walk, upon which Martha, who, herself actively employed, has no
need of this, insists; and Agnes leans upon him as on a good and
gentle brother; and there comes a strange ease and repose to
Rose’s heart as she walks shyly by his side in the twilight, saying
little, but preserving with a singular tenacity of recollection everything
the others say. And Rose, waking sometimes now to her old
personal grief—a thing which seems dead, distant and selfish, under
the shadow of this present sorrow—recollects that Martha’s “capital”
is from Mr. Buchanan—that Cuthbert is his favourite nephew, and
that there may be truth yet in the story which fell like a stone upon
her heart. But Rose only speculates unawares upon these individual
anxieties—they seem to her guilty, and she is ashamed to harbour
them—yet still unconsciously she looks for Cuthbert’s coming, and
when he comes grows abstracted and silent, and looks like a shy,
incompetent girl, instead of the fair, sweet-hearted woman into
whose fuller form and maturity her youth developes day by day. Yet
Cuthbert’s eyes are witched and charmed, and he has strangely
correct understanding of every shy, half-broken word she says; and
Rose would start, and wonder, and scarcely believe, in her timid
unconscious humility, could she see how these broken words remain
in Cuthbert’s heart.
CHAPTER XXI.

I am a very foolish, fond old man,


Fourscore and upward

king lear.
“I was born this day fourscore and five years ago,” said Dragon.
“It’s a great age, bairns, and what few folk live to see; and for every
appearance that’s visible to me, I may live ither ten, Missie, and
never ane be a prin the waur. I would like grand mysel to make out
the hunder years, and it would be a credit to the place, and to a’
belonging till’t; and naebody wishes ill to me nor envies me for my
lang life. Just you look at that arm, Missie; it’s a strong arm for a man
o’ eighty-five.”
And Dragon stretched out his long thin arm, and snapt the curved
brown fingers—poor old Dragon! Not a child in Maidlin Cross but
could have overcome the decayed power which once had knit those
loose joints, and made them a strong man’s arm; but Dragon waved
it in the air exultingly, and was proud of his age and strength, and
repeated again with earnestness: “But I would like grand to make out
the hunder year.”
Lettie, now a tall girl of fifteen, stood by Dragon’s stair, arranging
flowers, a great number of which lay before her on one of the steps.
They were all wild flowers, of faint soft colour and sweet odours, and
Lettie was blending hawthorn and primroses, violets and cowslips,
with green sprigs of the sweetbriar, and here and there an early half-
opened wild rose—blending them with the greatest care and
devotion; while Katie Calder, developed into a stout little comely
woman-like figure, stood by, looking on with half contempt; for Katie
already had made a superb bouquet of garden flowers, and was
carrying it reverentially in her apron.
“It’s five years this day since Mr. Hairy came first to Allenders”,
continued the old man, “and it’s mair than three since they laid him in
his grave. The like o’ him—a young lad! and just to look at the like o’
me!”
“But it was God’s pleasure, Dragon,” said Lettie, pausing in her
occupation, while the shadow which stole over her face bore witness
that Harry’s memory had not passed away even from her girl’s heart.
“Ay, Missie,” said the old man vacantly; “do ye think the spirit gaed
willingly away? I’ve thought upon that mony a time when I was able
to daunder up bye to the road, and see the farm; and it’s my belief
that Mr. Hairy will never get right rest till a’s done of the guid he
wanted to do, and a’s undone o’ the ill he did—that’s my belief. I
think myself he canna get lying quiet in his grave for minding of the
work he left to do; and if there was ane here skilled to discern spirits,
he might be kent in the fields. What makes the lady sae constant at
it, think ye, night and morning, putting to her ain hand to make the
issue speedier, if it’s no that she kens about him that’s aye waiting,
waiting, and never can enter into his rest.”
Lettie let her flowers fall, and looked away with a mysterious glance
into the dark shade of the trees; for the vague awe of poetic
superstition was strong upon Lettie still.
“Dragon,” she said in a very low voice, “I used to think I heard Harry
speak, crying on me, and his footstep in his own room, and on the
stair; and all the rest thought that too, for I have seen them start and
listen many a time, thinking it was Harry. Do ye think it could be true?
Do ye think, Dragon, it could be Harry? for I came to think it was just
because he was aye in our mind that we fancied every sound was
him.”
“Ane can never answer for the dead,” said the poor old Dragon.
“Ane kens when a living person speaks, for ye can aye pit out your
hand and touch them, and see that they’re by your side; but I pit out
my hand here, Missie—it’s a’ clear air to me—but for aught I ken, an
angel in white raiment may be standing on my stair-head, and
anither within my door, laying a mark in the Book yonder that I may
open it the night at ae special verse, and read that and nae ither.
How is the like o’ me to ken? And you’ll no tell me that Mr. Hairy
winna stand by the bride the morn, and be the first voice to wish her
joy, though we may ne’er hear what he says.”
With a slight tremble, Violet, putting away her flowers, leaned upon
the step, and looked again into the darkening shadow of the trees;
and Lettie tried to think, and to pray in her simplicity that her eyes
might be opened to discern the spirits, and that she might see Harry,
if he were here. But again the mortal shrank from the visible
immortality, and Lettie covered her eyes with a thrill of visionary fear.
“Dragon, look at Lettie’s flowers,” said Katie Calder; “she wants to
put them on the table, where the minister’s to stand, instead of all
the grand ones out of Lady Dunlop’s; and I never saw such grand
flowers as Lady Dunlop’s, Dragon.”
“The dew never falls on them,” said Lettie, starting to return to her
occupation; “and if you were in the room in the dark, you would
never know they were there; but I gathered this by the Lady’s Well,
and this was growing at the foot of the stone where Lady Violet sat,
and the brier and the hawthorn out of that grand hedge, Dragon,
where a’ the flowers are; and if I put them on the table in the dark,
the wee fairy that Dragon kens, will tell the whole house they’re
there; but Lady Dunlop’s have no breath—and mine are far liker
Rose.”
As Lettie speaks, some one puts a hand over her shoulder, and
lifting her flowers, raises them up very close to a glowing radiant
face; and Dragon, hastily getting up from the easy-chair on his stair-
head, jerks his dangling right arm upward towards the brim of the low
rusty old hat, which he wears always. It is only persons of great
distinction whom Dragon so far honours, and Dragon has forgotten
“yon birkie,” in his excited glee about the approaching wedding, and
his respect for the “groom.”
“Very right, Lettie,” said the bridegroom, with a little laugh which has
a tremble in it; “they are far liker Rose. And will you be able to come
to the gate to-morrow, Dragon, and see me carry the flower of
Allenders away?”
“But ye see, my man,” said Dragon, eagerly, shuffling about his little
platform, as he looked down on Cuthbert, “I never had her about me
or among my hands, when she was a little bairn; and if it was either
Missie there, or the ither ane, I would have a greater miss; for I’ve
gotten into a way o’ telling them stories, and gieing a word of advice
to the bit things, and training them the way they should go; so they’re
turned just like bairns o’ my ain. But I wish Miss Rose and you
muckle joy, and increase and prosperity, and that ye may learn godly
behaviour, and be douce heads of a family; and that’s the warst wish
that’s in my head, though you are taking ane of the family away, and
I never was married mysel.”
And Cuthbert, responding with another joyous laugh, shook hands
with Dragon, after a manner somewhat exhausting to the loose arm,
of whose strength the old man had boasted, and immediately went
away to the waterside, to take a meditative walk along its banks, and
smile at himself for his own exuberant boyish joy. Serious and
solemn had been many of the past occasions on which he had
visited Allenders; and now, as the fulfilment of all his old anticipations
approached so certainly, so close at hand, Cuthbert’s moved heart
turned to Harry—poor Harry! whose very name had a charm in it of
mournful devotion and love!
The sun shone in next morning gaily to the rooms of Allenders, now
suddenly awakened as out of a three years’ sleep; and Agnes curls
her bright hair, and lets the sunshine glow upon it as she winds it
round her fingers, and with a sigh, lays away the widow’s cap, which
would not be suitable, she thinks, on Rose’s wedding-day; but the
sigh is a long-drawn breath of relief—and with an innocent
satisfaction, Agnes, blooming and youthful still, sees her pretty curls
fall again upon her cheek, and puts on her new white gown. It is a
pleasant sensation, and her heart rises unawares, though this other
sigh parts her lips. Poor Harry! his little wife will think of him to-day!
Think and weep, but only with a serene and gentle melancholy; for
the young joyous nature has long been rising; and Agnes, though
she never can forget, laments no longer with the reality of present
grief. It is no longer present—it is past, and only exists in
remembrance; and Agnes is involuntarily glad, and will wear her
widow’s cap no more.
And Martha is dressing little Harry, who will not be quiet in her
hands for two minutes at a time, but dances about with a perpetual
elasticity, which much retards his toilet. There are smiles on Martha’s
face—grave, quiet smiles—for she too has been thinking, with a few
tears this morning, that Harry will be at the bride’s side, to join in the
blessing with which she sends her other child away.
And Rose, in her own chamber, in a misty and bewildered
confusion, seeing nothing distinctly either before or behind her, turns
back at last to that one solemn fact, which never changes, and
remembers Harry—remembers Harry, and weeps, out of a free heart
which carries no burden into the unknown future, some sweet
pensive tears for him and for the home she is to leave to-day; and so
sits down in her bewilderment to wait for Martha’s summons, calling
her to meet the great hour whose shadow lies between her and the
skies.
And Lettie’s flowers are on the table, breathing sweet, hopeful
odours over the bridegroom and the bride. And Lettie, absorbed and
silent, listens with a beating heart for some sign that Harry is here,
and starts with a thrill of recognition when her heart imagines a
passing sigh. Poor Harry! if he is not permitted to stand unseen
among them, and witness this solemnity, he is present in their
hearts.
CHAPTER XXII.

Behold I see the haven now at hand


To which I mean my wearie course to bend.
Vere the maine shete, and beare up with the land,
The which afar is fairly to be kend,
And seemeth safe from storms that may offend.

faery queen.
Agnes, with her relieved and lightened spirits, goes cheerfully
about her domestic business now, and has learned to drive the little
old gig, and sometimes ventures as far as Stirling to make a
purchase, and begins to grow a little less afraid of spending money.
For some time now, Agnes has given up the “opening”—given it up
at Martha’s special desire, and with very little reluctance, and no one
does “opening” now at Allenders, except sometimes Martha herself,
in her own room, when she is alone. These three years have paid
Miss Jean’s thousand pounds, and one of Macalister’s four, and Mr.
Macalister is very happy to leave the rest with Miss Allenders, who,
when her fourth harvest comes, has promised to herself to pay Mr.
Buchanan. For assiduous work, and Martha’s almost stern economy,
have done wonders in these years; and the bold Armstrong boasts of
his crops, and his cattle now, and is sometimes almost inclined to
weep with Alexander, that there is no more unfruitful land to
subjugate and reclaim.
But before her fourth harvest time, Martha has intimated to Sir John
Dunlop’s factor that it was her brother’s intention to make an offer for
the little farm of Oatlands, now again tenantless, and Armstrong
does not long weep over his fully attained success; though Oatlands
has little reformation to do, compared with Allender Mains. And
Harry’s model houses are rising at Maidlin Cross; sagacious people
shake their heads, and say Miss Allenders is going too far, and is not
prudent. She is not prudent, it is very true—she ventures to the very
edge and utmost extent of lawful limits—but she has never ventured
beyond that yet, nor ever failed.
And Harry’s name and remembrance lives—strangely exists and
acts in the country in which Harry himself was little more than a
subject for gossip. To hear him spoken of now, you would rather
think of some mysterious unseen person, carrying on a great work
by means of agents, that his chosen privacy and retirement may be
kept sacred, than of one dead to all the business and labour of this
world; and there is a certain mystery and awe about the very house
where Harry’s intentions reign supreme, to be considered before
everything else. So strong is this feeling, that sometimes an ignorant
mind conceives the idea that he lives there yet in perpetual secrecy,
and by and bye will re-appear to reap the fruit of all these labours;
and Geordie Paxton shakes his head solemnly, and tells his
neighbours what the “auld man” says—that Allenders cannot rest in
his grave till this work he began is accomplished; and people speak
of Harry as an active, existing spirit—never as the dead.
It is more than a year now since Rose’s marriage, and not far from
five since Harry’s death, and there is a full family circle round the
drawing-room fireside, where Mrs. Charteris has been administering
a lively little sermon to Lettie about the extravagance of destroying
certain strips of French cambric; (“It would have cost five-and-twenty
shillings a yard in my young days,” says the old lady), with which
Lettie has been devising some piece of ornamental work for the
adornment of Agnes. But Lettie’s execution never comes up to her
ideal, and the cambric is destroyed for ever; though Katie Calder,
looking on, has made one or two suggestions which might have
saved it.
“For you see, my dear, this is waste,” said Mrs. Charteris; “and ye
should have tried it on paper first, before you touched the cambric.”
“So I did,” said Lettie, nervously; “but it went all wrong.”
And Rose smiles at the childish answer; and Mrs. Charteris bids
Violet sit erect, and keep up her head. Agnes is preparing tea at the
table. Martha, with little Sandy kneeling on the rug before her,
playing with a box of toys which he places in her lap, sits quietly
without her work, in honour of the family party; and Uncle Sandy is
telling Katie Calder all kinds of news about her companions in Ayr.
Why is Lettie nervous? Cuthbert at the table is looking over a new
magazine, which has just been brought in from Stirling with a supply
of other books ordered by their good brother; and constant longing
glances to this magazine have had some share in the destruction of
Lettie’s cambric. But Lettie is sixteen now, and Agnes thinks she
should not be such a child.
“Here is something for you,” says Cuthbert, suddenly. “Listen, we
have got a poet among us. I will read you the ballad of the ‘Lady’s
Well.’”

“She sat in her window like a dream,


She moved not eye nor hand;
Her heart was blind to the white moonbeam,
And she saw not the early morning gleam
Over the dewy land;
Nor wist she of aught but a tale of wrong,
That rang in her ears the dim day long.

Her hair was like gold upon her head,


But the snow has fallen there;
And the blush of life from her face has fled,
And her heart is dumb, and tranced, and dead,
Yet wanders everywhere—
Like a ghost through the restless night,
Wanders on in its own despight.

But hither there comes a long-drawn sigh—


A thrill to her form, a light to her eye:
Only a sigh on the wind, I wiss;
Keep us and guard us from sounds like this!
For she knew in the breath, for a mystic token,
The words of the rede, by that graybeard spoken.
The bridal robes are glistening fair
In the gray eventide,
Her veil upon her golden hair,
And so goes forth the bride—
Who went before to guide astray
All wayfarers from this way;
Whose the voice that led her hence,
How that graybeard came, and whence;
Known were these to her alone,
And she told the tale to none.

The fountain springs out of the earth,


Nor tells what there it sees;
And the wind with a cry, ’twixt grief and mirth,
Alights among the trees.
She sat her down upon the stone,
Her white robes trailed o’er the cold green turf,
Her foot pressed on the dreary earth,
Alone, alone, alone.
Not an ear to hear, not a voice to tell,
How the lady passed from the Lady’s Well.

The lady sat by the Lady’s Well.


When the night fell dark and gray;
But the morning sun shone in the dell,
And she had passed away.
And no man knew on the coming morrow
Aught but the tale of an unknown sorrow;
And nought but the fountain’s silver sound,
And the green leaves closing in around,
And a great silence night and day,
Mourned for her vanishing away.

But peace to thee, Ladie, lost and gone!


And calm be thy mystic rest.
Whether thou dwellest here unknown,
Or liest with many a kindred one,
In the great mother’s breast;
The woe of thy curse has come and fled,
Peace and sweet honour to our dead!”

But Lettie, growing red and pale, dropping the paper pattern which
Mrs. Charteris has cut for her, and casting sidelong, furtive glances
round upon them all from under her drooped eyelids, trembles
nervously, and can scarcely keep her seat. When Cuthbert comes to
the end there is a momentary silence, and Martha looks with wonder
on her little sister, and Agnes exclaims in praise of the ballad, and
wonders who can possibly know the story so well. Then follows a
very free discussion on the subject, and some criticism from
Cuthbert; and then Martha suddenly asks: “It is your story, Lettie,
and you don’t often show so little interest. How do you like it? Tell
us.”
“I—I canna tell,” said Lettie, letting all her bits of cambric fall, and
drooping her face, and returning unconsciously to her childish
tongue; “for—it was me that wrote it, Martha.”
And Lettie slid down off her chair to the carpet, and concealed the
coming tears, and the agitated troubled pleasure, which did not quite
realize yet whether this was pain or joy, on Martha’s knee.
Poor Lettie! many an hour has she dreamed by the Lady’s Well—
dreamed out grand histories for “us all,” or grander still

“——Resolved
To frame she knows not what excelling thing
And win she knows not what sublime reward
Of praise and honour——”

But just now the sudden exultation bewilders Lettie; and there is
nothing she is so much inclined to do as to run away to her room in
the dark, and cry. It would be a great relief.
But the confession falls like lightning upon all the rest. Cuthbert,
with a burning face, thinks his own criticism the most stupid in the
world. Rose laughs aloud, with a pleasure which finds no other
expression so suitable. Agnes, quite startled and astonished, can do
nothing but look at the bowed head, which just now she too had
reproved for stooping. And Mrs. Charteris holds up her hands in
astonishment, and Katie claps hers, and says that she kent all the
time. But Martha, with a great flush upon her face, holds Lettie’s wet
cheeks in her hands, and bends down over her, but never says a
word. Children’s unpremeditated acts, simple words and things have
startled Martha more than once of late, as if a deeper insight had
come to her; and now there is a great motion in the heart which has
passed through tempests innumerable, and Martha cannot speak for
the thick-coming thoughts which crowd upon her mind.
That night, standing on the turret, Martha looks out upon the lands
of Allenders—the lands which her own labour has cleared of every
overpowering burden, and which the same vigorous and unwearied
faculties shall clear yet of every encumbrance, if it please God. The
moonlight glimmers over the slumbering village of Maidlin—over the
pretty houses of poor Harry’s impatient fancy, where Harry’s
labourers now dwell peacefully, and know that their improved
condition was the will and purpose of the kindly-remembered dead.
And the little spire of Maidlin Church shoots up into the sky, guarding
the rest of him, whose memory no man dares malign—whose name
has come to honour and sweet fame, since it shone upon that tablet
in the wall—and not one wish or passing project of whose mind,
which ever gained expression in words, remains without fulfilment, or
without endeavour and settled purpose to fulfil. And Martha’s
thoughts turn back—back to her own ambitious youth and its bitter
disappointment—back to the beautiful dawn of Harry’s life—to its
blight, and to its end. And this grand resurrection of her buried hopes
brings tears to Martha’s eyes, and humility to her full and swelling
heart. God, whose good pleasure it once was to put the bar of utter
powerlessness upon her ambition, has at last given her to look upon
the work of her hands—God, who did not hear, according to her
dimmed apprehension, those terrible prayers for Harry which once
wrung her very heart, gave her to see him pass away with peace and
hope at the end, and has permitted her—her, so greedy of good
fame and honour—to clear and redress his sullied name. And now
has been bestowed on Martha this child—this child, before whom
lies a gentle glory, sweet to win—a gracious, womanly, beautiful
triumph, almost worthy of an angel—and the angels know the dumb,
unspeakable humility of thanksgiving which swells in Martha’s heart.
So to all despairs, agonies, bitternesses, of the strong heart which
once stormed through them all, but which God has chastened,
exercised, at length blessed, comes this end. Harvest and seedtime
in one combination—hopes realized, and hopes to come; and all her
children under this quiet roof, sleeping the sleep of calm, untroubled
rest—all giving thanks evening and morning for fair days sent to
them out of the heavens, and sorrow charmed into sweet repose,
and danger kept away. But though Martha’s eyes are blind with
tears, and her heart calls upon Harry—Harry, safe in the strong hand
of the Father, where temptation and sorrow can reach him never
more—the same heart rises up in the great strength of joy and faith,
and blesses God: Who knoweth the beginning from the end—who
maketh His highway through the flood and the flame—His highway
still, terrible though it be—who conducts into the pleasant places,
and refreshes the failing heart with hope; and the sleep which He
gives to His beloved, fell sweet and deep that night upon the wearied
heart of Martha Muir.
the end.

LONDON:
Printed by Schulze and Co., 13, Poland Street.

Corrections

The first line indicates the original, the second the correction.
p. 90

to her ttle sister


to her little sister

p. 115

that is my concern—your’s is
that is my concern—yours is

p. 239

the pain of them mingled wlth


the pain of them mingled with

p. 275

ROMEO AND JULIE T.


ROMEO AND JULIET.

p. 287

since Mr. Hairy ame first


since Mr. Hairy came first

Erratum

In chapter numbering, Chapter III is missing.


*** END OF THE PROJECT GUTENBERG EBOOK HARRY MUIR
***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright
in these works, so the Foundation (and you!) can copy and
distribute it in the United States without permission and without
paying copyright royalties. Special rules, set forth in the General
Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE

You might also like