0% found this document useful (0 votes)
335 views59 pages

Wrox Pro 2012

Test

Uploaded by

AzjolNerub
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
335 views59 pages

Wrox Pro 2012

Test

Uploaded by

AzjolNerub
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Feature Styles

Feature

Feature Type

Other Instructions

Page Number

Sidebar

type = general

Title must be provided

1011

Warning

type = warning

No title

1000

Note

type = note

No title

1008

Code Lengths for Wrox Professional


CodeSnippet (83 characters)
12345678901234567890123456789012345678901234567890123456789012345678901234567890123

CodeSnippetSub (77 characters)


12345678901234567890123456789012345678901234567890123456789012345678901234567

CodeListing (83 characters)


12345678901234567890123456789012345678901234567890123456789012345678901234567890123

Code80 (88 characters)


1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678

Code80Sub (82 characters)


1234567890123456789012345678901234567890123456789012345678901234567890123456789012

CodeListing80 (88 characters)


1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678

The bubblesheet does not


show content from an actual
chapter and should only
be used for formatting. For
specific content information
please refer to the series
guideline documentation.

PRODUCTION NOTE: DO NOT WRAP CODE AROUND FIGURES

WroxPro.030912.indd 1

3/14/12 12:25 PM

Feature
Test classes will be named as follows [class name]Tests, for example if we are testing the PayController class then the test fi xture will be named PayControllerTests.
FeatureCoDeSniPPet (68 CHaraCterS)
12345678901234567890123456789012345678901234567890123456789012345678

FeatureCoDeSniPPetSub (62 CHaraCterS)


12345678901234567890123456789012345678901234567890123456789012

FeatureCoDe80 (72 CHaraCterS)


123456789012345678901234567890123456789012345678901234567890123456789012

FeatureCoDe80Sub (66 CHaraCterS)


123456789012345678901234567890123456789012345678901234567890123456

nOte/WarnIng (66 characters)

FeatureCodeSnippet
123456789012345678901234567890123456789012345678901234567890123456

nOte/WarnIng (70 characters)

FeatureCode80
1234567890123456789012345678901234567890123456789012345678901234567890

nOte/WarnIng (60 characters)

FeatureCodeSnippetSub
123456789012345678901234567890123456789012345678901234567890

nOte/WarnIng (64 characters)

FeatureCode80Sub
1234567890123456789012345678901234567890123456789012345678901234

WroxPro.030912.indd 2

3/14/12 12:25 PM

Professional
ASP.NET MVC Test Driven Development
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
Chapter 1

Requirements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Chapter 2

High-Level Design. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

Chapter 3

Membership . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

Chapter 4

Refactor: Model Binders, Mocks, and Asserts . . . . . . . . . . . . . . . . . . . . . 65

Chapter 5

Client and Server Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

Chapter 6

Data Layer and IRepository Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

Chapter 7

 eclare Your Independence with Dependency Injection


D
and IRepository Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103

Chapter 8

Contact Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

Chapter 9

Import Contacts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

Chapter 10 Composing Messages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167


Chapter 11

HTML WYSIWYG Editing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187

Chapter 12

Image Hosting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195

Chapter 13

Message Templating. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211

Chapter 14

Billing and Subscriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225

Chapter 15

Usage Tracking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237

Chapter 16

Fill In the Blanks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

Chapter 17

Client and Server Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

Chapter 18

Data Layer and IRepository Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

Chapter 19

 eclare Your Independence with Dependency Injection


D
and IRepository Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103

Chapter 20 Contact Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109


Chapter 21

Import Contacts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

Chapter 22 Composing Messages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167


Chapter 23 HTML WYSIWYG Editing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187

Continues

WroxPro.030912.indd 3

3/14/12 12:25 PM

Chapter 24 Image Hosting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195


Chapter 25 Message Templating. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Chapter 26 Billing and Subscriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Chapter 27 Usage Tracking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Chapter 28 Fill In the Blanks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
Appendix A Useful Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
Appendix B Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263

WroxPro.030912.indd 4

3/14/12 12:25 PM

Professional
ASP.NET MVC Test Driven Development
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix

Part I Part Opener Title


Chapter 1

Requirements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Chapter 2

High-Level Design. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

Chapter 3

Membership . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

Chapter 4

Refactor: Model Binders, Mocks, and Asserts . . . . . . . . . . . . . . . . . . . . . 65

Chapter 5

Client and Server Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

Part II The Second Part Opener Title


Chapter 6

Data Layer and IRepository Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

Chapter 7

Declare Your Independence with Dependency Injection. . . . . . . . . . . 103

Chapter 8

Contact Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

Chapter 9

Import Contacts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

Chapter 10 Composing Messages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167


Chapter 11

HTML WYSIWYG Editing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187

Part III AnD a Third Part Opener Title


Chapter 12

Image Hosting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195

Chapter 13

Message Templating. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211

Chapter 14

Billing and Subscriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225

Chapter 15

Usage Tracking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237

Chapter 16

Fill In the Blanks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

Appendix A Useful Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253


Appendix B Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263

WroxPro.030912.indd 5

3/14/12 12:25 PM

WroxPro.030912.indd 6

3/14/12 12:25 PM

MatterTitle

Praise for

Professional ASP.NET MVC Test Driven Development


A must read for anyone wanting to learn how Excel Services revolutionizes the world of
spreadsheets!
Para

Para

Richard McAniff
Corporate Vice President,
Microsoft Office

This book will guide you through everything you need to know about the great new functionality in Excel Services. Microsoft Office SharePoint Server 2007 is Microsofts platform for business
applications. Excel Services provides great new business intelligence functionality and helps users
control and manage their spreadsheets. Were already seeing these tools and services unleashing tremendous creativity in the developer community.

Kurt DelBene
Corporate Vice President,
Office Business Platform Group
Microsoft Excels sophisticated calculation and analysis capabilities, combined with ease of use
and programmability, have led to wide deployment in Capital Markets for critical applications such
as pricing and risk management. To date, management and auditing, of what can be highly complex
linked workbooks, have posed challenges.
Excel Services, part of Microsoft Office SharePoint Server 2007, now provides a powerful
solution for management of mission-critical spreadsheet applications by centralizing workbook content and calculations and providing controlled web browser access to Excel applications and data on
a client/server basis.
We at HCL technologies see huge take-up of Excel Services in Capital Markets and are making significant investments in developing deployment capabilities. If you want to learn more about
Excel Services, you must get this book.
Para

Peter Bennett
Principal, Capital Markets,
HCL Former CIO of London Stock Exchange

Excel Services is a critical enhancement to the analysis tool that the world knows and loves. This is
the definitive book on Excel Services, from the team that dreamed it up and built it.

Bill Baker
Distinguished Engineer,
General Manager Business Intelligence,
Microsoft Corporation

WroxPro.030912.indd 7

3/14/12 12:25 PM

WroxPro.030912.indd 8

3/14/12 12:25 PM

BookHalfTitle

Professional

ASP.NET MVC Test Driven Development

WroxPro.030912.indd 9

3/14/12 12:25 PM

WroxPro.030912.indd 10

3/14/12 12:25 PM

BookTitle

Professional

ASP.NET MVC Test Driven Development


Problem Design Solution
BookEdition

BookSubtitle

Fifth Edition
If there is an Edition number, no
subtitle, then edition number is
styled as BookSubtitle

BookAuthor

WroxPro.030912.indd 11

Emad Ibrahim

3/14/12 12:25 PM

Professional ASP.NET MVC Test Driven Development: Third Edition


Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256

www.wiley.com

InlineURL

Copyright 2009 by Wiley Publishing, Inc., Indianapolis, Indiana


Published simultaneously in Canada
ISBN: 978-0-470-44762-8
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of
the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through
payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978)
750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department,
John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at
http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with
respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including
without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold
with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services.
If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to
in this work as a citation and/or a potential source of further information does not mean that the author or the publisher
endorses the information the organization or Web site may provide or recommendations it may make. Further, readers
should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was
written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the
United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available
in electronic books.
Library of Congress Control Number: 2009931752
Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its
affiliates, in the United States and other countries, and may not be used without written permission. All other trademarks
are the property of their respective owners. Wiley Publishing, Inc. is not associated with any product or vendor mentioned
in this book.

Copyright

WroxPro.030912.indd 12

3/14/12 12:25 PM

Dedication

This book is dedicated to my beautiful soon-to-bewife, Laura, for her unconditional love and support. I
love you. Te amo mucho.
Ana Bahebyk

WroxPro.030912.indd 13

3/14/12 12:25 PM

WroxPro.030912.indd 14

3/14/12 12:25 PM

About the AuthorSingle author

About the Author

MatterTitle

Para

Emad Ibrahim is a programmer, an entrepreneur, a thinker, a dreamer, and a

humanist. He is all that and none of that. He is clearly conflicted.


He graduated from Virginia Tech in 2009 without honors and since worked
in small and large companies, in small and large teams. He has worked in
coffee shops, libraries, skyscrapers, and basements. He has managed teams
across the room, across the country, and across the world.
He was born in Egypt, graduated kindergarten and met Santa Claus for the
first time in Jordan, graduated high school in Zambia, and graduated college in the Virginia, USA.
He has lived in Virginia for more than 14 years and now claims it as his home and final destination.
Emad programs in VB, C#, Objective-C, and Ruby. He programs for Windows, the Web, mobile,
and iPhone. Legend has it that after a few beers he once said, I wish I had my computer. I feel like
coding.

Para

