www.it-ebooks.info
www.it-ebooks.info
Beginning
ASP.NET Web Pages with WebMatrix®
FOREWORD. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv
Chapter 1
Getting Started with WebMatrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Chapter 2
Designing Web Pages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Chapter 3
Designing Websites. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Chapter 4
Programming Your Site . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Chapter 5
Adding User Interactivity. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Chapter 6
AJAX and jQuery. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Chapter 7
Packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
Chapter 8
Working with Files and Images. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Chapter 9
Debugging and Error Handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Chapter 10 Introduction to Data and Databases. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
Chapter 11
A Deeper Dive Into Data Access. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
Chapter 12
Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Chapter 13
Optimizing Your Site . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
Chapter 14
Deploying Your Site. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
Appendix
Exercise Answers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
www.it-ebooks.info
www.it-ebooks.info
Beginning
ASP.NET Web Pages with WebMatrix®
www.it-ebooks.info
www.it-ebooks.info
Beginning
ASP.NET Web Pages with WebMatrix®
Mike Brind
Imar Spaanjaars
www.it-ebooks.info
Beginning ASP.NET Web Pages with WebMatrix®
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2011 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-118-05048-4
ISBN: 978-1-118-20348-4 (ebk)
ISBN: 978-1-118-20350-7 (ebk)
ISBN: 978-1-118-20349-1 (ebk)
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 />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 and by print-on-demand. Not all content that is available
in standard print versions of this book may appear or be packaged in all book formats. If you have purchased a version
of this book that did not include media that is referenced by or accompanies a standard print version, you may request
this media by visiting . For more information about Wiley products, visit us at
www.wiley.com.
Library of Congress Control Number: 2011936929
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress 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. WebMatrix is a registered trademark of Microsoft Corporation.
All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any
product or vendor mentioned in this book.
www.it-ebooks.info
About the Authors
Mike Brind spent the first 20 years of his working life in a series of successful sales and marketing
roles, towards the end of which he was introduced to HTML and databases. A dormant inner geek
took over and Mike became very much more interested in developing websites than selling advertising space on them.
As well as on books such as those in the Wrox Beginner series, Mike became reliant on the enormous
amount of free help provided by online communities while he learned his new craft. Mike is now
one of the all-time leading contributors to the official ASP.NET forums at
and is also a moderator there.
As a result of his contributions to the ASP.NET community via the forums, and through his
technical article site at www.mikesdotnetting.com, Mike received the Microsoft Most Valuable
Professional (MVP) Award for ASP.NET in 2008, 2009, 2010, and 2011. Beginning ASP.NET Web
Pages with WebMatrix is Mike’s first book.
Mike is currently the Operations Director for ITEC Systems, a company that produces specialist
software for recruitment agencies all around the world.
Mike lives in Rochester in the UK with his wife of over 25 years, Anna. Together they have two
daughters and a grandson.
Imar Spaanjaars graduated in Leisure Management at the Leisure Management School in the
Netherlands, but he quickly changed his career path into the Internet world.
After working in the Internet business at various web agencies for thirteen years, he started up
his own company called De Vier Koeden (), a small Internet agency
specializing in consultancy and development of Internet and intranet applications with Microsoft
technologies such as ASP.NET 4. He’s also the technical director of Dynamicweb Netherlands and
Dynamicweb North America, two branches of the popular Danish CMS and eCommerce system
Dynamicweb.
Imar has written books on ASP.NET and Macromedia Dreamweaver, all published under the Wrox
brand. He is also one of the top contributors to the Wrox Community Forum at p2p.wrox.com,
where he shares his knowledge with fellow programmers.
Since 2008, Imar has been rewarded with Microsoft’s Most Valuable Professional (MVP) award for
his contributions to the ASP.NET community.
Imar lives in Utrecht, the Netherlands, with his girlfriend, Fleur. You can contact him through his
personal web site at or by email at
www.it-ebooks.info
www.it-ebooks.info
About the Technical Editor
Michael Apostol graduated from the University of Oregon with a B.S. in Economics. He started
his career working for Microsoft Corporation in Market Development. Michael has worked in both
software development and information technology as an I.T. manager, programmer, and consultant for numerous companies in the Western United States in addition to a few trips to Europe as a
software instructor. Presently, he is employed as a contractor writing SQL Server TSQL code for a
company in Hawaii. He has thoroughly enjoyed his work as a technical editor with his last project
being: Beginning Microsoft ASP.NET 4.0 by Imar Spaanjaars (2010, Wiley Publishing, Inc.). In his free
time, Michael tries to get as much time possible with his adopted seven year old Ethiopian son, Geremu,
and spouse, Melissa, outside in the sunshine.
www.it-ebooks.info
www.it-ebooks.info
Credits
Acquisitions Editor
Production Manager
Paul Reese
Tim Tate
Project Editor
Vice President and Executive Group
Publisher
Rosanne Koneval
Richard Swadley
Technical Editor
Michael Apostol
Vice President and Executive Publisher
Neil Edde
Production Editor
Rebecca Anderson
Associate Publisher
Jim Minatel
Copy Editor
Kezia Endsley
Project Coordinator, Cover
Katie Crocker
Editorial Manager
Mary Beth Wakefield
Compositor
Craig Johnson, Happenstance Type-O-Rama
Freelancer Editorial Manager
Rosemarie Graham
Proofreader
Nancy Carrasco
Associate Director of Marketing
David Mayhew
Indexer
Johnna VanHoose Dinse
Marketing Manager
Ashley Zurcher
Cover Designer
LeAndra Young
Business Manager
Amy Knies
Cover Image
© Nikada
www.it-ebooks.info
www.it-ebooks.info
Acknowledgments
I would like to start by thanking Imar Spaanjaars, my co-author and fellow MVP, for recommending me to Wrox for this project. I am also grateful for the advice and support he has provided as the
book became reality. I would also like to thank Paul Reese for listening to Imar and taking a chance
on me.
I would also like to thank Michael J. Apostol for his contribution as Technical Editor and for Kezia
Endsley for tirelessly translating my English into English. I am particularly appreciative of the efforts
of Rosanne Koneval for her patience and diplomacy in guiding this particular author newbie through
the process of getting a book done.
Finally, I would like to thank my wife of over 25 years, Anna, for her support and understanding
throughout the project. I lost count of how many times she asked “have you finished the book yet?”
But at last, I can answer “Yes!”
www.it-ebooks.info
www.it-ebooks.info
Contents
FOREWORD
xxiii
Introduction
xxv
Chapter 1: Getting Started with WebMatrix
Introducing WebMatrix
1
2
What Is WebMatrix?
Why Should You Use WebMatrix?
How Do You Acquire WebMatrix?
Introducing the ASP.NET Web Pages Framework
How the Web Works
A Tour of WebMatrix
2
3
3
6
10
11
The Site Workspace
The Ribbon Bar
Left Pane
Workspace Selector
Right Pane
The Files Workspace
The Databases Workspace
The Reports Workspace
Common WebMatrix Templates
File Types
WebMatrix Site Templates
Anatomy of a Web Pages Application
Default Folders in a Web Pages Application
The Root Folder
12
12
12
13
13
14
14
15
15
15
17
17
17
19
Summary19
Chapter 2: Designing Web Pages
Introducing HTML
21
21
HTML Elements and Tags
22
Tag Attributes
26
HTML Entities
30
IntelliSense31
HTML533
www.it-ebooks.info
CONTENTS
Cascading Style Sheets
34
CSS Structure and Style Rules
A Type Selector Example
A Class Selector Example
An ID Selector Example
CSS Positioning and the Box Model
CSS Properties
Tips for Working with CSS
36
36
36
36
43
48
49
Summary50
The Sample Site
51
Chapter 3: Designing WebSites
53
Site Templates from Layout Pages
54
Layout Pages
Nesting Layout Pages
58
62
Reusable Content Blocks
66
IsSectionDefined70
Passing Data Between Content and Layout Pages
70
Practical Tips When Designing Layouts
74
Summary74
Chapter 4: Programming Your Site
77
The .NET Framework, C#, VB, and Razor
78
Why C#?
Where Does Razor Fit In?
Programming Fundamentals
78
78
78
Variables and Data Types
79
Naming Variables
79
Data Types
80
The var Keyword and Strong Typing
81
Working with Strings
82
Converting Strings to Other Data Types
83
Collections83
Arrays84
Other Types of Collections
84
Statements
85
Operators85
Selection Statements
87
Iteration Statements
89
xvi
www.it-ebooks.info
CONTENTS
Objects, Properties, and Methods
91
Objects91
Properties92
Methods94
Introduction to the Razor Syntax
Mixing Razor and HTML
Reusable Code
Global Values and _AppStart.cshtml
Sharing Values Across Pages with _PageStart
Reusable Functions
Reusable Custom Helpers
97
98
101
101
104
108
110
Summary111
Chapter 5: Adding User Interactivity
Creating Forms
115
115
GET versus POST
116
Creating a Form to Obtain User Input
116
Other Form Elements
120
Validating User Input
122
Server-Side or Client-Side Validation?
HTML Encoding
Persisting Values Across Postbacks
HTML Helpers
ModelState and Validation Helpers
Processing User Input
123
125
125
129
132
138
The WebMail Helper
HTML and Request Validation
138
142
Summary144
Chapter 6: AJAX and jQuery
Introduction to jQuery
How to Include jQuery in Your Pages
Content Delivery Networks
147
148
148
149
jQuery Selectors
151
Basic Selectors
Selectors with Filters
152
153
Manipulating Page Elements with jQuery
154
Applying CSS to Elements
155
css(name, value)
155
css(map)155
addClass, removeClass, and toggleClass
155
xvii
www.it-ebooks.info
CONTENTS
Event Handling
158
Effects
159
show()160
hide()160
toggle()160
fadeIn()160
fadeOut()160
fadeToggle()160
Introduction to AJAX
163
Other jQuery AJAX Methods
166
jQuery.get166
jQuery.post167
jQuery.ajax167
JavaScript Object Notation (JSON)
167
The JSON Helper
168
Introducing jQuery Plug-Ins
171
Practical Tips When Working with jQuery
175
Summary176
Chapter 7: Packages179
Introducing “Packages”
179
How to Use the Package Manager
The Web Helpers Package
180
184
Using the Twitter Helper
185
Adding Video to Your Pages
187
Flash187
Windows Media Player
187
Silverlight188
The FileUpload Helper
188
Uploading Multiple Files
192
Other Notable Helpers
193
Visual Basic Site Templates
194
BBCode Parser and Helper
194
Facebook Helper
194
PayPal Helper
194
Twitter Helper
194
Summary194
xviii
www.it-ebooks.info
CONTENTS
Chapter 8: Working with Files and Images
197
Creating and Modifying Files
197
Creating Folders
199
Copying and Moving Files and Folders
202
Other Types of Files
203
Working with Images
206
Summary216
Chapter 9: Debugging and Error Handling
219
Anatomy of an Error
219
Syntax Errors
Runtime Exceptions
220
222
Global Error Handling
Logical Errors
225
228
Using ObjectInfo to Debug Errors
The ServerInfo Helper
230
232
Using ASP.NET Tracing
233
Summary240
Chapter 10: Introduction to Data and Databases
243
What Is a Database?
SQL Server Compact
Using the Databases Workspace
243
245
245
SQL Server Compact Data Types
250
Structured Query Language
251
Reading Data
251
Filtering Data
252
Adding and Modifying Data
256
Selecting Data from Multiple Tables
258
Relationships261
Using the Database Helper
263
Summary267
Chapter 11: A Deeper Dive Into Data Access
What Is SQL Injection?
271
271
Parameters Provide Protection
Developing CRUD Forms
273
274
xix
www.it-ebooks.info
CONTENTS
Displaying Data
285
The WebGrid Helper
Some AJAX Spice
Working with Styles and Columns
Selecting Items
285
289
290
297
Summary301
Chapter 12: Security305
Membership and Roles Management
305
Membership306
Roles
306
The WebSecurity Helper
306
Creating a Registration Form
Creating a Login Form
Resetting Passwords
Locking Accounts
Managing Roles
The SimpleRoleProvider
Programmatically Applying Roles
310
317
323
323
324
325
328
Summary331
Chapter 13: Optimizing Your Site
Search Engine Optimization
333
333
SEO Reports
336
Search344
URLs and Routing
345
Web Pages Routing
346
Performance Optimization
351
Visitor Tracking
353
Summary354
Chapter 14: Deploying Your Site
Web Hosting Services
357
357
Shared Hosting
358
Dedicated Server
358
Colocation358
Finding a Hosting Company
xx
www.it-ebooks.info
358
CONTENTS
Deployment Options
Common Deployment Issues
File Paths and URLs
Other Issues
What Next?
361
369
370
371
371
Summary372
Appendix: Exercise Answers
375
Index
385
xxi
www.it-ebooks.info
www.it-ebooks.info
FOREWORD
Back in 1997, when I began my career as a professional web developer, I started working with
Classic ASP. After a brief training period in a few different programming languages such as C++
and Java, I was thrown in at the deep end and assigned to a project to build an Intranet application for a large consultancy firm in the Netherlands using Classic ASP. Despite the complexity of
the project and my lack of experience at the time, I was still able to make valuable contributions to
the code base. This was partly due to the great support I received from my more experienced colleagues, but also because of how approachable Classic ASP was. Although it’s considered outdated
now, Classic ASP had a few great features that made it the technology of choice for many developers
for a long period of time. One of the things I really liked about it was how approachable it was. You
didn’t need complex and overwhelming tools, but instead you could use a simple text editor that had
features such as color coding and multiple tabs. Deployment was also very easy: You just uploaded
the file to the server and the changes would be applied immediately. For features not supported outof-the-box (such as image scaling and uploading of files), one of my colleagues would write a DLL
in Visual Basic 6 to get the job done. I had great respect for those that possessed these skills as it
seemed pretty complicated at that time.
Then in early 2000, ASP.NET was released. It marked a radical change in web development as it
approached things from a completely different angle. Rather than having you work with the underlying technologies that make up the Web (such as HTTP , HTML, CSS and more) directly, ASP.NET
shields the developer from many of these concepts, and lets you work with a web application in a
similar way to how you write desktop applications. As a result, ASP.NET made the hard things easy
and the easy things hard. Things that used to take hours or days to develop in Classic ASP — such
as building data-driven web pages — could now be done in minutes, simply by dragging and dropping a few controls. But things that were dead-easy before — such as adding an in-line CSS class to
a table cell displaying records from a database — all of a sudden turned out to be very difficult.
I clearly recall how the first books on ASP.NET I read stated how unbelievably cool it all was,
how it was so much better than Classic ASP, and how it solved so many problems. Although these
claims have proven to be true over the past ten years, back then I already started wondering what
people would write the day a successor or competitor for ASP.NET would be released, and how all
the benefits of ASP.NET would be turned upside down as disadvantages to better promote the new
technology.
www.it-ebooks.info