If there are no blanks and both pages are side-by-side, then


Credits should be on left and About the Authors on right

WroxPro.030912.indd 15

3/14/12 12:25 PM

WroxPro.030912.indd 16

3/14/12 12:25 PM

About the AuthorMultiple authors

About the Authors

MatterTitle

Para

Emad Ibrahim is a programmer, an entrepreneur, a thinker, a dreamer, and a humanist. He is all

that and none of that. He is clearly conflicted.He graduated from Virginia Tech in 2009 without
honors and since worked in small and large companies, in small and large teams. He has worked in
coffee shops, libraries, skyscrapers, and basements. He has managed teams across the room, across
the country, and across the world.
Emad Ibrahim is a programmer, an entrepreneur, a thinker, a dreamer, and a human-

ist. He is all that and none of that. He is clearly conflicted.He graduated from Virginia
Tech in 2009 without honors and since worked in small and large companies, in small
and large teams. He has worked in coffee shops, libraries, skyscrapers, and basements.
He has managed teams across the room, across the country, and across the world. He
has managed teams across the room, across the country, destination and across the world.
He was born in Egypt, graduated kindergarten and met Santa Claus for the first time in Jordan, graduated high school in Zambia, and graduated college in the Virginia, USA. He has lived in Virginia for
more than 14 years and now claims it as his home and final destination.
Emad Ibrahim is a programmer, an entrepreneur, a thinker, a dreamer, and a human-

ist. He is all that and none of that. He is clearly conflicted. He graduated from Virginia
Tech in 2009 without honors and since worked in small and large companies, in small
and large teams. He has worked in coffee shops, libraries, skyscrapers, and basements.
He has managed teams across the room, across the country, and across the world. He
was born in Egypt, graduated kindergarten and met Santa Claus for the first time in Jordan, graduated high school in Zambia, and graduated college in the Virginia, USA. He has lived in Virginia for
more than 14 years and now claims it as his home and final destination.
Emad Ibrahim is a programmer, an entrepreneur, a thinker, a dreamer, and a humanist.

He is all that and none of that. He is clearly conflicted.


He graduated from Virginia Tech in 2009 without honors and since worked in small
and large companies, in small and large teams. He has worked in coffee shops, libraries, skyscrapers, and basements. He has managed teams across the room, across the country, and
across the world. He was born in Egypt, graduated kindergarten and met Santa Claus for the first
time in Jordan, graduated high school in Zambia, and graduated college in the Virginia, USA.

WroxPro.030912.indd 17

3/14/12 12:25 PM

WroxPro.030912.indd 18

3/14/12 12:25 PM

Credits

MatterTitle

Acquisitions Editor

Vice President and


ExecutiveGroupPublisher

Paul Reese

Richard Swadley
Project Editor

Adaobi Obi Tulton

Vice President and Executive Publisher

Barry Pruett
Technical Editor

Cody Reichenau

Associate Publisher

Jim Minatel
Production Editor

Debra Banninger

Project Coordinator, Cover

Lynsey Stanford
Copy Editor

Catherine Caffrey

Compositor

Jeff Lytle, Happenstance Type-O-Rama


Editorial Director

Robyn B. Siesky

Proofreader

Jen Larson, Word One


Editorial Manager

Mary Beth Wakefield


Production Manager

Style as Credits,
Comp will apply
additional styles

Indexer

J & J Indexing

Tim Tate

WroxPro.030912.indd 19

3/14/12 12:25 PM

WroxPro.030912.indd 20

3/14/12 12:25 PM

Acknowledgments

MatterTitle

Para

Many people contributed directly and indirectly to this effort. I am grateful for their thoughtful

insights. I thank Adaobi Obi Tulton and Jim Minatel for their incredible patience, understanding,
and support throughout the writing process. They have made the writing process so much easier.
By the time this book is published, I will be married to Lauramy fiance of two years and the love of
my life. I am looking forward to spending the rest of my life with you. Thank you for your love, support, encouragement, and your belief in me.
I want to acknowledge my dad for teaching me to dream big, encouraging and supporting me in
everything I do. When I was a kid, I used to tell people I wanted to win the Nobel Peace Prize when
I grew up. Needless to say, everyone thought it was funny except my parents, and specifically except
for my dad. No dream was ever too big for him. Of course, I have not won the Nobel Peace Prize,
but the fact that I am writing this acknowledgement means that one of my dreams did come true to
write a book.
Last but not least, I want to acknowledge my little sister, Caroline. Thank you for being there when
I need you. You are a great sister and friend. I cant believe you will be a doctor in a few months. Dont
expect me to address you as Doctor, though.
ChapterCredit

Ana Bahebyk

I want to acknowledge the best mom in the world. She is the best listener, the most compassionate

and loving mother. Thanks for unconditionally listening to all that I have to say even when none of
it made sense. She is also a fantastic cook. One day we will create a cookbook together.I also want
to acknowledge the best mom in the world. She is the best listener, the most compassionate and loving mother. Thanks for unconditionally listening to all that I have to say even when none of it made
sense. She is also a fantastic cook. One day we will create a cookbook together.

John Smith

WroxPro.030912.indd 21

3/14/12 12:25 PM

WroxPro.030912.indd 22

3/14/12 12:25 PM

Contents

TOCTitle

Introduction

ContentsChapterTitle

xix

ContentsPartTitle

Part I: Part Opener Title


Chapter 1: Requirements

ContentsChapterTitle

Problem 1
Design 1
Message Management
Contact Management
Reports and Stats
Miscellaneous Requirements

2
3
5
5

ContentsH1
Solution 6

Model-View-Controller 6
ASP.NET MVC
6
Methodology, Concepts, and Approach
10
ContentsH2
Tools and Frameworks
18

Why EvenContact?
22
Summary 23
Chapter 2: High-Level Design

25

Problem 25
Design 25
Membership 25
Account Management
29
Message Management
31
ContentsH3
Contact Management
32

Solution 34
Summary 34
Part II: Part Opener Title Two
Chapter 3: Membership

35

Problem 35
Design 35
Solution 36
Minor Interruption

WroxPro.030912.indd 23

46

3/14/12 12:25 PM

CONTENTS

Problem 206
Back on Track
Message Templating

207
209

Design 209
Solution 211
My Templates

217

Summary 222
Chapter 4: Billing and Subscriptions

223

Problem 223
Design 223
Solution 224
PayPal Implementation

226

Summary 234
Part III: Part Opener Title Three
Chapter 5: Usage Tracking

235

Problem 235
Design 235
Solution 236
Summary 246
Chapter 6: Fill In the Blanks

247

Problem 247
Design 247
User Interface
247
Refactor and Optimize
248
Scaling 248

Solution 248
User Interface
248
Refactor and Optimize
254
Scaling 257

Summary 259
Appendix A: An Overview of XML

267

Glossary 271
Index

289

xxiv

WroxPro.030912.indd 24

3/14/12 12:25 PM

Foreword

MatterTitle
Para

After three years, the time is here. Microsoft Office SharePoint Server 2007 has shipped with great
fanfare and lots of accolades from customers, partners, and the press.
Its humbling to be part of the team that helped bring this monstrous release to market. When I
worked on SharePoint Portal Server 2001 (codenamed Tahoe back then), Microsoft was making its
first official foray into the portal market with document management added in for good measure. For
those of you who worked with SharePoint in those days, the 2001 version was a good first attempt to
enter into a new market for Microsoft even with some of the limitations we knew the product had.
With the 2007 release, I can definitely say that we have worked hard to make sure SharePoint meets
the needs of diverse sets of customers from the smallest business to the largest enterprise.
So, why should you care about SharePoint and this book?
Well, if you look at the 2007 release, weve extended the surface area of SharePoint twofold. The
previous version of SharePoint was a great collaboration, portal, and enterprise search tool. Weve
enhanced each of those capabilities, while at the same time adding enterprise content management,
business process management and e-forms, and finally business intelligence capabilities to the product. Thats a lot of new technology, information, APIs, and best practices that you need to learn.
Youll need a great teacher and this book is that teacher.
The authors cover the breadth of SharePoint without sacrificing the depth you need to understand
how to build complete and robust SharePoint solutions. In fact, you will find yourself consistently
reaching for this book on your bookshelf, earmarking pages that have the tips and tricks you need
to get your job done, and this book will quickly become an indispensable part of your SharePoint
reference set.
After reading this book, you will become a sought-after SharePoint expert ready to tackle the problems that your users throw at you. I know I learned a number of new things about SharePoint after
reading this book. I think you will, too.
ChapterCredit

WroxPro.030912.indd 25

Tom Rizzo
Redmond, WA
March 2007

3/14/12 12:25 PM

WroxPro.030912.indd 26

3/14/12 12:25 PM

Introduction

IntroductionTitle

Para

Dear reader, thank you for picking up this book, and welcome to the exciting world of Test

Driven Development (TDD) and ASP.NET MVC. Sometime in 2008, I quit my job and decided to
start my own company. Naturally, my startup was web-based. At the time, I was already very familiar with the Microsoft web development platform, a natural choice for my website. I hesitated to use
it because I wanted to learn something new and I wanted to use TDD. Several of the web startups at
the time were written in Ruby on Rails (RoR), and I seriously considered going that route. I played
around with RoR and became familiar with it. I liked its approach to development, the ease of testing, and the control I had over HTML and JavaScript. There are several things that I didnt like,
however, especially the Integrated Development Environment (IDE). Nothing came close to Visual
Studio. Luckily, around that time Microsoft introduced ASP.NET MVC, which made the decision
very easy for me.
Even though ASP.NET MVC was still in early alpha, I went ahead and built my startup on top of
it (talk about taking risks). It was a great experience for me and turned out to be a good decision. I
instantly fell in love with the MVC way of doing things. I enjoyed the control I had over the generated HTML and scripts. I loved the clean and friendly URLs. I cant imagine living without the unit
tests that I could easily run when I make a change to verify that I havent broken anything. I can go
on and on about why I love ASP.NET MVC and TDD and how much more enjoyable they make
programming.
Dont get me wrong, though; its not all sunshine. There is a learning curve. You cant just drag-anddrop a control and instantly have a grid. You cant drag-and-drop a few controls, set a couple properties, and instantly have form validation. ASP.NET MVC requires some manual work. The upside
is that there is no more magic, so you will actually know what is happening on your page, what
gets rendered, and how it gets there. Best of all, you will not see anything that you didnt put on
the page. No more hidden fields, strange scripts, or magical eventsjust straight up HTTP requests.

Who This Book Is For

H1

Do you love programming? I dont mean like or enjoy, I mean love. If you are like me, then you
probably do, and if you do, then you owe it to yourself to learn ASP.NET MVC and to get into Test
Driven Development. They will make something that you already love so much more enjoyable.
With that said, let me state up front that this isnt a book for completely novice programmers, or for
experienced developers who have never touched ASP.NET and the .NET Framework in general. This
book teaches how to write a real-world website from scratch to deployment, and as such, it cant explain
every single detail of the technology, but must concentrate on designing and writing actual solutions. To
read this book comfortably, you should already have had some experience with ASP.NET 2.0, even if
not advanced solutions. Youre not required to know ASP.NET MVC, as each chapter will introduce the
new concepts and features that youll use in that chapter, providing enough background information to

WroxPro.030912.indd 27

3/14/12 12:25 PM

introduction

implement the solution. If you then want to go deeper and learn everything you can about a feature, you
can refer to the MSDN official documentation or to another reference book such as Professional ASP.NET
MVC 1.0 by Rob Conery, Scott Hanselman, Phil Haack, and Scott Guthrie (Wrox, 2009).
This book is not a crash course in ASP.NET MVC, and its also not an advanced ASP.NET MVC
or TDD book. I dont do a lot of handholding, and I dont delve into all the intricacies of the framework or theories of TDD. I wanted this book to be practical and as close to real-world development
as possible. I wanted to create an application, show and explain my decisions, make mistakes, and
fix them.
Think of this book as a documentary. I try to develop a web application from scratch and document
the process. I make mistakes. I correct them. I (and hopefully you) learn from them. I intentionally
kept the mistakes I made in earlier chapters and addressed them in later chapters because I wanted
to show the flexibility, power, and usefulness of Test Driven Development. Do you know the feeling
when you make a change to the code and cross your fingers hoping that you didnt break something
somewhere else in the application? This problem, and the risks associated with it, is greatly diminished when you use TDD. Imagine making a change, running your tests, and instantly finding out
that you just broke six different tests. This immediate knowledge is very comforting. It also allows
you to make changes more frequently, fix bugs easily, and feel confident that your changes didnt
break anything.

What This Book Covers


This book is basically a documentary of creating a web application using Test Driven Development.
This book leads the reader through the development of an ASP.NET MVC 1.0 website that has most
of the features users expect to find in a modern site.
The one thing that sets this book apart is its practicality. You will not find many (if any) theoretical
explanations that span multiple pages. This book covers practical decisions and concepts, such as:

Unit testing frameworks and tools

Inversion of Control and Dependency Injection

Code coverage

Mocking

JavaScript libraries and AJAX

I will also use the following .NET 3.5 features that were added in C# 3.0:

LINQ

LINQ-to-SQL

Extension methods

Anonymous methods

xxviii

WroxPro.030912.indd 28

3/14/12 12:25 PM

introduction

In addition, you will learn how these new features and concepts integrate standard ASP.NET 2.0
features, such as:

Master pages

Membership and profile modules

Not only does this book cover the new features of ASP.NET MVC 1.0; it also demonstrates how to
integrate all of them together in order to develop a single full-featured site. After reading this book,
you will know many of the best practices for web development using TDD.

How This Book Is Structured


This books starts at the beginning of building a web application using TDD. It starts with a highlevel description of the project I am building and then goes into the initial setup and tool selection.
Then I start working my way through the actual development of the application.
There are many steps that are common to each chapter. These steps are explained in detail the first
time, and from then on they are briefly mentioned.
If you want to build the application and follow along, then it will be more useful to read the book in
order. Otherwise, you should be able to open any chapter and learn something new.
Each chapter has three major sections:

ProblemThis defines the problem or problems to be addressed in the chapter: What do you
want to do in this chapter? What features do you want to add to the site and why are they
important? What restrictions or other factors need to be taken into account?

DesignAfter the problem is defined adequately, this section describes what features are
needed to solve the problem. This will give you a broad idea of how the solution will work.

SolutionAfter establishing what I am going to accomplish and why (and how that solves
the problem defined earlier), I will produce and discuss the code and any other material that
will realize the design and solve the problem laid out at the beginning of the chapter. Just as
the book as a whole focuses primarily on the solution, so does each chapter. This is where
you will get hands-on practice and create the code.

What You Need to Use This Book


All you need to follow along in this book is Visual Studio 2008 and ASP.NET MVC 1.0, as well as
the tools, frameworks, and libraries mentioned in the first two chapters. Other than Visual Studio,
all the tools used in the book are free and/or Open Source. There are one or two commercial tools,
but they are only suggested, not required.

xxix

WroxPro.030912.indd 29

3/14/12 12:25 PM

introduction

Conventions
To help you get the most from the text and keep track of whats happening, weve used several conventions throughout the book.
FeatureType = warning

WARNING Boxes like this one hold important, not-to-be forgotten information
that is directly relevant to the surrounding text.
FeaturePara

FeatureType = note

Note Notes, tips, hints, tricks, and asides to the current discussion are offset
and placed in italics like this.

As for styles in the text:

We show filenames, URLs, and code within the text like so: persistence.properties.

We present code in two different ways:

ListBulleted

We use a monofont type with no highlighting for most code examples.


We use bolding to emphasize code thats particularly important in the present
context.

Source Code

CodeHighlight

CodeSnippet

As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All of the source code used in this book
is available for download at www.wrox.com. Once at the site, simply locate the books title (either by
using the Search box or by using one of the title lists) and click on the Download Code link on the
books detail page to obtain all the source code for the book.
FeatureType = note
Note Because many books have similar titles, you may find it easiest to search
by ISBN; this books ISBN is 978-0-470-44762-8.
FeaturePara

Once you download the code, just decompress it with your favorite compression tool. Alternatively, you
can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to
see the code available for this book and all other Wrox books.

InlineURL

xxx

WroxPro.030912.indd 30

3/14/12 12:25 PM

introduction

Errata
We make every effort to ensure that there are no errors in the text or in the code. However, no one
is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or
faulty piece of code, we would be very grateful for your feedback. By sending in errata you may save
another reader hours of frustration, and at the same time you will be helping us provide even higher
InlineURL
quality information.
To find the errata page for this book, go to www.wrox.com and locate the title using the Search box
or one of the title lists. Then, on the Book Search Results page, click on the Errata link. On this page,
you can view all errata that has been submitted for this book and posted by Wrox editors.
FeaturePara

FeatureType = note

Note A complete book list including links and info to errata is also available at
www.wrox.com/misc-pages/booklist.shtml.

Notes, tips, hints, tricks, and asides to the current discussion are offset and
placed in italics like this.
FeaturePara
If you dont spot your error on the Errata page, click on the Errata Form link and complete the form
to send us the error you have found. Well check the information and, if appropriate, post a message to
the books errata page and fix the problem in subsequent editions of the book.
Para

H1

p2p.wrox.com
For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based
system for you to post messages relating to Wrox books and related technologies and interact with
other readers and technology users. The forums offer a subscription feature to email you topics of
interest of your choosing when new posts are made to the forums. Wrox authors, editors, other
industry experts, and your fellow readers are present on these forums.
At http://p2p.wrox.com you will find a number of different forums that will help you not only as
you read this book, but also as you develop your own applications. To join the forums, just follow
these steps:
ListNumbered

Go to p2p.wrox.com and click on the Register link.

1.
2.
3.

4.

You will receive an email with information describing how to verify your account and complete the joining process.

Read the terms of use and click Agree.


Complete the required information to join as well as any optional information you wish to
provide and click Submit.

Para
xxxi

WroxPro.030912.indd 31

3/14/12 12:25 PM

introduction

Note You can read messages in the forums without joining P2P, but in order to
post your own messages, you must join.

Once you join, you can post new messages and respond to messages other users post. You can read
messages at any time on the Web. If you would like to have new messages from a particular forum
emailed to you, click on the Subscribe to this Forum icon by the forum name in the forum listing.
For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to
questions about how the forum software works as well as many common questions specific to P2P
and Wrox books. To read the FAQs, click on the FAQ link on any P2P page.

xxxii

WroxPro.030912.indd 32

3/14/12 12:25 PM

Style as PartTitle, Part number and Part


title should be on one line in manuscript

PART I

PartTitle

an Overview of excel services


chapter 1: Introduction to Excel Services
chapter 2: Getting Started with Excel Services
PartFeaturingList

chapter 3: Architecture
chapter 4: XML

WroxPro.030912.indd 997

3/14/12 12:25 PM

WroxPro.030912.indd 998

3/14/12 12:25 PM

NOTE: There is NO monofont in heads and


figure and table captions

The bubblesheeT does noT


show conTenT from an acTual
chapTer and should only
be used for formaTTing. for
specific conTenT informaTion
please refer To The series
guideline documenTaTion.

ChapterTitle

Chapter number and Chapter title should be


on one line in manuscript

nHibernate with aSP.net


What's In thIs chapter?

ChapterTitle

ChapterObjectiveTitle

How to build a very simple web application that will immediately


introduce you to NHibernate .

Understanding the concepts behind NHibernate in detail .

Showing you how to leverage the power of NHibernate as an Object


Relational Mapper to help remove the monotony of setting up and
creating your data layer .

WrOx.cOm cOde dOWnLOads FOr thIs chapter

ChapterObjective

ChapterIntroductionHead

Wrox.com
downloads

The wrox.com code downloads for this chapter are found at www.wrox.com/remtitle.cgi
?isbn=0123456789 on the Download Code tab. The code for this chapter is divided into the

Option 1

following major examples:

MyBasePageCS.zip

MyBasePageVB.zip

maximum
5 ListBulleted
items

WrOx.cOm cOde dOWnLOads FOr thIs chapter

Wrox.com
downloads

Para

ChapterIntroductionHead

The wrox.com code downloads for this chapter are found at www.wrox.com/remtitle.cgi
?isbn=0123456789 on the Download Code tab. The code is in the chapter xx download and

Option 2

individually named according to the names throughout the chapter.

What Is an Object reLatIOnaL mapper?

H1

The role of an Object Relational Mapper (ORM) is to bridge the gap between the relational
model (the database) and the object-oriented model. This problem is often referred to as the
impedance mismatch. Using mapping fi les or attributes on a business object.

WroxPro.030912.indd 999

3/14/12 12:25 PM

1000

CHAPTER 1 NHibernate with ASP.NET


H2

Why NHibernate?
NHibernate is a port of the popular Open Source Hibernate Framework for Java. Hibernate has
been around for years, and its a proven and robust piece of software. ORM has had a slow takeup in the .NET world, but with the release of LINQToSQL and the beta of the Entity Framework,
many developers are starting to see the benefit of automating their Data Access Layer.
One of the best features of NHibernate, in my opinion, is the support for transparent persistence
this means that your business objects dont have to inherit from any base classes or implement any
framework interfaces. This enables you as a developer to build a rich model of a problem domain
and put off worrying about persistence requirements to the end. This is why I have chosen to use
NHibernate as my ORM of choice, and after you read this article, I hope you start to use it as well.
Warning You will often see the terms exception and error used interchangeably, although technically they are not the same thing. An error is simply any
situation in which unwanted or unexpected results occur, while an exception is
a specific object instantiated in response to a runtime error. However, as long as
its understood that youre talking about runtime errors, swapping these terms is
usually not a problem. For more information, go to www.wrox.com.
InlineURL

Getting Started with NHibernate


Before we get into the details of NHibernate, I think its important to show you how powerful it is with
a quick demo project. By the end of this small project, you will have a real taste for what NHibernate
can offer you and just how much time its going to save you.
Now that you have NHibernate, its time to start writing the Quick
Demo project. Open Visual Studio and create a new blank solution
called NHibernate.QuickDemo, as shown in Figure1-1.
Add a Class Library project to the solution by following these steps:

1.
2.
ListNumbered
3.

From the File menu, select AdddNew Project. MenuArrow


Select a Visual Basic Class Library.
When a figure

Name the Class Library NHibernate.QuickDemo.


is 1/2 the width
NHibernateDAL.
of the text block

Add a web site to the solution by following these steps:


12.

From the File menu, select AdddNew Website.

ListNumberedSub

i.

Figure1-1: The solution


structure of a newly created
Silverlight Application project type.

Select an ASP.NET web site with the language set as


Visual Basic.

ii.

or smaller, text
should wrap
around it.

Name the web site NHibernate.QuickDemo.Web.

ListNumberedSub2

Your solution should resemble the solution posted earlier.

WroxPro.030912.indd 1000

3/14/12 12:25 PM

Getting Started with NHibernate

1001

Add a new SQL Express 2005 database to the web project, and name it QuickDemo.mdf. Visual
Studio will prompt you to ask if you want to place it in the App_Data folder. Do so and add a new
table to the database called People with the column definitions shown in Table1-1.
Add a class file to the Class Library project called person as defined in Listing1-1. This will be the
plain old business object that you will map to the database table.
Listing1-1: Selectors Example SelectorsAPIExample01.htm

protected void LogEntry(object sender, EventArgs e)


{
string path = GetPathToLog();
try
{
StreamWriter writer = File.AppendText(path);

CodeTitle

Listing title or TIO title


should match the name of
the download file.

CodeListing

writer.WriteLine(DateTime.Now.ToString(CultureInfo.InstalledUICulture));
writer.WriteLine(Entry: {0}, txtLogEntry.Text);
writer.WriteLine(-------------------);
writer.Dispose();
}
catch (PathTooLongException)
{
Response.Write(
The path contains too many characters.);
catch (DirectoryNotFoundException)
{
Response.Write(The specified path is invalid.);
}
catch (IOException)
Response.Write(There was a problem accessing the file.);
}

Now add a reference to the NHibernate.dll from the location where you extracted the NHibernate
files and folders. If you were following along, the NHibernate.dll will be found in the folder
C:\NHibernate\bin\net-2.0.
InlineCode
TableCaption
Table1-1: XPath Overview
Description

Node Name

Retrieves the node

Selects nodes from the root, for example, /menu/section retrieves the section
nodes that are children of the menu node

&5

Selects an attribute, so in the example, this is how we retrieve the section title,
and the links url and name

TableEntry

WroxPro.030912.indd 1001

TableHead

Expression

continues

3/14/12 12:25 PM

1002

CHAPTER 1 NHibernate with ASP.NET

Table1-5 (continued)
Expression

Description

Selects nodes from the root, for example, /menu/section retrieves the section
nodes that are children of the menu node

//

Selects all children nodes regardless of where they are; for example, we could use
//link to retrieve every link element without having to navigate down through
the section

Selects an attribute, so in the example, this is how we retrieve the section title,
and the links url and name

Fill in the textboxes with a first and last name, select a date, and then click on the Add Person
button. Do this a couple of times with different data, and you will see your people appear on the
grid. If you take a look in the People database table, you will see your newly added Person.
EquationNumbered

Equation

(x+1)2 = 2x 2 + x + 1

(x+1)2 = 2x2 + x + 1

(1)

Dont worry if you didnt understand exactly how it workedthats whats covered in the rest of
this article. When you have learned all about the concepts and features of NHibernate, you will
build a real-world ASP.NET application with more of an enterprise feel so you can see how to use
NHibernate in your line-of-business applications.

Architecture and Core Concepts


Before we start going into the details of the NHibernate Framework API, its important to understand some concepts that you used in the Quick Demo project in Part 1.
H3

Configuration, ISession, and ISessionFactory


Listing8 walks you through the steps you took in the demo project and the different parts of
NHibernates framework that you met. You created an instance of NHibernates configuration
class, called the configure method, which set up NHibernate based on the application configuration file, which in this case was the web.config file. You then added the assembly that contained the
embedded mapping metadata, and lastly, you asked the configuration to build an instance of the
ISessionFactory.
H4

ISessionFactory
An ISessionFactory is typically created as a singleton object; this is because of the relatively
expensive operation of creating it. One of the jobs of the SessionFactory is to provide ISession
instances. The ISession is the main interface used to persist and retrieve business entities. In the
demo project, you used it to retrieve all the people from the database, as can be seen in Listing9,
and persist new people. Think of ISession as your gateway to the database or, as the NHibernate
site defines it, as the persistence manager, and then send email to [email protected].

InlineEmail

WroxPro.030912.indd 1002

3/14/12 12:25 PM

Getting Started with NHibernate

ISession

1003

Option A for code snippets where an entire section used the same code
(no need to repeat the code name with every snippet):

All of the code in this section uses SelectorsAPIExample01.htm code file. An ISession instance will
enable you to retrieve and persist your business objects. There are a variety of ways to do this with
NHibernate, and I will go into them in more detail later in this article.
SETS WIDTH AND HEIGHT

<TextBlock TextWrapping=Wrap >


<TextBlock.Foreground>
<LinearGradientBrush EndPoint=0,0 StartPoint=1,1>
<GradientStop Color=#FFFF2300/>
<GradientStop Color=#FFFB00FF Offset=1/>
ADDS PADDING
<GradientStop Color=#FFF0FF00
Offset=0.25900000333786011/>
<GradientStop Color=#FF1CFF00
<GradientStop Color=#FF0B07FF
Offset=0.75900000333786011/>
</LinearGradientBrush>
</TextBlock.Foreground>

ADDS MORE TEXT

The ISession interface implements the Unit of Work patterna number of actions can be performed
on business entities, and the session will keep track of the updates, additions, and deletions; then,
using a transaction, all changes can be committed as part of one atomic action. You will see this
later when you look at the ITransaction interface. A second pattern that NHibernate makes use of
is the Identity Map pattern. NHibernate uses an Identity Map to maintain a single instance of each
persistent entity in the ISession no matter how many times you retrieve the same entity.

ITransaction
NHibernate supports its own Transaction API via the ITransaction interface. Now you may be
asking, why is another Transaction API needed when we have ADO.NET transactions as well as
many others? The advantage is that by using NHibernates implementation, we can abstract away
the concrete underlying Transaction API, which enables you to code against a consistent Transaction
API no matter what your underlying database or environment is.

IQuery and ICriteria


NHibernate has two interfaces for queryingthe IQuery and the ICriteria interfaces. IQuery
supports NHibernates own brand of SQLHQLthat queries using object syntax: that is,
classes and properties versus SQL syntax tables and columns. The ICriteria interface enables the
querying of entities in an object-oriented manner as well as querying by example. NHibernate
also supports native SQL for retrieving entities;
you look at all of these different methods in more
detail later in this article (see Figure1-2).
To retrieve all the people in the database, I have
used the Criteria API. The Criteria API is one of
the two main APIs for querying the database. If
create an instance of a criterion that will be used

WroxPro.030912.indd 1003

Figure1-2: IntelliSense displays all of the objects in


that namespace.

3/14/12 12:25 PM

1004

CHAPTER 1 NHibernate with ASP.NET

to query against the Person entity. I then just call a list to return all of the people. If I wanted to add
a clausesuch as people whose name began with a PI would need to add a criterion to the
criteria, but more on this later in the article (see Listing1-2).
Listing1-2: Exception handling in a CreateUserWizard control

protected void CreateUserWizard1_CreateUserError(object sender,


CreateUserErrorEventArgs e)
{
switch (e.CreateUserError)
{
case MembershipCreateStatus.DuplicateUserName:
litResult.Text =
That user name is taken. +
Please enter a different user name.;
break;
case MembershipCreateStatus.InvalidUserName:
litResult.Text =
The user name provided is invalid. +
Please check the value and try again.;
break;
case MembershipCreateStatus.DuplicateEmail:
litResult.Text =
A user with that email address already exists. +
Please enter a different email address.;
break;
case MembershipCreateStatus.InvalidPassword:
litResult.Text =
The password provided is invalid. +
Please enter a valid password.;
break;
case MembershipCreateStatus.InvalidEmail:
litResult.Text =
The email address is invalid. +
Please check the email address and try again.;
break;
CodeHead

CodeHead
case MembershipCreateStatus.InvalidAnswer:
litResult.Text =
The password retrieval answer provided is invalid. +
Please check the answer and try again.;
break;
litResult.Text =
The password retrieval answer provided is invalid. +
Please check the answer and try again.;

WroxPro.030912.indd 1004

3/14/12 12:25 PM

Using NHibernate

1005

break;
case MembershipCreateStatus.ProviderError:
litResult.Text =
An error occurred. The user was not created. +
Please verify your input and try again.;
litResult.Text =
break;
}
}

The CreateUserError event handler in Listing15 uses the CreateUserError property of the passedin CreateUserErrorEventArgs object to determine what error has occurred and notifies the user
accordingly. The CreateUserError property is an enumeration of type MembershipCreateStatus,
which contains all the possible outcomes from an attempt to create a user.

Using NHibernate
Now that you have a good grounding in the main components of NHibernate, its time to find out
how you can leverage it into your line-of-end-business applications. I find the best way to learn is by
example, so I am going to follow the Wrox ProblemDesignSolution approach to a small application. Lets begin by looking at the requirements (see Figure1-3).
RMS
Roles
End User

HIPAA
Compliance
Officer

SOX
Compliance
Officer

Administrator

Responsibilities
Ensure the validity
of document
metadata

Ensure
confidentiality of
patient records

Ensure
accuracy of
financial records

Optimize storage
bandwidth and
performance

FigureLabel
Activities
Send
documents
to the
repository

Procedures

Assign
permissions

Monitor
access to
patient
records

Policies
Requests

Perform
consistency
checks
on records

Logs
Logs

Gather
and monitor
system
metrics

Validation Rules

Metrics

Documents

287620
Ch01 figure
05 f0105.eps
Figure1-3: This is just a regular
full-size
figure.

9/03/09 rs

Slug

WroxPro.030912.indd 1005

3/14/12 12:25 PM

1006

CHAPTER 1 NHibernate with ASP.NET

Before we can start to build an application, we need a set of requirements. This section will introduce a sample set of requirements for a fictitious mail order company. Once we have these requirements, we can define an architecture that will best suit the solution and one that will shape the rest
of our project.
The company has these requirements for the software:

The ability to add, remove, and update customers. However, no customer should be able to
be deleted if they have placed an order with us.
The ability to add, remove, and update products; again, we do not want products that have
been ordered to be deleted.

ListPara

The ability to create an order

The ability to process orders that we have stock for. When an order is processed, we need
the product stock to decrease by the amount shipped. Because the company also has plans
for other systems like mobile devices for dispatchers and rich clients for sales staff to interact
with orders, so some kind of concurrency check must be put in place.

The Design
Based on the requirements, the system will have a small amount of business logic to start with but
will increase as the software evolves over time. You need to ensure that you can isolate the business
logic and process from the code that is used to present it. To keep focused on the business problem,
you will be following a domain-driven approach and using a Domain Model pattern to model the
business problem. The Domain Model will implement all of the business rules, processes, and logic
and will represent the problem domain in code.
The architecture will consist of the following layers:

ListHead
ListUnmarked

ListHead

User Interface (UI)T his layer is responsible for displaying the data and handling
user commands. In this application, you are using ASP.NET pages, but you could easily
add a Win Forms or WPF front-end with only a few minor changes to the applications
configuration.
Presentation LayerT his layer is the interface between the UI (in this case, the ASP.NET
pages) and the rest of the application. This layer will contain some validation logic and can
be easily unit tested and used with a variety of different UIs.
Service LayerT he Service Layer acts as the entry point into the application and
coordinates all activity between the presentation layer and the repositories. The
services will expose business use cases and will be autonomous.

ListUnmarkedSub

Domain ModelT he Domain Model contains all of the business objects,


business rules.

ListUnmarkedSub2

Repository (Data Access Layer)T he Repository acts like an in-memory domain collection. It is used to persist and retrieve our domain business objects. The Repository Layer
needs to support Lazy Loading, concurrency checks, querying of business entities, and a
transaction interface that can be controlled via the service layer.

WroxPro.030912.indd 1006

3/14/12 12:25 PM

Using NHibernate

1007

The Solution
The solution will be written in Visual Studio 2008 with a SQL Express 2005 database.
Not surprisingly, I am going to be using NHibernate as my Data Access Layer because it has built-in
support for concurrency, transactions, and Lazy Loading. NHibernate also gives you transparent
persistence, which will allow me to build my Domain Model without hindrance, and if you want to
change my Data Access Strategy at a later date, you will be able to with no change to your Domain
Model as in Tables 1-2 and 1-3.
Table1-2: The Mapping Relationships that NHibernate Supports
set narrow tables to 23p0 wide

Relationship

Ex ample

One-to-one

One customer has one payment card.

One-to-many

One customer has many orders.

Many-to-many

Customers can rent many DVDs, and a


DVD can be rented by many customers.

Many-to-one

Many orders are placed by one customer.

table footnote

TableFootnote

TabularHead
Mapping Collection type

When to Use and .NET Type

Bags

Collection of objects each element can repeat. Implemented as


IList, or IList(Of T).

Sets

Collection of objects; each element must be unique. Implemented


as ISet or ISet(Of T) using the Iesi.Collections.dll
namespace.

List

TabularEntry

Map

Collection of object with integer indices. Each element can repeat.


Implemented as IList or ArrayList.
Collection of Key/Value pairs. Implemented as Hashtable or
IDictionary.

Figure1-19 shows how you would map a simple one-to-many relationshipan Order and its
OrderItems.
The table definitions for this example are shown in Table1-5 and Table1-6.
The object-oriented model of the relationship (shown in Listing1-54) uses an IList(Of OrderItem)
to store the Items collection. I could have also used an ISet(Of OrderItem) as well, as the order
should not contain any duplicate OrderItems.*
*Footnote on a page

WroxPro.030912.indd 1007

FootnoteEntry

3/14/12 12:25 PM

1008

CHAPTER 1 NHibernate with ASP.NET

Listing1 has a call to File.AppendText (which takes as an argument a string indicating the physical path to the file you want to append to), as well as several has a call to File.AppendText (which
takes as an argument a string indicating the calls to the StreamWriter.WriteLine

path could be an empty string.

path could be null.

ListBulleted

ListBulletedSub

It would be great if there was a way to defer the loading of the full list of orders
until you really needed it.

path could be too long.

ListParaSub

ListBulletedSub2

path could be in an invalid format.

The file may be Read Only.

The file may be locked by a previous process.

There could be a disk error while opening the file or writing to the disk.

InlineCode

Note that the foreign key in the object is a full order, not just an order ID property.

FeatureType = note

Note When handling an exception, avoid throwing a new exception that fails
to include the original exception in its InnerException property, as all the information about the original exception is then lost. The new exception starts a new
stack trace starting from the exact spot.

FeaturePara

Windows error occurred while running SP_TRACE_CREATE. Error =


0x80070050(failed to retrieve text for this error.
Reason: 15100).
Msg 19062, Level 16, State 1, Procedure sp_trace_create, Line 1
Could not create a trace file.

FeatureCodeSnippet

FeaturePara

The new exception starts a new stack trace starting from the exact spot where
you threw it, making it appear as though this is where the error actually
originated.

There was a requirement to ensure that customers with orders were not deleted. Now you can easily
check if a customer has an order by inspecting his or her orders collectionif the count is 0, then
you can safely remove them; and if it is 1 or greater, then you cannot.
Relationship

Ex ample

One-to-one

One customer has one payment card.

One-to-many

One customer has many orders.

Many-to-many

Customers can rent many DVDs, and a


DVD can be rented by many customers.

WroxPro.030912.indd 1008

3/14/12 12:25 PM

Using NHibernate

1009

6 Terabytes of Usable Capacity Looks Like:


RAID 5 Configuration Means 7 1TB Drives:
1TB

1TB

1TB

1TB

1TB

1TB

data

data

data

data

data

data

1TB
data

RAID 10 Configuration Means 12 Drives:


1TB

1TB

1TB

1TB

1TB

1TB

data

data

data

data

data

data

+ Mirrored Copy:
1TB

1TB

1TB

1TB

1TB

1TB

data

data

data

data

data

data

RAID 5 Configuration Means 4TB of Usable Capacity:


1TB

1TB

1TB

1TB

1TB

1TB

data

data

data

data

data

data

1TB
data

Copyright 2001, Library of Congress.

FigureSource

Figure1-4: This is just a regular full-size figure.

Following Along?
If you are following along and building the projects as I progress through the application, simply
follow the steps below; or alternatively, you can download the entire application from the Wrox site:

1.

Add a reference to the System.Web.dll from the ACompany.OrderProcessing.NHibernate


Repository project by right-clicking on the project and selecting Add Reference, then
finding the System.Web component from the list and clicking OK. You need to add this
reference because you need to implement the IHttpModule and obtain a reference to the
applications HttpContext.

2.

Add a new class to the ACompany.OrderProcessing.NHibernateRepository project, and


name it NHibernateHttpModule. The code definition can be found in Listing1-65.

3.

Add the NHibernate configuration section as defined in Listing66 to the web.config file
located in the web site project. Dont worry that Visual Studio will complain about the
namespacethis will be fixed later when you add the reference to the Presentation project.

4.

Add the context property definition as described in Listing64 to the web.config file within
the web site project. This will let NHibernate know that you want to store the current session
in a Web context.

5.

Add the GetCurrentSession() method to the SessionFactory class within the


ACompany.OrderProcessing.NHibernateRepository project, as defined in code Listing1-67.

6.

Refactor the NHibernateRepository class from the ACompany.OrderProcessing.


NHibernateRepository project by adding support for the current session, as defined in
Listing1-68.

Your solution should now resemble the solution in Figure1-23.

WroxPro.030912.indd 1009

3/14/12 12:25 PM

1010

CHAPTER 1 NHibernate with ASP.NET

Overriding the equals and getHashCode Methods in the Business Base


One thing I havent talked about is ensuring that we always identify an entity by its ID. Its important to override the equals and getHashCode methods of each of the entities because NHibernate
will use proxy classes for the Lazy Load features, and comparing objects may bring undesired
results. Also if you are using more than one NHibernate session, overriding the equality methods will ensure that NHibernate will identify an entity in the correct way. You can add a new
method definition to the IEntity interface to support equality checking as seen in Listing1-87.
The updated BusinessBase class with equality overrides is displayed in Listing1-88. (code file:
SelectorsAPIExample01.htm)
CodeSnippet
Imports ACompany.OrderProcessing.Presentation
Imports ACompany.OrderProcessing.Infrastructure
Option B for code snippets if there
Imports ACompany.OrderProcessing.Model
are multiple individual downloads
Partial Class CustomerList
add the following sentence to the
Inherits System.Web.UI.UserControl
end of the preceding paragraph.
Implements ICustomerListView
The wording can be different but the
Private _Presenter As CustomerListPresenter
meaning should be the same
Protected Sub Page_Init(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles Me.Init
_Presenter = New CustomerListPresenter(Me)
End Sub
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles Me.Load
_Presenter.Display()
End Sub
Public WriteOnly Property Customers() As List(Of Customer) _
Implements ICustomerListView.Customers
Set(ByVal value As List(Of Customer))
Me.grdCustomers.DataSource = value
Me.grdCustomers.DataBind()
End Set
End Property
Protected Sub btnNewCustomer_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnNewCustomer.Click
Response.Redirect(CustomerDetail.aspx)
End Sub
Protected Sub grdCustomers_RowCommand(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) _
Handles grdCustomers.RowCommand
Select Case e.CommandName.ToLower()
Case deletecustomer
_Presenter.RemoveCustomerBy( _
New Guid(e.CommandArgument.ToString))
End Select
End Sub

The remainder of the pages in the web site project follow the same logic using user controls to implement the views from the presentation project and creating a presenter in the code-behind to interact
with the model.

WroxPro.030912.indd 1010

3/14/12 12:25 PM

using nHibernate

1011

Again, I will only be showing you the code required to satisfy the customer management requirements. You will be able to inspect all of the other classes involved in the ASP.NET layer from the
complete application download from the Wrox web site. Lets ensure that the user can actually view
the Register page. We start by creating a simple test that would simply need to show whether a user
can navigate to the Register view i.e. http://evencontact.com/account/register.
One thing I havent talked about is ensuring that we always identify an entity by its ID. Its important to override the equals and getHashCode methods of each of the entities because NHibernate
will use proxy classes for the Lazy Load features, and comparing objects may bring undesired
results. Also if you are using more than one NHibernate session, overriding the equality methods
will ensure that NHibernate will identify an entity in the correct way. You can add a new method
defi nition to the IEntity interface to support equality checking as seen in Listing1-87. The updated
BusinessBase class with equality overrides is displayed in Listing1-88.
Not surprisingly, I am going to be using NHibernate as my Data Access Layer because it has built-in
support for concurrency, transactions, and Lazy Loading. NHibernate also gives you transparent
persistence, which will allow me to build my Domain Model without hindrance, and if you want to
change my Data Access Strategy at a later date, you will be able to with no change to your Domain
Model as in Tables 1-2 and 1-3.
FeatureType = general

FeatureTitle

FeaturePara

cOnVentIOn
Test classes will be named as follows [class name]Tests, for example if we are testing
the PayController class then the test fi xture will be named PayControllerTests.
Test methods will be named using clear and descriptive names that clearly identify
the test and its outcome. You can either separate the name using capitals or using
underscores. For example:
CallbackShouldReturnNull or callback_should_return_null
FeatureCodeSnippet
public void Register_Can_Successfully_Register_New_User()
{
var ac = new AccountController();
var results = ac.Register(username, email,
question, answer, password);
FeatureCodeSnippet +
Assert.IsNotNull(results);
CodeHighlight
results);
var typedResults = results as RedirectToRouteResult;
Assert.AreEqual(Index,

One thing I havent talked about is ensuring that we always identify an entity by its
ID. Its important to override the equals and getHashCode methods of each of the
entities because NHibernate will use proxy classes for the Lazy Load features, and
comparing objects may bring undesired results. Also if you are using more than one
NHibernate session, overriding the equality methods will ensure that NHibernate
will identify an entity in the correct way. You can add a new method defi nition to
the IEntity interface to support equality checking as seen in Listing1-87.
continues
FeaturePara

WroxPro.030912.indd 1011

3/14/12 12:25 PM

1012

chapter 1 NHiberNate witH aSP.Net

continued

Not surprisingly, I am going to be using NHibernate as my Data Access Layer


because it has built-in support for concurrency, transactions, and Lazy Loading.
NHibernate also gives you transparent persistence, which will allow me to build
my Domain Model without hindrance, and if you want to change my Data Access
Strategy at a later date, you will be able to with no change to your Domain Model
as in Tables 1-2 and 1-3.
I personally prefer the underscore method but there will be a mix of both in the
code. I settle on using lower cases and underscores towards the end of the book.

Run the test. The test passes (green light). Woohoo!!! Our fi rst test works.
nOte This is a very simple action and test, so there isnt really much to refactor. At least, for now.

Moving on. We need to write tests for the second Register Action, the one that actually registers the
user. We want to:

Ensure that a Register action exists with the correct signature

Ensure that the user is registered

Ensure that we are redirected to the homepage after registration

Again, I will only be showing you the code required to satisfy the customer management requirements. You will be able to inspect all of the other classes involved in the ASP.NET layer from the
complete application download from the Wrox web site. Lets ensure that the user can actually view
the Register page. We start by creating a simple test that would simply need to show whether a user
can navigate to the Register view i.e. http://evencontact.com/account/register.
One thing I havent talked about is ensuring that we always identify an entity by its ID. Its important
to override the equals and getHashCode methods of each of the entities because NHibernate will
use proxy classes for the Lazy Load features, and comparing objects may bring undesired results.
Also if you are using more than one NHibernate session, overriding the equality methods will ensure
that NHibernate will identify an entity in the correct way. You can add a new method defi nition to
the IEntity interface to support equality checking as seen in Listing1-87. The updated BusinessBase
class with equality overrides is displayed in Listing1-88.

WroxPro.030912.indd 1012

3/14/12 12:25 PM

Using NHibernate

1013

Here is our first test


public void Register_Can_Successfully_Register_New_User()
{
var ac = new AccountController();
var results = ac.Register(username, email,
question, answer, password);
Assert.IsNotNull(results);
Assert.IsInstanceOfType(typeof(RedirectToRouteResult), results);
var typedResults = results as RedirectToRouteResult;
Assert.AreEqual(Index,
typedResults.Values[action],
Wrong action);
Assert.AreEqual(Home,
typedResults.Values[controller],
Wrong controller);
}

In this test, we check that the returned value is not null and that it is of type RedirectToRoute
Result. Then we make sure that it is redirecting to the correct destination i.e. /home/index. Then
we check that page title is correct. There are two Register actions that we need to accommodate.
One action just displays the view that would happen with a GET request and the other will submit
the form to the server to perform the registration that would happen with a POST request.

Bill Gates earns $250 every SECOND; thats about $20 million a DAY and
$7.8 billion a YEAR!
QuotePara
If he drops a thousand-dollar bill, he neednt even bother to pick it up because
in the four seconds it would take him to pick it up, he wouldve already earned
it back.
QuoteSource

Joe Everymans Blog

As Microsoft has morphed and spread into new markets over the years, Gates has remained the constant star by which everything and everyone connected with the company has navigated. In short,
up until this point, Microsoft has been all about Bill.

WroxPro.030912.indd 1013

3/14/12 12:25 PM

1014

CHAPTER 1 NHibernate with ASP.NET


H1

Recommended Reading
Wardriving & Wireless Penetration Testing by Chris Hurley, Russ Rogers, Frank Thornton, and
Daniel Connelly (Syngress Publishing. ISBN: 159749111X)
Infosec Career Hacking: Sell Your Skillz, Not Your Soul by Aaron W. Bayles, Chris Hurley, Johnny
Long, and Ed Brindley (Syngress Publishing. ISBN: 1597490113)
Reference

OnlineReference Option A

OnlineReference Option B

Insert Graphic [blurb1.ai]


space above varies, generally placed at
the bottom of a page. If wording doesnt
match, graphic will need to be updated.
Apply para style _AnchoredGraphic and
object style Reference.

Insert Graphic [blurb2.ai]


space above varies, generally placed at the
bottom of a page. If wording doesnt match,
graphic will need to be updated. Apply para style
_AnchoredGraphic and object style Reference.

CONFER PROGRAMMER TO PROGRAMMER ABOUT THIS TOPIC.

Visit p2p.wrox.com

YOU CAN DOWNLOAD THE CODE FOUND IN THIS BOOK. VISIT WROX.COM
AND SEARCH FOR ISBN 9780470123456
Neither should be used in the middle of a chapter. End of chapter
only and not on every chapter. Very occasionally.

WroxPro.030912.indd 1014

3/14/12 12:25 PM

NOTE: For multiple appendixes, use a letter


AppendixLetter and AppendixTitle should be
on one line in the manuscript

AppendixTitle

regular expressions
Thomas Hardy

AppendixTitle

ChapterAuthor

This appendix examines some basic aspects of constructing regular expressions. One reason
for working through the simple regular expressions presented in this chapter is to illuminate
the regular expressions used in Chapter 3 and extend your knowledge of regular expressions.
nOte This appendix has been borrowed from Beginning Regular
Expressions (Wiley Publishing, Inc., 2005) by Andrew Watt. We recommend this book for further (and more comprehensive) reference into the
world of regular expressions.

This Appendix looks at the following:

How to match single characters

How to match optional characters

How to match characters that can occur a specified number of times Matching Single
Characters

LIstInga-1: logentry method with exception type-filtering

protected void LogEntry(object sender, EventArgs e)


{
string path = GetPathToLog();
try
{
StreamWriter writer = File.AppendText(path);
writer.WriteLine(DateTime.Now.ToString(CultureInfo.InstalledUICulture));

continues

WroxPro.030912.indd 1015

3/14/12 12:25 PM

1016

Appendix ARegular Expressions

Listing1-1 (continued)

writer.WriteLine(Entry: {0}, txtLogEntry.Text);


writer.WriteLine(-------------------);
writer.Dispose();
}
catch (PathTooLongException)

Matching Single Characters

style RunInHead and RunInPara


as two separate lines & styles

The simplest regular expression involves matching a single character. If you want to match a single,
specified alphabetic character or numeric digit, you simply use a pattern that consists of that characRunInHead ter or digit. So, for example, to match the uppercase letter L, you would use the following pattern:
RunInParaAny occurrence of the uppercase L. You have not qualified the pattern in any way to
limit matching, so expect it to match any occurrence of uppercase L. Of course, if matching is being
carried out in a case-insensitive manner (which is discussed in Chapter 4), both uppercase L and
lowercase l will be matched.
RunInPara
RunInParaSubThe matching of the pattern L in OpenOffice.org Writer against the sample
document UpperL.txt. Notice that there are five matches contained in the sequences of characters XLM, CMLIII, Leoni, Legal, and Lewinski.

RunInHead

RunInParaSub

The default behavior of OpenOffice.org Writer is to carry out a case-insensitive match. As you can
see in Figure A-1, I have checked the Match Case check box so that only the same case as specified
in the regular expression is matched.
Question

Interview Q&A

Q:

If my wireless network doesnt have a lot of traffic, is it okay to use WEP because the IVs
required to crack the WEP key wont be generated?

A:

No. Automated tools are available that allow attackers to capture an ARP packet and reinject it to the access point very rapidly. This generates a significant amount of traffic and
allows the attacker to capture enough unique initialization vectors to quickly crack the key.

Q:
A:

What is the difference between active and passive WLAN detection?

Active WLAN detection requires that the SSID be broadcast in the beacon frame. Passive
WLAN detection listens to all traffic in range of the device and determines what WLANs
are in range.
Answer

WroxPro.030912.indd 1016

3/14/12 12:25 PM

NOTE: For a single appendix, drop the letter

appendIx

style as MatterTitle, Comp will


apply correct style

regular expressions
Mail your packages early so the post office can
lose them in time for Christmas.

Johnny Carson

Epigraph
EpigraphSource

This appendix examines some basic aspects of constructing regular expressions. One reason
for working through the simple regular expressions presented in this chapter is to illuminate
the regular expressions used in Chapter 3 and further extend your knowledge of regular
expressions.
The following exercises use OpenOffice.org Writer a free document editor that makes it
easy to apply regular expressions to text, and verify that they do what you expected. You can
download this tool from http://www.openoffice.org.
nOte This appendix has been borrowed from Beginning Regular
Expressions (Wiley Publishing, Inc., 2005) by Andrew Watt. We recommend this book for further (and more comprehensive) reference into the
world of regular expressions.

One of the issues this chapter explores in some detail is the situation where you want to match
occurrences of characters other than those characters simply occurring once.
This Appendix looks at the following:

WroxPro.030912.indd 1017

How to match single characters

How to match optional characters

3/14/12 12:25 PM

1018

RunInParaSub

appendIx regular exPreSSioNS

RunInPara

matchIng sIngLe characters


The simplest regular expression involves matching a single character. If you want to match a single,
specified alphabetic character or numeric digit, you simply use a pattern that consists of that characRunInHead ter or digit. So, for example, to match the uppercase letter L, you would use the following pattern:
runInpara Any occurrence of the uppercase L. You have not qualified the pattern in any way to
limit matching, so expect it to match any occurrence of uppercase L. Of course, if matching is being
carried out in a case-insensitive manner (which is discussed in Chapter 4), both uppercase L and
lowercase l will be matched.

RunInHeadSub

runInparasub The matching of the pattern L in OpenOffice.org Writer against the sample
document UpperL.txt. Notice that there are five matches contained in the sequences of characters XLM, CMLIII, Leoni, Legal, and Lewinski.

The default behavior of OpenOffice.org Writer is to carry out a case-insensitive match. As you can
see in Figure A-1, I have checked the Match Case check box so that only the same case as specified
in the regular expression is matched.
FeatureType = general

_FeatureParaAfterTitle

FeatureTitle

cOnVentIOn
Test classes will be named as follows [class name]Tests, for example if we are testing
the PayController class then the test fi xture will be named PayControllerTests.

1.

Test methods will be named using clear and descriptive names that clearly identify the test and its outcome. You can either separate the name using capitals or
FeatureListNumbered
using underscores. For example:

CallbackShouldReturnNull or callback_should_return_null
public void Register_Can_Successfully_Register_New_User()
{
var ac = new AccountController();
var results = ac.Register(username, email,
FeatureCodeSnippet +
question, answer, password);
CodeHighlight
Assert.AreEqual(Index,

FeatureCodeSnippet

I personally prefer the underscore method but there will be a mix of both in the
code. I settle on using lower cases and underscores towards the end of the book.

I personally prefer the underscore method but there will be a mix of both in the
code. I settle on using lower cases and underscores towards the end of
the book.
FeatureListBulleted

Widespread industry support exists for XML. There are also some subtle
differences in the way Apache handles rules for mod_rewrite in .htac vs.
httpd.conf.Numerous tools and utilities are being with Web browsers,
databases, and operating systems.

InlineCodeUserInput

InlineCode

InlineCodeVariable
InlineCodeUserInputVariable

WroxPro.030912.indd 1018

3/14/12 12:25 PM

GlossaryTerm and GlossaryDefinition should


be typed as two separate lines in manuscript

Glossary

GlossaryTitle

GlossaryTerm

GlossaryDefinition

Apache Cocoon An open source XML publishing system developed under the banner of the
Apache Software Foundation.
Attribute Metadata on an XML tag that provides additional information.
BizTalk An XML-based framework from the Microsoft Corporation that enables communications
and integration of business applications.
BPMN Business Process Modeling Notation.
BPMS Business process management systems.
BPR Business process reengineering.
CDATA Character DATA, which is not interpreted or parsed.
CMS Content management system.
COM Component Object Model.
Comment Characters included between the comment delimiters <!-- and --> that are not considered
part of the documents character content.
CORBA Common Object Request Broker Architecture.
DCOM Distributed Component Object Model.
Declaration If present, this is the first line within an XML file, which essentially lets parsers, tools,
and readers know that the file contains XML.
DOM Document Object Model.
DTD Document type definition; a file that contains element and attribute definitions.
ebXML Electronic Business using Extensible Markup Language.
Elements The structural units represented by the starting and ending tags that make up XML files.
Encoding The manner in which the abstract characters of a coded character set, such as
Unicode, are converted into an integer code representation suitable for storage, transmission, and
manipulation.
Entity An item that can be included in an XML metadata document by referring to it by a representative name.

WroxPro.030912.indd 1019

3/14/12 12:25 PM

1020

GLossary

FOFormating Objects.
DOM Document Object Model.
DTD Document type definition; a file that contains element and attribute definitions.
ebXML Electronic Business using Extensible Markup Language.
Elements The structural units represented by the starting and ending tags that make up XML files.
Encoding The manner in which the abstract characters of a coded character set, such as
Unicode, are converted into an integer code representation suitable for storage, transmission, and
manipulation.
Entity An item that can be included in an XML representation document by referring to it by a representative name.
ETL Extract, Transform, and Load.
FOFormating Objects.
Markup Logical delimiters of a document, consisting of start tags, end tags, empty element tags,
entity references, character references, comments, CDATA section delimiters, document type declarations, processing instructions, XML declarations, text declarations, and white space outside of the
document.
Parameter Entity A distinct type of entity that is used to modify the structures of a DTD.
PCDATA Parsed Character Data, which is parsed and uses XML syntax.
Pipeline A chain of application components that allows processing data in stages.
Processing Instruction Markup used to convey information directly to an application, without
being part of the documents character data.
Prologue The optional XML declaration, document type declaration, and any comments, processing instructions, or spaces that occur at the very beginning of an XML document.
RMI Remote Method Invocation.
RosettaNet An organization that defines standards for business processes such as supply chain and
distribution management.
SAX Simple API for XML.
SGML Standard Generalized Markup Language, somewhat related to XML and HTML.
SOAService-Oriented Architecture.
SOAP Simple Object Access Protocol.
Tag The markup delimiters, element name, and (for a start tag) the attributes, demarcating the start
and end of an element instance within a document. In XML an element is expressed either as a paired
start tag and end tag, or as a single empty element tag. Contrast with element, which encompasses
the entire logical structure.

WroxPro.030912.indd 1020

3/14/12 12:25 PM

If you need to tighten or lengthen the Index,


suggested range is from 7/9 to 10/12, add
additional space above/below if needed.
You can also go to a 3-column format.

Index

IndexTitle

IndexLetter
Index1

nesting XML output from a DataSet


or comma, 228230
& (ampersand) symbol, 8
.NET Framework, 42, 56
(apostrophe) symbol, 8
overview, 214
@ (at) expression, 160
ReadXml method, 214
// (backslash, double) expression, 160
string from a DataSet, getting XML as,
/ (backslash) expression, 160
227228
[ ] (brackets) expression, 160
transforming DataSet to XML, 222230
> (greater than) symbol, 8
XML data type columns and, 303316
< (less than) symbol, 8
XmlDataDocument class, 235241
.. (period, double) expression, 160
XmlReadMode enumeration, 215
. (period) expression, 160
XmlWriteMode enumeration, 222
| (pipe) expression, 160
XPathNavigator class and XmlData
(quotation) symbol, 8
Document relationship between, 242243
advanced operations, 207209
advanced serialization
A
collections, serializing, 392394
Actor property, 427, 431
namespaces used to generate qualified
Index2
Add method, 108
names, 389392
AddExtensionObject method, 190
overview, 384385
AddParam method, 190
XmlAttributeOverrides object, 387
administration and management, 3537
389
ADO.NET
XmlAttributes class, 385387
DataColumn objects, controlling the
XmlSerializerNamespaces object,
rendering behavior of, 225
389392
DataSet schemas, 218222
xsd namespace declaration, removing,
DataTable, 243245
391392
DiffGram, 223225
xsi namespace declaration, removing,
executing FOR XML queries from, 290
391392
loading XML into a DataSet, 214218
advanced operations, 207209
modifying table and column names,
airline reservation system
225227
architecture of system, 336
Multiple Active Result Sets (MARS) in,
ASP.NET 2.0 script callback, 367369
323326
business processes, 336337

Symbols

Index3
1021

WroxPro.030912.indd 1021

3/14/12 12:25 PM

airline reservation system (continued) building XML Web service

airline reservation system (continued)


confirmation page implementation, 374
Access layer methods, implementation of,
343349
database design, 337342
HTML, transforming XML to, 371373
limitations, 337
login process, 352355
logout process, 360362
new user registration process, 356360
overview, 335337
search flight process, 362367
ambiguity and namespaces, 11
ampersand (&) symbol, 8
annotations used with typed DataSets, 234235
<anonymousIdentification> configuration
section, 468
AnonymousIdentificationSection class,469
App_Code subdirectory, 25
AppendChild method, 137, 164
AppendChildElement method, 164
application settings, 473474
applying a style sheet to an XML document,
179186
apostrophe () symbol, 8
/appsettingbaseurl: [url] command line
switch, 418
AppSettings property, 472
/appsettingurlkey: [key] command line
switch, 418
architecture
of airline reservation system (case study), 336
of Atlas, 280281
for configuration, 57
of ShoppingAssistant (case study), 498
499ASP.NET MMC snapin, 492
ASP.NET page, implementation of, 204207
ASP.NET 1.x way of accessing configuration
sections, 467
<asp:XmlDataSource>, 26
async pages, 446447
asynchronous invocation of Web service
async pages, 446447

from a browser using IE Web service


behavior, 448453
callService method, 448
from a client application, 443447
createUseOptions method, 448
how it works, 448450, 455457
methods, 454457
.NET client application, asynchronous
programming in, 444446
overview, 443444, 448, 454
ShoppingAssistant (case study), 530
useService method, 448
asynchronous invocation of Windows
service, 526531
at (@) expression, 160
Atlas
architecture of, 280281
features of, 281
overview, 280
retrieving data from a Web service using,
281284
AttributeCount property, 64
attributes
appending, 151
elements compared, 6
overview, 67
reading, 69, 7376
writing, 86
Attributes property, 136
AuthenticationSection class, 469
AuthorizationSection class, 469
AUTO mode, 289

B
// (backslash, double) expression, 160
/ (backslash) expression, 160
benefits of configuration system used by
ASP.NET, 58
binary serialization, 51
brackets ([ ]) expression, 160
BufferResponse property, 416
building XML Web service, 412416

1022

WroxPro.030912.indd 1022

3/14/12 12:25 PM

built-in configuration management tools diffusion networks

built-in configuration management tools


ASP.NET MMC snapin, 492
ASPNET_REGSQL tool, 495
command line tools, 495
Budzinski, 133
Burch, David, 268
Burt, Ronald S., 416
Bush, George W., 15
Business Models for Realities: The Newspapers
Industrys Video SEO Opportunity (Crowell),
364365
BuzzLogic, 366

C
Call for Help program, 279
Call Me ad, 143
calls to action, 319, 321
camcorders
defined, 449
guidelines, 281283, 282
reviews, 277278, 278
camera techniques, 262263, 263
campaign comparisons in Google Analytics, 371
Cansei De Ser Sexy band, 100
captdeaf channel, 272
captions, 272273, 272, 449
CaptionTube, 281
Caraeff, Rio, 291, 407
Carl Zeiss optics, 283
Carlson, Nicholas, 152
Carnegie Mellon University, 80
Carousel application, 299
Carr, Nicholas, 119120,
119120, 239
Carroll, Jill, 113114, 114, 431
Carrozza, J. L., 132
categories
Channels tab, 56
defined, 449
Live Search Video, 110
in titles, 98
videos, 417421, 418421
Videos tab, 52
viewer statistics, 3334, 34

Caucus Night: Barack in Ankeny video, 385


CBS channel, 192, 193
Colbert, Stephen, 15, 22
Colbert Report, 34
college partners, 417
color
brand channels, 185187, 186
channel background, 175
Computer.TV video, 278, 278
Comedian accounts, 174, 449
comedy and humorous videos, 3334
Comicless, 281
comments
brand channels, 197198
defined, 450
recent comments box, 199
on videos, 214215, 215
comments box, 197198
communication channels, 77
Community Auditions, 69
community engagement, 7879, 209
Akon, 231232
Boyle, Susan, 244246, 24424D

D
Dailymotion, 5, 7071, 70
Dancing 2006 video, 154
Darling, Jennifer, 60
Insight, 346347, 347
demonstrations, 135
Denters, Esmee, 140142, 141,
224, 423
depth of field, 450
descriptions
defined, 450
optimizing, 9798
Dickson, Tom, 398, 402
Did You Know; Shift Happens - Globalization;
Information Age (Fisch), 447448, 447
Diet Coke + Mentos video,
12, 158
diffusion networks, 8
brand channels, 197198
defined, 450
1023

WroxPro.030912.indd 1023

3/14/12 12:25 PM

You might also like