Asp.net
Upcoming SlideShare
Loading in...5
×
 

Asp.net

on

  • 365 views

 

Statistics

Views

Total Views
365
Views on SlideShare
365
Embed Views
0

Actions

Likes
1
Downloads
3
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Asp.net Asp.net Document Transcript

    • ffirs.indd iiffirs.indd ii 10/8/2012 10:16:49 AM10/8/2012 10:16:49 AM
    • BEGINNING ASP.NET 4.5 FOREWORD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxi INTRODUCTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxiii CHAPTER 1 Getting Started with ASP.NET 4.5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 CHAPTER 2 Building an ASP.NET Website . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 CHAPTER 3 Designing Your W eb Pages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 CHAPTER 4 Working with ASP.NET Server Controls. . . . . . . . . . . . . . . . . . . . . . . . . . 107 CHAPTER 5 Programming Your ASP.NET Web Pages. . . . . . . . . . . . . . . . . . . . . . . . . 145 CHAPTER 6 Creating Consistent Looking Websites . . . . . . . . . . . . . . . . . . . . . . . . . . 207 CHAPTER 7 Navigation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 CHAPTER 8 User Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 CHAPTER 9 Validating User Input. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 CHAPTER 10 ASP.NET AJAX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 CHAPTER 11 jQuery. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385 CHAPTER 12 Introducing Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421 CHAPTER 13 Displaying and Updating Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453 CHAPTER 14 LINQ and the ADO.NET Entity Framework . . . . . . . . . . . . . . . . . . . . . . . 497 CHAPTER 15 Working with Data — Advanced Topics. . . . . . . . . . . . . . . . . . . . . . . . . . 553 CHAPTER 16 Security in Your ASP.NET 4.5 Website. . . . . . . . . . . . . . . . . . . . . . . . . . .603 CHAPTER 17 Personalizing Websites. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643 CHAPTER 18 Exception Handling, Debugging, and Tracing . . . . . . . . . . . . . . . . . . . . 679 CHAPTER 19 Deploying Your Website . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 729 APPENDIX A Exercise Answers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 767 APPENDIX B Configuring SQL Server 2012 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 793 INDEX. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807 ffirs.indd iffirs.indd i 10/8/2012 10:16:48 AM10/8/2012 10:16:48 AM DownloadfromWow!eBook<www.wowebook.com>
    • ffirs.indd iiffirs.indd ii 10/8/2012 10:16:49 AM10/8/2012 10:16:49 AM
    • BEGINNING ASP.NET 4.5 ffirs.indd iiiffirs.indd iii 10/8/2012 10:16:49 AM10/8/2012 10:16:49 AM
    • ffirs.indd ivffirs.indd iv 10/8/2012 10:16:49 AM10/8/2012 10:16:49 AM
    • BEGINNING ASP.NET 4.5 IN C# AND VB Imar Spaanjaars ffirs.indd vffirs.indd v 10/8/2012 10:16:49 AM10/8/2012 10:16:49 AM
    • Beginning ASP.NET 4.5: in C# and VB Published by John Wiley & Sons, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2013 by John Wiley & Sons, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN: 978-1-118-31180-6 ISBN: 978-1-118-38799-3 (ebk) ISBN: 978-1-118-33202-3 (ebk) ISBN: 978-1-118-33530-7 (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 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 pro- motional 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 pub- lisher 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 publishes in a variety of print and electronic formats and by print-on-demand. Some material included with stan- dard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://book- support.wiley.com. For more information about Wiley products, visit www.wiley.com. Library of Congress Control Number: 2012944686 Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trade- marks 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. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book. ffirs.indd viffirs.indd vi 10/8/2012 10:16:52 AM10/8/2012 10:16:52 AM
    • —To Niek ffirs.indd viiffirs.indd vii 10/8/2012 10:16:52 AM10/8/2012 10:16:52 AM
    • ffirs.indd viiiffirs.indd viii 10/8/2012 10:16:52 AM10/8/2012 10:16:52 AM
    • ABOUT THE AUTHOR IMAR SPAANJAARS graduated in Leisure Management at the Leisure Management School in the Netherlands, but he quickly changed his career path to the Internet world. After working in the Internet business at various web agencies for over twelve years, he now runs his own company called De Vier Koeden (http://devierkoeden.com), a small Internet agency special- izing in consultancy and development of Internet and intranet applications with Microsoft technolo- gies such as ASP.NET 4.5. 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. Imar has received Microsoft’s Most Valuable Professional (MVP) award each year since 2008 for his contributions to the ASP.NET community. In early 2012, Imar joined the ASPInsiders, a small group of international professionals that provide feedback and direction on new features for future versions of ASP.NET. Imar lives in Utrecht, the Netherlands, with his girlfriend Fleur and his son Niek. You can contact him through his personal web site at http://imar.spaanjaars.com or by e-mail at imar@spaanjaars.com. ffirs.indd ixffirs.indd ix 10/8/2012 10:16:52 AM10/8/2012 10:16:52 AM
    • ffirs.indd xffirs.indd x 10/8/2012 10:16:52 AM10/8/2012 10:16:52 AM
    • CREDITS Acquisitions Editor Mary James Project Editor Brian Herrmann Technical Editor Damien Foggon Production Editor Kathleen Wisor Copy Editor Kim Cofer Editorial Manager Mary Beth Wakefield Freelancer Editorial Manager Rosemarie Graham Associate Director of Marketing David Mayhew Marketing Manager Ashley Zurcher Business Manager Amy Knies Production Manager Tim Tate Vice President and Executive Group Publisher Richard Swadley Vice President and Executive Publisher Neil Edde Associate Publisher Jim Minatel Project Coordinator, Cover Katie Crocker Proofreader Word One, New York Indexer Jack Lewis Cover Designer Ryan Sneed Cover Image © Nevin Giesbrecht / iStockPhoto ffirs.indd xiffirs.indd xi 10/8/2012 10:16:52 AM10/8/2012 10:16:52 AM
    • ffirs.indd xiiffirs.indd xii 10/8/2012 10:16:52 AM10/8/2012 10:16:52 AM
    • ACKNOWLEDGMENTS ALTHOUGH THE JUMP IN VERSION NUMBER by only 0.5 seems to suggest that there’s not much new in ASP.NET 4.5 or Visual Studio 2012, you’d be surprised at the number of changes—small and large—that made their way into these products. I spent the past couple of months working on updating this book from the .NET 4 release to the new .NET 4.5 release. I discovered new features and functionality every day. Some of those changes are really small, but could mean a boost in pro- ductivity on a day-to-day basis. Others are much bigger and affect the way you built or deploy your web sites. I tried to incorporate as many of the new features found in ASP.NET and Visual Studio as long as they make sense for you, someone with no or limited experience with ASP.NET. I have also made a lot of changes to the book based on reader feedback. Just as with the previous versions of the book, I went over all the errata that have been submitted as well as over the hundreds of forum posts that were made, identifying areas in the book that readers had difficulties with, and finding ways to improve it. If you have the previous edition and posted a question in the Wrox forums: thanks for your valuable feedback; you’ve really helped to make this book better. Besides my readers, I owe a lot to other people who helped me write this book. First of all, a big thanks goes out to Brian Herrmann and Kim Cofer for their editorial work. Once again, it was a pleasure to work with you! I also want to thank Damien Foggon for his many useful suggestions he provided as a technical editor. All of you really helped shape this book. Many thanks also to the people from Wrox for their support and contributions to this book. Another person I owe a lot to is my friend Anne Ward from Blue Violet, a UK-based web and graphic design company. Anne has done most of the new designs used in this book and I highly appreciate her input. Thanks again, Anne! The concert pictures you see in this book come from Nigel D. Nudds, who kindly let me use pictures from his collection. Finally, I would like to thank my lovely girlfriend Fleur for her support during this project. With her help, writing a book with our newborn son Niek around wasn’t as hard as I expected it to be. ffirs.indd xiiiffirs.indd xiii 10/8/2012 10:16:52 AM10/8/2012 10:16:52 AM DownloadfromWow!eBook<www.wowebook.com>
    • ffirs.indd xivffirs.indd xiv 10/8/2012 10:16:52 AM10/8/2012 10:16:52 AM
    • CONTENTS FOREWORD xxxi INTRODUCTION xxxiii CHAPTER 1: GETTING STARTED WITH ASP.NET 4.5 1 Microsoft Visual Studio Express for Web 2 Getting Visual Studio 3 Installing Visual Studio Express (VSEW) 3 Creating Your First ASP.NET 4.5 Website 5 An Introduction to ASP.NET 4.5 10 Understanding HTML 11 HTML Elements and Tags 11 HTML Attributes 14 HTML Comments 14 The Rules of HTML5 14 A First Look at ASP.NET Markup 16 A Tour of the IDE 16 The Main Development Area 17 Choosing Your Development Profile 17 The Main Menu 18 The Toolbar Area 18 The Toolbox 18 The Solution Explorer 18 The Database Explorer 19 The Properties Grid 19 The Document Window 19 The Start Page 20 Informational Windows 22 The Error List 22 The Output Window 22 The Find Results Window 23 ftoc.indd xvftoc.indd xv 10/8/2012 10:17:57 AM10/8/2012 10:17:57 AM
    • xvi CONTENTS Customizing the IDE 23 Rearranging Windows 23 Modifying the Toolbox 24 Customizing the Document Window 26 Customizing Toolbars 27 Enabling and Disabling Toolbars 27 Editing Existing Toolbars 27 Creating Your Own Toolbars 27 Customizing Keyboard Shortcuts 27 Resetting Your Changes 28 Resetting the Window Layout 28 Resetting the Toolbox 28 Resetting All Settings 28 The Sample Application 28 Practical Tips on Visual Studio 30 Summary 31 CHAPTER 2: BUILDING AN ASP.NET WEBSITE 33 Creating Websites with Visual Studio 2012 34 Different Project Types 34 Web Application Projects 34 Web Site Projects 34 Choosing between Web Site Projects and Web Application Projects 35 Choosing the Right Website Template 35 ASP.NET Web Forms Site 36 ASP.NET Web Site (Razor v1 / Razor v2) 36 ASP.NET Empty Web Site 36 ASP.NET Dynamic Data Entities Web Site 36 WCF Service 36 Creating and Opening a New Website 37 Creating New Websites 37 Opening Existing Websites 39 ftoc.indd xviftoc.indd xvi 10/8/2012 10:17:58 AM10/8/2012 10:17:58 AM
    • xvii CONTENTS Working with Files in Your Website 40 The Many File Types of an ASP.NET 4.5 Website 41 Web Files 41 Code Files 43 Data Files 44 Adding Existing Files 44 Organizing Your Site 46 Special File Types 47 Working with Web Forms 47 The Different Views on Web Forms 47 Choosing between Code Behind and Pages with Inline Code 49 Adding Markup to Your Page 54 Inserting and Formatting Text 54 Adding Tables and Other Markup 57 Connecting Pages 60 Practical Tips on Working with Web Forms 62 Summary 63 CHAPTER 3: DESIGNING YOUR WEB PAGES 65 Why Do You Need CSS? 66 Problems of HTML Formatting 66 How CSS Fixes Formatting Problems 67 An Introduction to CSS 67 CSS — The Language 72 The Style Sheet 72 Selectors 73 Properties 75 Values 76 Using Shorthand 77 The CSS Box Model 78 Adding CSS to Your Pages 85 Choosing among External, Embedded, and Inline Style Sheets 86 ftoc.indd xviiftoc.indd xvii 10/8/2012 10:17:58 AM10/8/2012 10:17:58 AM
    • xviii CONTENTS Working with CSS in Visual Studio 87 Using the CSS Editor 88 Creating Embedded and Inline Style Sheets 93 Applying Styles 98 Managing Styles 100 Practical Tips on Working with CSS 102 Summary 103 CHAPTER 4: WORKING WITH ASP.NET SERVER CONTROLS 107 Introduction to Server Controls 108 A Closer Look at ASP.NET Server Controls 112 Defining Controls in Your Pages 112 Common Properties for All Controls 113 Types of Controls 116 Standard Controls 116 Simple Controls 116 List Controls 117 Container Controls 123 Other Standard Controls 130 HTML Controls 132 How to Choose between Standard and HTML Controls 132 Data Controls 132 Validation Controls 133 Navigation Controls 133 Login Controls 133 Ajax Extensions 133 WebParts 133 Dynamic Data 134 The ASP.NET State Engine 134 What Is State and Why Is It Important? 134 How the State Engine Works 135 ftoc.indd xviiiftoc.indd xviii 10/8/2012 10:17:58 AM10/8/2012 10:17:58 AM
    • xix CONTENTS Not All Controls Rely on View State 139 A Note about View State and Performance 140 Practical Tips on Working with Controls 141 Summary 142 CHAPTER 5: PROGRAMMING YOUR ASP.NET WEB PAGES 145 Introduction to Programming 146 Data Types and Variables 147 Converting and Casting Data Types 150 Using Arrays and Collections 153 Defining and Working with Arrays 153 Defining and Working with Collections 154 An Introduction to Generics 156 Statements 157 Operators 158 Assignment Operators 158 Arithmetic Operators 158 Comparison Operators 161 Concatenation Operators 163 Logical Operators 164 Making Decisions 166 If, If Else, and ElseIf Constructs 166 Select Case/switch Constructs 168 Loops 173 The For Loop 173 The For Each/foreach Loop 175 The While Loop 175 Exiting Loops Prematurely 176 Organizing Code 177 Methods: Functions and Subroutines 177 The App_Code Folder 180 Organizing Code with Namespaces 184 ftoc.indd xixftoc.indd xix 10/8/2012 10:17:58 AM10/8/2012 10:17:58 AM
    • xx CONTENTS Writing Comments 186 Commenting Code Inline 186 Writing XML Comments 187 Object Orientation Basics 189 Important OO Terminology 189 Objects 189 Classes 190 Fields 190 Properties 191 Methods 194 Constructors 195 Inheritance 197 Access Modifiers 200 Events 201 Practical Tips on Programming 202 Summary 203 CHAPTER 6: CREATING CONSISTENT LOOKING WEBSITES 207 Consistent Page Layout with Master Pages 208 Creating Master Pages 210 Creating Content Pages 212 A Closer Look at Master Pages 215 Nesting Master Pages 216 Master Page Caveats 217 Using a Centralized Base Page 218 An Introduction to the ASP.NET Page Life Cycle 219 Implementing the Base Page 221 Creating Reusable Page Templates 225 Themes 229 Different Types of Themes 230 Choosing Between Theme and StyleSheetTheme 230 Applying Themes 230 Extending Themes 235 Dynamically Switching Themes 238 ftoc.indd xxftoc.indd xx 10/8/2012 10:17:58 AM10/8/2012 10:17:58 AM
    • xxi CONTENTS Skins 245 Creating a Skin File 246 Named Skins 248 Disable Theming for Specific Controls 249 Practical Tips on Creating Consistent Pages 249 Summary 250 CHAPTER 7: NAVIGATION 253 Different Ways to Move Around Your Site 254 Understanding Absolute and Relative URLs 254 Relative URLs 255 Absolute URLs 256 Understanding Default Documents 257 Using the Navigation Controls 257 Architecture of the Navigation Controls 258 Examining the Web.sitemap File 258 Key Elements of the Web.sitemap File 259 Using the Menu Control 261 Using the Rendering Mode 262 Creating a Basic Version of the Menu Control 262 Styling the Menu Control 265 Using the TreeView Control 270 Using the SiteMapPath Control 274 Programmatic Redirection 276 Programmatically Redirecting the Client to a Different Page 276 Server-Side Redirects 279 Practical Tips on Navigation 281 Summary 282 CHAPTER 8: USER CONTROLS 285 Introduction to User Controls 286 Creating User Controls 287 Adding User Controls to a Content Page or Master Page 290 Sitewide Registration of User Controls 293 ftoc.indd xxiftoc.indd xxi 10/8/2012 10:17:58 AM10/8/2012 10:17:58 AM
    • xxii CONTENTS User Control Caveats 295 Understanding and Managing Client IDs 295 Introducing ClientIDMode 296 Adding Logic to Your User Controls 296 Creating Your Own Data Types for Properties 297 Implementing View State Properties 302 View State Considerations 308 Practical Tips on User Controls 308 Summary 309 CHAPTER 9: VALIDATING USER INPUT 311 Gathering Data from the User 312 Validating User Input in Web Forms 313 The ASP.NET Validation Controls 313 A Warning on Client-Side Validation 314 Using the Validation Controls 314 Using the HTML5 Data Types 317 The Standard Validation Controls 320 The CustomValidator and ValidationSummary Controls 327 Understanding Request Validation 332 Processing Data at the Server 334 Sending E-mail from Your Website 334 Configuring Your Website for Sending E-mail 334 Creating E-mail Messages 336 Reading from Text Files 340 Practical Tips on Validating Data 345 Summary 346 CHAPTER 10: ASP.NET AJAX 349 Introducing Ajax 350 Using ASP.NET AJAX in Your Projects 351 Creating Flicker-Free Pages 352 The UpdatePanel Control 352 A Closer Look at the UpdatePanel 355 The ScriptManager Control 356 ftoc.indd xxiiftoc.indd xxii 10/8/2012 10:17:58 AM10/8/2012 10:17:58 AM
    • xxiii CONTENTS Providing Feedback to Users 358 The UpdateProgress Control 358 The Timer Control 362 Using Web Services and Page Methods in Ajax Websites 363 What Are Web Services? 364 Introducing WCF 364 Calling Services from Client-Side Code 365 Exchanging Complex Objects with WCF 366 Creating Web Services 369 Configuring the ScriptManager 372 Introducing Page Methods 378 Practical Ajax Tips 381 Summary 382 CHAPTER 11: JQUERY 385 An Introduction to jQuery 386 Introducing NuGet 387 Using the Manage NuGet Packages Dialog Box 387 Using the Package Manager Console 389 Choosing the Location for Your jQuery Reference 391 Different Ways to Include the jQuery Library 392 jQuery Syntax 395 jQuery Core 396 Selecting Items Using jQuery 397 Basic Selectors 397 Basic Filters 400 Advanced Filters 402 Modifying the DOM with jQuery 404 CSS Methods 404 css(name, value) 404 css(name) 404 css(properties) 404 addClass, removeClass, and toggleClass 404 attr(attributeName) 405 attr(attributeName, value) 405 ftoc.indd xxiiiftoc.indd xxiii 10/8/2012 10:17:58 AM10/8/2012 10:17:58 AM
    • xxiv CONTENTS Handling Events 405 Miscellaneous jQuery Functionality 407 Common Mistakes When Working with jQuery 408 Your ID Selectors Don’t Work 408 Your ID Selectors Don’t Work, Even with a Hash Symbol 408 None of Your Code Seems to Run 408 Effects with jQuery 408 jQuery and Validation 414 Practical Tips on jQuery 418 Summary 418 CHAPTER 12: INTRODUCTION TO DATABASES 421 What Is a Database? 422 Different Kinds of Relational Databases 423 Installing SQL Server 2012 Express 424 Using SQL to Work with Database Data 425 Retrieving and Manipulating Data with SQL 428 Reading Data 428 Selecting Data 428 Filtering Data 429 Ordering Data 430 Joining Data 434 Creating Data 437 Updating Data 438 Deleting Data 438 Creating Your Own Tables 441 Data Types in SQL Server 441 Understanding Primary Keys and Identities 442 Creating Relationships Between Tables 446 Practical Database Tips 450 Summary 451 CHAPTER 13: DISPLAYING AND UPDATING DATA 453 Data Controls 453 Data-Bound Controls 454 List Controls 454 ftoc.indd xxivftoc.indd xxiv 10/8/2012 10:17:59 AM10/8/2012 10:17:59 AM
    • xxv CONTENTS Single Item Controls 455 Paging Controls 455 Data Source Controls 456 Other Data Controls 456 Data Source and Data-bound Controls Working Together 456 Displaying and Editing Data with GridView 456 Inserting Data with DetailsView 463 Storing Your Connection Strings in Web.config 464 Filtering Data 466 Customizing the Appearance of the Data Controls 472 Configuring Columns or Fields of Data-bound Controls 473 Updating and Inserting Data 479 Using DetailsView to Insert and Update Data 479 Practical Tips for Displaying and Updating Data 493 Summary 494 CHAPTER 14: LINQ AND THE ADO.NET ENTITY FRAMEWORK 497 Introducing LINQ 498 LINQ to Objects 499 LINQ to XML 499 LINQ to ADO.NET 499 Introducing the ADO.NET Entity Framework 500 Mapping Your Data Model to an Object Model 501 Introducing Query Syntax 507 Standard Query Operators 507 Select 508 From 508 Order By 508 Where 509 Sum, Min, Max, Average, and Count 509 Take, Skip, TakeWhile, and SkipWhile 509 Single and SingleOrDefault 510 First, FirstOrDefault, Last, and LastOrDefault 511 Shaping Data with Anonymous Types 511 ftoc.indd xxvftoc.indd xxv 10/8/2012 10:17:59 AM10/8/2012 10:17:59 AM
    • xxvi CONTENTS Using Server Controls with LINQ Queries 517 Using Data Controls with the Entity Framework 517 Introducing the EntityDataSource Control 517 Introducing the ListView Control 524 Using Strongly Typed Data-Bound Controls 536 Introducing the DataPager Control 544 A Few Notes about Performance 549 Practical LINQ and ADO.NET Entity Framework Tips 550 Summary 550 CHAPTER 15: WORKING WITH DATA — ADVANCED TOPICS 553 Formatting Your Controls Using Styles 554 An Introduction to Styles 555 Combining Styles, Themes, and Skins 559 Handling Events 563 The ASP.NET Page and Control Life Cycles Revisited 564 The ASP.NET Page Life Cycle and Events in Data Controls 569 Handling Errors that Occur in the Data Source Controls 574 Hand-Coding Data Access Code 579 Caching 589 Common Pitfalls with Caching Data 589 Avoiding Stale Data 590 Don’t Rely on the Data Being There 590 Different Ways to Cache Data in ASP.NET Web Applications 590 Output Caching 591 Caching with Data Source Controls 592 Programmatic Caching 593 Practical Data Tips 600 Summary 600 CHAPTER 16: SECURITY IN YOUR ASP.NET 4.5 WEBSITE 603 Introducing Security 604 Identity: Who Are You? 604 ftoc.indd xxviftoc.indd xxvi 10/8/2012 10:17:59 AM10/8/2012 10:17:59 AM DownloadfromWow!eBook<www.wowebook.com>
    • xxvii CONTENTS Authentication: How Can You Prove Who You Are? 604 Authorization: What Are You Allowed to Do? 605 An Introduction to the ASP.NET Application Services 605 Introducing the Login Controls 607 The Login Controls 612 Login 612 LoginView 614 LoginStatus 615 LoginName 615 CreateUserWizard 617 PasswordRecovery 621 ChangePassword 621 Configuring Your Web Application 624 The Role Manager 627 The Role Manager Configuration 627 Managing Users with the WSAT 628 Configuring the Web Application to Work with Roles 632 Programmatically Checking Roles 636 Practical Security Tips 640 Summary 641 CHAPTER 17: PERSONALIZING WEBSITES 643 Understanding Profile 644 Configuring the Profile 645 Creating Simple Profile Properties 645 Creating Profile Groups 646 Using Non-Standard Data Types 647 Using the Profile 652 Other Ways of Dealing with Profile 670 Anonymous Identification 670 Cleaning Up Old Anonymous Profiles 671 Looking at Other Users’ Profiles 672 Practical Personalization Tips 675 Summary 675 ftoc.indd xxviiftoc.indd xxvii 10/8/2012 10:17:59 AM10/8/2012 10:17:59 AM
    • xxviii CONTENTS CHAPTER 18: EXCEPTION HANDLING, DEBUGGING, AND TRACING 679 Exception Handling 680 Different Types of Errors 680 Syntax Errors 680 Logic Errors 681 Runtime Errors 682 Catching and Handling Exceptions 682 Global Error Handling and Custom Error Pages 690 The Basics of Debugging 698 Tools Support for Debugging 701 Moving Around in Debugged Code 701 Debugging Windows 702 Watching Variables 702 Other Windows 704 Debugging Client-Side Script 709 Debugging with the Page Inspector 712 Introducing the Page Inspector 712 Using the Page Inspector 713 Tracing Your ASP.NET Web Pages 718 Using the Standard Tracing Capabilities 719 Tracing with Individual Pages 719 Tracing the Entire Website 720 Adding Your Own Information to the Trace 723 Tracing and Performance 725 A Security Warning 725 Practical Debugging Tips 725 Summary 726 CHAPTER 19: DEPLOYING YOUR WEBSITE 729 Preparing Your Website for Deployment 730 Avoiding Hard-Coded Settings 730 The Web.config File 731 Expression Syntax 731 The WebConfigurationManager Class 732 ftoc.indd xxviiiftoc.indd xxviii 10/8/2012 10:17:59 AM10/8/2012 10:17:59 AM
    • xxix CONTENTS Introducing Bundling and Minification 738 Copying Your Website 741 Creating a Simple Copy of Your Website 742 Publishing Your Website 745 Running Your Site under IIS 746 Installing and Configuring the Web Server 746 Making Sure IIS Is Installed 747 Installing and Configuring ASP.NET 748 Understanding Security in IIS 753 NTFS Settings for Planet Wrox 754 Troubleshooting Web Server Errors 757 Moving Data to a Remote Server 759 Exporting Your Data to a File 760 Re-Creating the Database 762 The Deployment Checklist 763 What’s Next 764 Summary 765 APPENDIX A: EXERCISE ANSWERS 767 APPENDIX B: CONFIGURING SQL SERVER 2012 793 Configuring SQL Server 2012 793 Terminology and Concepts 793 SQL Server Authentication 794 Windows Authentication 794 Choosing between Windows and Server Authentication 795 Using SQL Server Management Studio 795 Enabling Remote Connections in SQL Server 795 Attaching Databases to SQL Server 796 Connecting Your Application to SQL Server 2012 798 Scenario 1 — Using SQL Server Authentication 799 Scenario 2 — Using Windows Authentication with IIS and the Database on the Same Machine 803 Configuring Application Services 805 INDEX 807 ftoc.indd xxixftoc.indd xxix 10/8/2012 10:17:59 AM10/8/2012 10:17:59 AM
    • flast.indd xxxflast.indd xxx 10/8/2012 10:17:22 AM10/8/2012 10:17:22 AM
    • FOREWORD THE ADOPTION RATE OF EMERGING STANDARDS like HTML5 and CSS3 grows every day. Things that were only possible on thick client apps are becoming a reality on the web. With browsers get- ting faster and better each day, with more common tasks becoming available as reusable libraries, and with open sourcing of nearly all big web frameworks, our world wide web is a happening place. Penetration of mobile devices and the varied mobile app development technologies are making devel- opers further consider the open and accessible web as their medium of expression. During this time, client side libraries like jQuery and jQuery mobile, and server-side technologies like ASP.NET are making typically difficult and cumbersome tasks approachable. On top of all this, free tools like Visual Web Developer 2012 make web development more fun than ever before. It is indeed a joy to be a web developer these days, and it is nice to see this book come out and make becoming web developer approachable for everyone. Imar Spaanjaars, the author of this book, has been a Microsoft MVP in ASP.NET since 2008, and this time around we also had him join the ASP.NET Insiders group, in which we bounce feature ideas and pre-release products even before they ever get to public beta. Imar has been a constant source of feedback for the team during the development process and I am certain he will continue to be so even in the future. In Beginning ASP.NET 4.5: in C# and VB he starts slow, goes deep, builds concepts, and covers the latest features of both ASP.NET 4.5 and Visual Studio 2012. Whether you are just starting web development or upgrading to ASP.NET 4.5, this book is certainly worth adding to your toolbox. It is my pleasure to know Imar, and I want to thank him for his contribution to our community. His insights and thoughts were invaluable the product team behind ASP.NET and Visual Studio. I hope his insights will help you too. Vishal R. Joshi Principal Program Manager Lead Windows Azure Group, Microsoft Corporation http://vishalrjoshi.com flast.indd xxxiflast.indd xxxi 10/8/2012 10:17:23 AM10/8/2012 10:17:23 AM
    • flast.indd xxxiiflast.indd xxxii 10/8/2012 10:17:23 AM10/8/2012 10:17:23 AM
    • INTRODUCTION TO BUILD EFFECTIVE AND ATTRACTIVE database-driven websites, you need two things: a solid and fast framework to run your web pages on and a rich and extensive environment to create and pro- gram these web pages. With ASP.NET 4.5 and Visual Studio 2012 you get both. Together they form the platform to create dynamic and interactive websites. ASP.NET 4.5 builds on top of its popular predecessors ASP.NET 2.0, 3.5, and 4.0. While main- taining backward compatibility with sites built using these older versions, ASP.NET 4.5 and Visual Studio 2012 introduce new, exciting features and bring many smaller, but much needed changes to the framework and development tools. With each new release of Visual Studio since Visual Studio 2003, I am surprised by the sheer amount of new functionality and changes Microsoft has been able to put in the product. Visual Studio 2012 is no exception. If you’re familiar with earlier versions, you’ll notice the new design as a big change. The UI of Visual Studio has been updated to the Windows 8 design look and feel to bet- ter align with other products from Microsoft. You’ll also find many changes—small and large—in both the ASP.NET Framework and Visual Studio. Some of these changes are the improved CSS and JavaScript editors (discussed in Chapter 3 and Chapter 10, respectively), the strongly typed data-bound controls (discussed in Chapter 14), the inclusion of NuGet, discussed in Chapter 11, and the introduction of bundling and minification, discussed in Chapter 19. My favorite new feature is probably the Page Inspector that helps you debug client-side as well as server-side code at the same time. I discuss the Page Inspector in Chapter 18. If you’re familiar with earlier versions of ASP.NET, you’ll be happy to find many small gems in the new version of the framework that will make your life as a developer easier. I mention and discuss these new features throughout this book where appropriate. For a complete list of all new features in ASP.NET, check out the following white paper at the official ASP.NET website: http://www.asp.net/vnext/overview/whitepapers/whats-new If this link no longer works by the time you read this book, search www.asp.net for “What’s new in ASP.NET 4.5.” Probably the best thing about Visual Studio Express 2012 for Web is its price: it’s available for free. This makes Visual Studio and ASP.NET probably the most attractive and compelling web develop- ment technologies available today. flast.indd xxxiiiflast.indd xxxiii 10/8/2012 10:17:23 AM10/8/2012 10:17:23 AM
    • xxxiv INTRODUCTION WHO THIS BOOK IS FOR This book is for anyone who wants to learn how to build rich and interactive websites that run on the Microsoft platform. With the knowledge you gain from this book, you create a great foundation to build any type of website, ranging from simple hobby-related websites to sites you may be creat- ing for commercial purposes. Anyone new to web programming should be able to follow along because no prior background in web development is assumed, although it helps if you do have a basic understanding of HTML and the web in general. The book starts at the very beginning of web development by showing you how to obtain and install Visual Studio. The chapters that follow gradually introduce you to new tech- nologies, building on top of the knowledge gained in the previous chapters. Do you have a strong preference for Visual Basic over C# or the other way around? Or do you think both languages are equally cool? Or maybe you haven’t made up your mind yet and want to learn both languages? Either way, you’ll like this book because all code examples are presented in both languages! Even if you have some experience with prior versions of ASP.NET, you may gain a lot from this book. Although many concepts from previous versions are brought forward into ASP.NET 4.5, you’ll discover there’s a lot of new stuff to be found in this book, including the strongly typed data controls, smarter code editors, new debugging facilities, and more. WHAT THIS BOOK COVERS This book teaches you how to create a feature-rich, data-driven, and interactive website called Planet Wrox. Although this is quite a mouthful, you’ll find that with Visual Studio 2012, develop- ing such a website isn’t as hard as it seems. You’ll see the entire process of building a website, from installing Visual Studio in Chapter 1 all the way up to putting your website on a live server in Chapter 19. The book is divided into 19 chapters, each dealing with a specific subject: ‰ Chapter 1, “Getting Started with ASP.NET 4.5.” In this chapter you see how to obtain and install Visual Studio Express 2012 for Web, the free version of Visual Studio 2012 to build ASP.NET websites. You are also introduced to HTML5, the latest standard for defining web pages. The chapter closes with an overview of the customization options that Visual Studio gives you. ‰ Chapter 2, “Building an ASP.NET Website.” This chapter shows you how to create a new website and how to add new items like pages to it. Besides learning how to create a well- structured site, you also see how to use the numerous tools in Visual Studio to create HTML and ASP.NET pages. ‰ Chapter 3, “Designing Your Web Pages.” Visual Studio comes with a host of tools that enable you to create well-designed and attractive web pages. In this chapter, you see how to make good use of these tools. Additionally, you learn about CSS, the language that is used to format web pages. flast.indd xxxivflast.indd xxxiv 10/8/2012 10:17:24 AM10/8/2012 10:17:24 AM
    • xxxv INTRODUCTION ‰ Chapter 4, “Working with ASP.NET Server Controls.” ASP.NET Server Controls are one of the most important concepts in ASP.NET. They enable you to create complex and feature-rich websites with very little code. This chapter introduces you to the large number of server controls that are available, explains what they are used for, and shows you how to use them. ‰ Chapter 5, “Programming Your ASP.NET Web Pages.” Although the built-in CSS tools and the ASP.NET Server Controls can get you a long way in creating web pages, you are likely to use a programming language to enhance your pages. This chapter serves as an introduction to programming with a strong focus on programming web pages. Best of all: all the examples you see in this chapter (and the rest of the book) are in both Visual Basic and C#, so you can choose the language you like best. ‰ Chapter 6, “Creating Consistent-Looking Websites.” Consistency is important to give your website an attractive and professional appeal. ASP.NET helps you create consistent-looking pages through the use of master pages, which enable you to define the global look and feel of a page. Skins and themes help you to centralize the looks of controls and other visual ele- ments in your site. You also see how to create a base page that helps to centralize program- ming code that you need on all pages in your site. ‰ Chapter 7, “Navigation.” To help your visitors find their way around your site, ASP.NET comes with a number of navigation controls. These controls are used to build the navigation structure of your site. They can be connected to your site’s central site map that defines the pages in your website. You also learn how to programmatically send users from one page to another. ‰ Chapter 8, “User Controls.” User controls are reusable page fragments that can be used in multiple web pages. As such, they are great for repeating content such as menus, banners, and so on. In this chapter, you learn how to create and use user controls and enhance them with some programmatic intelligence. ‰ Chapter 9, “Validating User Input.” A large part of interactivity in your site is defined by the input of your users. This chapter shows you how to accept, validate, and process user input using ASP.NET Server Controls. Additionally, you see how to send e-mail from your ASP .NET website and how to read from text files. ‰ Chapter 10, “ASP.NET AJAX.” Microsoft ASP.NET AJAX enables you to create good- looking, flicker-free web pages that close the gap between traditional desktop applications and websites. In this chapter you learn how to use the built-in Ajax features to enhance the presence of your web pages, resulting in a smoother interaction with the website. ‰ Chapter 11, “jQuery.” jQuery is a popular, open source and cross-browser JavaScript library designed to make it easier to interact with web pages in the client’s browser. In this chapter you learn the basics of jQuery and see how to add rich visual effects and animations to your web pages. ‰ Chapter 12, “Introduction to Databases.” Understanding how to use a database is critical to building websites, because most modern websites require the use of a database. You learn the flast.indd xxxvflast.indd xxxv 10/8/2012 10:17:24 AM10/8/2012 10:17:24 AM
    • xxxvi INTRODUCTION basics of SQL, the query language that enables you to access and alter data in a database. In addition, you are introduced to the database tools found in Visual Studio that help you create and manage your SQL Server databases. ‰ Chapter 13, “Displaying and Updating Data.” Building on the knowledge you gained in Chapter 12, this chapter shows you how to use the ASP.NET data-bound and data source controls to create a rich interface that enables your users to interact with the data in the data- base that these controls target. ‰ Chapter 14, “LINQ and the ADO.NET Entity Framework.” LINQ is Microsoft’s solution for accessing objects, databases, XML, and more. The ADO.NET Entity Framework (EF) is Microsoft’s new technology for database access. This chapter shows you what LINQ is all about, how to use the visual EF designer built into Visual Studio, and how to write LINQ to Entities queries to get data in and out of your SQL Server database. You also see how to work with strongly typed data controls to make it easier to write code with fewer errors. ‰ Chapter 15, “Working with Data—Advanced Topics.” Whereas earlier chapters focus mostly on the technical foundations of working with data, this chapter looks at the same topic from a front-end perspective. You see how to change the visual appearance of your data through the use of control styles. You also see how to interact with the data-bound controls and how to speed up your website by keeping a local copy of frequently accessed data. ‰ Chapter 16, “Security in Your ASP.NET 4.5 Website.” Although presented quite late in the book, security is a first-class, important topic. This chapter shows you how to make use of the built-in ASP.NET features related to security. You learn about a number of application services that facilitate security. You also learn how to let users sign up for an account on your website, how to distinguish between anonymous and logged-on users, and how to man- age the users in your system. ‰ Chapter 17, “Personalizing Websites.” Building on the security features introduced in Chapter 16, this chapter shows you how to create personalized web pages with content tar- geted at individual users. You see how to configure and use ASP.NET Profile, which enables you to store personalized data for known and anonymous visitors. ‰ Chapter 18, “Exception Handling, Debugging, and Tracing.” You need good debugging tools to understand, improve, and fix the code you write for your ASP.NET web pages. Visual Studio ships with great debugging support that enables you to diag- nose the state of your application at run time, helping you find and fix problems before your users do. You also get a good look at the Page Inspector that has been introduced in Visual Studio 2012. ‰ Chapter 19, “Deploying Your Website.” By the end of the book, you should have a website that is ready to be shown to the world. But how exactly do you do that? What are the things you need to know and understand to put your website out in the wild? This chapter gives the answers and provides you with a good look at configuring different production systems in order to run your final website. You also see how to implement bundling and minification to improve the performance of your website. flast.indd xxxviflast.indd xxxvi 10/8/2012 10:17:24 AM10/8/2012 10:17:24 AM
    • xxxvii INTRODUCTION HOW THIS BOOK IS STRUCTURED This book takes the time to explain concepts step by step using working examples and detailed explanations. Using the famous Wrox Try It Out and How It Works sections, you are guided through a task step by step, detailing important things as you progress through the task. Each Try It Out task is followed by a detailed How It Works section that explains the steps you performed in the exercise. At the end of each chapter, you find exercises that help you test the knowledge you gained in this chapter. You can find the answers to each question in Appendix A at the end of this book. Don’t worry if you don’t know all the answers to the questions. Later chapters do not assume you followed and carried out the tasks from the exercise sections of previous chapters. Because this is a beginner’s book, I can’t go into great detail on a number of topics. For nearly every chapter in this book, you’ll find numerous other books that exclusively deal with the topic discussed. Where appropriate, I have included references to these books so you can easily decide where to go to next if you want to deepen your knowledge on a specific subject. WHAT YOU NEED TO USE THIS BOOK This book assumes you have a system that meets the following requirements: ‰ Capable of running Visual Studio. For the exact system requirements, consult the readme file that comes with the software. ‰ Running Windows 7 or Windows 8 (at least the Home Premium edition), or one of the Windows Server 2008 R2 or 2012 editions. Chapter 1 shows you how to obtain and install Visual Studio 2012, which in turn installs the Microsoft .NET Framework version 4.5 and SQL Server Express LocalDB edition; then all you need is a good operating system and the drive to read this book! CONVENTIONS To help you get the most from the text and keep track of what’s happening, a number of conventions are used throughout the book. TRY IT OUT Conventions The Try It Out is an exercise you should work through, following the text in the book. 1. They usually consist of a set of steps. 2. Each step has a number. 3. Follow the steps through with your copy of the code. 4. Then read the How It Works section to find out what’s going on. flast.indd xxxviiflast.indd xxxvii 10/8/2012 10:17:24 AM10/8/2012 10:17:24 AM
    • xxxviii INTRODUCTION How It Works After each Try It Out, the actions you carried out and the code you’ve typed in are explained in detail. NOTE Boxes like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text. COMMON MISTAKES Mistakes that are easily made while following the exer- cises are presented in a box like this. Be sure to read these carefully when you get stuck in an exercise. As for styles in the text: ‰ New terms and important words are italicized when they are introduced. ‰ Code within the text is presented like this: Request.QueryString.Get("Id") ‰ URLs that do not start with www are prefixed with http:// to make it clear it’s an Internet address. URLs within the text are presented like this: http://imar.spaanjaars.com. ‰ You’ll see many URLs that start with tinyurl.com or bit.ly, which are handy, online services to make URLs shorter (and thus easier to type). Entering a tinyurl.com or bit.ly address in your browser should take you to its final destination. ‰ Menu items that require you to click multiple submenus have a special symbol that looks like this: Í . For example: File Í New Í Folder. ‰ Code or content irrelevant to the discussion is either left out completely or replaced with ellipsis points (three dots) and a comment, like this: <tr> <td style="white-space: nowrap;"> ... Menu items go here; not shown </td> </tr> The three dots are used regardless of the programming language used in the example, so you’ll see it for C#, Visual Basic, HTML, CSS, and JavaScript. When you see it in code you’re instructed to type into the code editor, you can simply skip the three dots and any- thing that follows them on the same line. flast.indd xxxviiiflast.indd xxxviii 10/8/2012 10:17:24 AM10/8/2012 10:17:24 AM
    • xxxix INTRODUCTION ‰ Code shown for the first time, or other relevant code, is in the following format: Dim roles As New ArrayList() roles.Add("Administrators") roles.Add("ContentManagers") To put emphasis on a block of code surrounded by other code, I use a bolded font like this: <appSettings> <add key="FromAddress" value="planetwrox@example.com"/> </appSettings> The surrounding code is used to make it easier to see where the bolded code should be placed. ‰ Quite often, white space in code is irrelevant, as is mostly the case with ASP.NET markup and HTML. To fit code within the boundaries of this book, I often wrap code over multiple lines and indent the part that should have been on the previous line like this: Dim result As String = WebConfigurationManager.AppSettings.Get("FromAddress") If you’re typing this code yourself, you can put it all on one line, or use the same line breaks if you prefer. The sample code that comes with this book has the code typically on a single line. ‰ Text that appears on-screen often has Each Word Start With A Capital Letter, even though the original screen text uses a different capitalization. This is done to make the screen text stand out from the rest of the text. SOURCE CODE 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 from the book’s own page on the Wrox website at www.wrox.com/ remtitle.cgi?isbn=1118311809. If somehow this link no longer works, go to www.wrox.com and locate the book either by using the Search box or by using one of the title lists. Click the Download Code link on the book’s detail page to obtain all the source code for the book. NOTE Because many books have similar titles, you may find it easiest to search by ISBN; for this book the ISBN is 978-1-118-31180-6. You can download the full source for this book as a single file for each programming language used in the book (C# or Visual Basic). You can decompress these files with your favorite decompression tool. If you extract the source, make sure you maintain the original folder structure that is part of flast.indd xxxixflast.indd xxxix 10/8/2012 10:17:24 AM10/8/2012 10:17:24 AM
    • xl INTRODUCTION the code download. The different decompression tools use different names for this feature, but look for a feature like Use Folder Names or Maintain Directory Structure. Once you have extracted the files from the code download, you should end up with a folder called Source and a folder called Resources. Then create a new folder in the root of your C drive, call it BegASPNET, and move the Source and Resources folders into this new folder so you end up with folders like C:BegASPNET Source and C:BegASPNETResources. The Source folder contains the source for each of the 19 chapters of this book and the final version of the Planet Wrox website. The Resources folder con- tains files you need during some of the exercises in this book. If everything turned out correctly, you should end up with the structure shown in Figure I-1. FIGURE I-1 Later chapters have you create folders called Site and Release inside the same C:BegASPNET folder, giving you a folder structure similar to that in Figure I-2. flast.indd xlflast.indd xl 10/8/2012 10:17:24 AM10/8/2012 10:17:24 AM
    • xli INTRODUCTION FIGURE I-2 The Site folder contains the site as you’ll build it throughout this book, and the Release folder will contain your final version at the end of this book. Whenever you’re stuck with some examples in this book, you can take a peek in the Source folder to see how things should have ended up. If you want to run the site for a specific chapter to see how it works, be sure to open the chapter’s folder in Visual Studio as a website. So, you should open a folder such as C:BegASPNETSource Chapter 12 directly rather than opening its parent folder C:BegASPNETSource. If you want to follow along in both programming languages, create a second folder called C: BegASPNETVB or C:BegASPNETCS to hold the files for the other version. This way, the two sites can coexist without any problems. If you create a folder specifically for the C# language, don’t include the hash symbol (#) because that’s an invalid character in the pathname for a website. Sticking to this structure ensures a smooth execution of the Try It Out exercises in this book. Incorrectly mixing or nesting these folders makes it harder to carry out the exercises and may even lead to unexpected situations and errors. Whenever you run into an issue or error that is not explained in this book, ensure that your site structure is still closely related to the one presented here. ERRATA I have made 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 this book, such as a spelling mistake or a faulty piece of code, I’d 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 me provide even higher quality information. flast.indd xliflast.indd xli 10/8/2012 10:17:25 AM10/8/2012 10:17:25 AM
    • xlii INTRODUCTION To find the errata page for this book, go to www.wrox.com/remtitle.cgi?isbn=1118311809 or go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Errata link. On this page you can view all errata that has been submitted for this book and posted by Wrox editors. A complete book list including links to each book’s errata is also available at www.wrox.com/misc-pages/booklist.shtml. If you don’t spot “your” error on the book’s Errata page, go to www.wrox.com/contact/ techsupport.shtml and complete the form there to send us the error you have found. I’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in sub- sequent editions of the book. 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 e-mail you topics of interest of your choosing when new posts are made to the forums. I am a frequent visitor of the Wrox forums, and I’ll do my best to help you with any questions you may have about this book. At 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: 1. Go to p2p.wrox.com and click the Register Now link. 2. Read the terms of use and click Agree. 3. Complete the required information to join as well as any optional information you wish to provide and click Submit. 4. You will receive an e-mail with information describing how to verify your account and com- plete the joining process. You can read messages in the forums without joining P2P but in order to post your own messages, you must join (which is free). After you join, you can post new messages and respond to messages other users post. You’ll find this book’s own forum under the ASP.NET 4.5 category that is available from the homepage. You can read messages at any time on the web. If you would like to have new messages from a particu- lar forum e-mailed to you, click 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 the FAQ link on any P2P page. flast.indd xliiflast.indd xlii 10/8/2012 10:17:25 AM10/8/2012 10:17:25 AM DownloadfromWow!eBook<www.wowebook.com>
    • BEGINNING ASP.NET 4.5 flast.indd xliiiflast.indd xliii 10/8/2012 10:17:25 AM10/8/2012 10:17:25 AM
    • flast.indd xlivflast.indd xliv 10/8/2012 10:17:25 AM10/8/2012 10:17:25 AM
    • Getting Started with ASP.NET 4.5 WHAT YOU WILL LEARN IN THIS CHAPTER: ‰ How to acquire and install Visual Studio Express 2012 for Web and Visual Studio 2012 ‰ How to create your first website with Visual Studio Express 2012 ‰ How an ASP.NET page is processed by the server and sent to the browser ‰ How you can use and customize the development environment Ever since the first release of the .NET Framework 1.0 in early 2002, Microsoft has put a lot of effort and development time into ASP.NET, the part of the .NET Framework that enables you to build rich web applications. This first release meant a radical change from the older Microsoft technology to build websites called Active Server Pages (ASP), now often referred to as classic ASP. The introduction of ASP.NET 1.0 and the associated Visual Studio .NET gave developers the following benefits over classic ASP: ‰ A clean separation between presentation and code. With classic ASP, your program- ming logic was often scattered throughout the HTML of the page, making it hard to make changes to the page later. ‰ A development model that was much closer to the way desktop applications are pro- grammed. This made it easier for the many Visual Basic desktop programmers to make the switch to web applications. ‰ A feature-rich development tool (called Visual Studio .NET) that enabled developers to create and code their web applications visually. 1 c01.indd 1c01.indd 1 10/8/2012 9:39:18 AM10/8/2012 9:39:18 AM
    • 2 x CHAPTER 1 GETTING STARTED WITH ASP.NET 4.5 ‰ A choice between a number of object-oriented programming (OOP) languages, of which Visual Basic .NET and C# (pronounced as C-Sharp) are now the most popular. ‰ Access to the entire .NET Framework, which for the first time meant that web developers had a unified and easy way to access many advanced features to work with databases, files, e-mail, networking tools, and much more. Despite the many advantages of ASP.NET over the older model, using ASP.NET also meant an increase in complexity and the knowledge needed to build applications with it, making it harder for many new programmers to get started with ASP.NET. After the initial release in 2002, Microsoft released another version of the .NET Framework (called .NET 1.1) and the development IDE (called Visual Studio .NET 2003). Many people saw this as a service pack for the initial release, although it also brought a lot of new enhancements in both the framework and the development tools. In November 2005, Visual Studio 2005 and ASP.NET 2.0 were released. To the pleasant surprise of many developers around the world, Microsoft had again been able to drastically improve and expand the product, adding many features and tools that helped reduce the complexity that was introduced with ASP.NET 1.0. New wizards and smart controls made it possible to reduce the code required to build an application, decreasing the learning curve for new developers and increasing their productivity. In November 2007, Microsoft released Visual Studio 2008 and the ASP.NET 3.5 framework, fol- lowed by Visual Studio 2010 and ASP.NET 4 in March 2010. Both versions added a lot of new func- tionality, including LINQ (discussed in Chapter 14), the integration of the AJAX Framework (which you learn more about in Chapter 10), the ADO.NET Entity Framework (discussed in Chapter 14), the inclusion of jQuery (discussed in Chapter 11), and more. The current versions, Visual Studio 2012 and ASP.NET 4.5, build on top of the successful Visual Studio 2010 and ASP.NET 4 releases, leaving many of the beloved features in place while adding new features and tools in other areas. Over the next 19 chapters, you learn how to build full-featured ASP.NET websites using Visual Studio Express 2012 for Web, Microsoft’s free development tool for ASP.NET web applications, which is also part of the full Visual Studio 2012 suite. This book guides you through the process of creating a fully functional, database-driven website, starting with a bare-bones website in the next chapter, all the way down to the deployment of it to a production environment in Chapter 19. The sample site that comes with this book and all the examples are built with Visual Studio Express 2012 for Web (VSEW), so it’s important that you have it installed on your development machine. The next section shows you how to acquire and install VSEW. Once you have it up and running, you see how to create your first website, followed by an extensive tour through the many features of VSEW. MICROSOFT VISUAL STUDIO EXPRESS FOR WEB Although you could theoretically write ASP.NET web applications with Notepad or another text editor alone, you really want to install a copy of Microsoft Visual Studio (VS). VS hosts an enor- mous number of tools that will help you in rapidly creating complex ASP.NET web applications. c01.indd 2c01.indd 2 10/8/2012 9:39:21 AM10/8/2012 9:39:21 AM
    • Microsoft Visual Studio Express for Web x 3 Visual Studio comes in two flavors: as a standalone and free version called Microsoft Visual Studio Express 2012 for Web, and as part of the larger development suite called Visual Studio 2012, which is also available in different editions, each with its own price tag. With the commer- cial editions of Visual Studio, the web components are fully integrated. You just start Visual Studio 2012 and then create a Web Site Project or a Web Application Project, which in turn enables the web components of Visual Studio. Although the Express edition of Visual Studio is free, it contains all the features and tools you need to create complex and feature-rich web applications. All the examples you find in the book can be built with the free Express edition, so there’s no need to shell out big bucks for the commercial ver- sions of Visual Studio 2012 to follow along with this book. I’ll use the term Visual Studio (VS) to refer to both the commercial and free versions of Visual Studio. When talking about the free edition specifically, I’ll use the terms Express edition or Visual Studio Express 2012 (VSEW). Getting Visual Studio is easy. You can download it from the Microsoft site as discussed next. Getting Visual Studio You can get the free Visual Studio Express 2012 for Web from the Microsoft site at www.microsoft .com/express/. On the Express homepage, follow the Downloads link until you reach the page that offers the downloads for the Express products, including VSEW. From this page, you can download VSEW as a Web Install, where you download only the installer, while the remaining files are downloaded during the installation process. Make sure you choose Visual Studio Express 2012 for Web from the page, and not one of the other free Express products or one of the older editions of Visual Studio. Don’t be fooled by the file size of the Web Install download, which is just a few megabytes. The file you download is just the installer that downloads the required files over the Internet. The total download depends on your current system and will be somewhere between 180 MB and 270 MB. If you want to try out the full version of Visual Studio 2012, which also contains the web components, you can sign up for a free trial on the Microsoft site at http://msdn.microsoft.com/ vstudio. You can choose to download an ISO image that you’ll need to burn on a DVD or choose to download the Web Installer. Finally, you can download VSEW with the Microsoft Web Platform Installer (WPI) application available for download at www.microsoft.com/web/platform and at www.asp.net/downloads/. Besides VSEW, this tool also gives you easy access to many other web development–related tools and programs. The WPI is an excellent tool to get a whole bunch of web development–related programs and tools in one fell swoop. I often use it to get up and running real quick on a clean development machine. Installing Visual Studio Express (VSEW) Installing VSEW is a straightforward, although somewhat lengthy, process. Depending on your installation method, your computer, and your Internet connection speed, installing VSEW may take anywhere between 20 minutes and an hour — or even more. c01.indd 3c01.indd 3 10/8/2012 9:39:21 AM10/8/2012 9:39:21 AM
    • 4 x CHAPTER 1 GETTING STARTED WITH ASP.NET 4.5 TRY IT OUT Installing Visual Studio Express 2012 for Web This Try It Out exercise guides you through installing VSEW on your computer. It assumes you’re using the Web Platform Installer option as explained earlier, although the process for installing the Express edition from a DVD is almost identical. The steps you need to perform to install the full versions of Visual Studio 2012 are similar as well, although the screens you’ll see will be somewhat different. No matter how you install VSEW, it’s important that you also install Microsoft SQL Express LocalDB Edition 11.0 — a required component if you want to follow along with many of this book’s examples. It should be installed automatically when you install VSEW, but in case it’s not installed, you’ll find instructions at the end of this exercise to make sure it’s properly installed. 1. Start by browsing to www.microsoft.com/express/ and follow the instructions to download VSEW 2012. Make sure you install Visual Studio Express 2012 for Web, and not one of the other free Express editions or older versions. If this link is ever changed or no longer provides direct access to the VSEW download, search the web for “install Visual Studio Express 2012 for Web” and you’ll be taken to a download page where you can start the installation. 2. Depending on how you started the installer, you have a few options. If you started the VSEW download, you should see a screen similar to Figure 1-1. FIGURE 1-1 Click Install to initiate the installation and related components. If you started the Web Platform Installer instead, find Visual Studio Express 2012 for Web in the list of tools and select it. Finally, start the installation process. 3. In both cases, you get a screen that lists the components to be installed. In addition, you need to agree to the license terms for the software. Once you agree, you should see a screen similar to Figure 1-2. 4. After a while you should see a message indicating that VSEW has been installed successfully. The installer may need to reboot your machine during or after the installation. Once the installer has c01.indd 4c01.indd 4 10/8/2012 9:39:21 AM10/8/2012 9:39:21 AM
    • Creating Your First ASP.NET 4.5 Website x 5 finished, VSEW is ready for use. To check if SQL Express LocalDB has installed correctly, start the Web Platform Installer from the Windows Start menu or Start screen. Next, under the Products item, find Microsoft SQL Express LocalDB Edition 11.0 and install it if it hasn’t been installed already. FIGURE 1-2 How It Works The straightforward installation process guided you through the setup of VSEW using the Web Platform Installer. During installation, the WPI also installed a copy of Microsoft SQL Express LocalDB Edition 11.0, Microsoft’s free version of its SQL Server 2012 database engine. SQL Server 2012 is discussed and used a lot in this book, starting with Chapter 12. Appendix B shows you how to configure security settings for the various versions of SQL Server 2012. Now that VSEW is installed, it’s time to fire it up and start working with it. The next section shows you how to create your very first site in VSEW. You see how to create a site, add content to a web page, and view that page in your browser. CREATING YOUR FIRST ASP.NET 4.5 WEBSITE You probably can’t wait to get started with your first ASP.NET website, so instead of giving you a theoretical overview of websites in VS, the next Try It Out exercise dives right into the action and shows you how to build your first web project. Then, in the How It Works explanation and the section that follows, you get a good look at what goes on behind the scenes when you view an ASP.NET page in your browser. c01.indd 5c01.indd 5 10/8/2012 9:39:21 AM10/8/2012 9:39:21 AM
    • 6 x CHAPTER 1 GETTING STARTED WITH ASP.NET 4.5 TRY IT OUT Creating Your First ASP.NET Website 1. Start VS from the Windows Start menu or Start screen if you haven’t done so already. Follow the on-screen instructions to register VSEW online and get a key. Enter the key in the VSEW start-up screen and click Next to continue. Note: if you’re using the commercial version of Visual Studio, just start Visual Studio 2012 from the Start menu. All web-related components are accessed from the main VS program. The first time you start VS, there might be a delay before you can use it because it’s busy configuring itself. Subsequent starts of the application will go much faster. 2. If you’re using a commercial version of Visual Studio, you may also get a dialog box that lets you choose between different collections of settings the first time you start Visual Studio. The choice you make on that dialog box influences the layout of windows, toolboxes, menus, and shortcuts. Choose the Web Development settings because those settings are designed specifically for ASP.NET developers. You can always choose a different profile later by resetting your settings, as explained later in this chapter. 3. Once VS is fully configured, you see the main screen appear, as shown in Figure 1-3. FIGURE 1-3 You get a full description of all the windows, toolbars, panels, and menus in the next section, so for now, just focus on creating a new website. Click the File menu in the upper-left corner and choose New Web Site. If you’re using a commercial version of Visual Studio, depending on the settings you chose when starting Visual Studio the first time, you may have to open the submenu New first. c01.indd 6c01.indd 6 10/8/2012 9:39:21 AM10/8/2012 9:39:21 AM
    • Creating Your First ASP.NET 4.5 Website x 7 Make sure you don’t accidentally use the New Project menu, because that is used to create differ- ent types of .NET applications. The New Web Site dialog box appears as shown in Figure 1-4. FIGURE 1-4 4. In the Installed Templates section on the left you can choose a pro- gramming language you will use for your site. This book shows all examples in both Visual Basic and Visual C# so you can choose a language to your liking. 5. In the list of templates in the middle, click ASP.NET Web Forms Site. Verify that File System is the selected option in the Web Location drop-down list at the bottom left. If you want, you could change the location on disk where the website is stored by clicking the Browse button and choosing a new location on your computer’s hard drive. For now, the default location — a folder under your Documents folder — is fine, so you can leave the location as is. 6. Click OK. VS creates a new website for you that includes a number of files and folders (see Figure 1-5) to jump-start your website. 7. Open the file Default.aspx by double-clicking it and remove all the code inside the <asp:Content> block that has its ID set to BodyContent (it starts with <h3> at around line 19 and ends with </ol>) all the way at the bottom. Replace it with the following bolded code: <asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent"> <h2>Hello World</h2> <p>Welcome to Beginning ASP.NET 4.5 on <%: DateTime.Now.ToString() %></p> </asp:Content> FIGURE 1-5 c01.indd 7c01.indd 7 10/8/2012 9:39:21 AM10/8/2012 9:39:21 AM
    • 8 x CHAPTER 1 GETTING STARTED WITH ASP.NET 4.5 You’ll see code formatted like this a lot more in this book. When you are instructed to type in code formatted like this with some code in bold, you only need to type in the bolded code. The other code should already be present in the file. Don’t worry about the code with the angle brackets (<>) and percentage symbol in the welcome message; these are called tags, and you learn more about them later. Although this code may not look familiar to you now, you can probably guess what it does: It writes out today’s date and time. 8. Press Ctrl+F5 to open the page in your default web browser. You see a page similar to the one shown in Figure 1-6. FIGURE 1-6 If you already have some experience with Visual Studio you may be used to pressing F5 instead. If you use that option, the site is opened in debug mode and you may get a dialog asking if you want to enable debugging (which you can safely do). Debugging with F5 is discussed in Chapter 18, and you’re advised to use Ctrl+F5 until then. If you see an information bar warning about intranet settings in Internet Explorer, click Turn on Intranet Settings. If you don’t see the date and time in the page, or if you get an error, look again at the code in the welcome message. It starts with an angle bracket (<) followed by a percentage symbol and a colon. It closes with a single percentage sign and another angle bracket (>). Also, make sure you typed in the code exactly as shown here, including capitalization. This is especially true when you are using C#, because that language is case sensitive. 9. Notice how a small icon representing IIS Express has appeared in the tray bar of Windows, visible in Figure 1-7. FIGURE 1-7 c01.indd 8c01.indd 8 10/8/2012 9:39:22 AM10/8/2012 9:39:22 AM
    • Creating Your First ASP.NET 4.5 Website x 9 If you see a different icon, right-click your site in VS and choose Use IIS Express. If you don’t see the icon in the tray, click the arrow near the other icons in the Windows tray and click the Customize option. Then set IIS Express System Tray to Show Icon and Notifications. The icon belongs to the built-in web server called IIS Express. This web server has been started by VS auto- matically to serve the request for your page. You learn more about how the web server processes your page later in this chapter. That’s it. You just created your very first ASP.NET website with Visual Studio. How It Works Although the website you created in this Try It Out is quite simple, the process that eventually results in the page Default.aspx being displayed in your browser isn’t so simple. All by itself, an ASP.NET page (also referred to as an ASPX page because of its extension, or a Web Form) can’t do much. It needs to be processed and served by a web server before your browser can display it. That’s why VS automati- cally started up IIS Express to handle the request for the page. Next, it started up your default web browser and directed it to the address of the web server (http://localhost:49474/Default.aspx in the Try It Out example), although the actual port number in the address may change every time you start the web server because it is randomly chosen by VS. It’s important to realize that the ASPX file you modified in VS is not the same as the one that eventually gets displayed by the browser. When you create a page in VS, you add markup to it. The markup in an ASPX page is a combination of HTML, code for ASP.NET Server Controls (which you learn more about in this chapter and in Chapter 4), code written in Visual Basic.NET or C#, and more. When you request an ASPX page in your browser, the web server processes the page, executes any server-side code it finds in the file, and effectively transforms the ASP.NET markup into plain HTML that it then sends to the browser, where it is displayed. In the preceding Try It Out, the resulting HTML causes the browser to display the current date and time. HTML, or HyperText Markup Language, is the language that browsers use to display a web page. You learn how HTML looks and how to use it later in this chapter. To see how the final HTML differs from the original ASPX page, open the source for the page in your browser. In most browsers, you can bring up the source window by right-clicking the page in the browser and choosing View Source or View Page Source. This brings up your default text editor, show- ing the HTML for the page. If you already closed your browser after the preceding Try It Out, press Ctrl+F5 in VS to open the page and choose View Source. Scroll down in the source file until you see the line with the Welcome text. Notice how instead of the code between the tags, you now see the actual date and time: <h2>Hello World</h2> <p>Welcome to Beginning ASP.NET 4.5 on 8/31/2012 2:13:15 AM</p> When the web server processed the page, it looked up the current date and time from the server and inserted it in the HTML that got sent to the browser. Depending on the language settings of your Windows installation, you may see the date and time formatted differently to accommodate the Windows Regional Settings. c01.indd 9c01.indd 9 10/8/2012 9:39:22 AM10/8/2012 9:39:22 AM
    • 10 x CHAPTER 1 GETTING STARTED WITH ASP.NET 4.5 In the following section, you see how ASP.NET works in much more detail. AN INTRODUCTION TO ASP.NET 4.5 When you type a URL like www.wrox.com in your web browser and press Enter, the browser sends a request to the web server at that address. This is done through HTTP, the HyperText Transfer Protocol. HTTP is the protocol by which web browsers and web servers communicate. When you request the URL, you send a request to the server. When the server is active and the request is valid, the server accepts the request, processes it, and then sends the response back to the client browser. The relationship between the request and response is shown in Figure 1-8. Because you are using IIS Express, the server and the client are really the same machine. However, in a real-world scenario, you’ll host your website on an external web server where it can be accessed by many different clients. For simple, static files, like HTML files or images, the web server simply reads the file from its local hard drive and sends it to the browser. However, for dynamic files, such as ASPX pages, this is obviously not good enough. If the web server were to send the ASPX file directly to the browser as a text file, you wouldn’t have seen the current date and time in the browser, but instead you would have seen the actual code (<%: DateTime.Now.ToString() %>). So, instead of sending the file directly, the web server hands over the request to another piece of software that is able to process the page. This is done with a con- cept called Application Mapping or Handler Mapping, where an extension of a file (.aspx in this example) is mapped to an application that is capable of handling it. In the case of an .aspx page, the request is eventually handled and processed by the ASP.NET run time, part of the Microsoft .NET Framework designed specifically to handle web requests. During the processing of the page, three main areas can influence the way the page eventually ends up in the browser: ‰ Static text. Any static text, like HTML, CSS, or JavaScript code you place in a page, is sent to the browser directly. You learn more about HTML, CSS, and JavaScript (a programming language used at the client) in this and subsequent chapters, including Chapter 3, which gives you a detailed look at CSS. ‰ ASP.NET Server Controls. These controls are placed in your ASPX page and when they are processed, they emit HTML that is inserted in the page. You learn more about server controls after the discussion of HTML in this chapter, and Chapter 4 is devoted entirely to ASP.NET Server Controls. ‰ Programming code. You can embed code, like Visual Basic .NET or C#, directly in a page, as you saw in the previous Try It Out. In addition, you can place code in a separate code file. The official term for this code file is Code Beside. However, most developers refer to this as the Code Behind file, which is the term I’ll stick to in this book. This code can be executed by the run time automatically, or based on a user’s action. Either way, execution of the code can greatly influence the way the page is displayed, by accessing databases, performing Web Server Browser Request Response 21 FIGURE 1-8 c01.indd 10c01.indd 10 10/8/2012 9:39:22 AM10/8/2012 9:39:22 AM
    • An Introduction to ASP.NET 4.5 x 11 calculations, hiding or showing specific controls, and much more. You learn more about this Code Behind file in the next chapter, and programming your ASP.NET web pages is dis- cussed in great detail in Chapter 5. Once the page is done processing, and all the HTML for the page has been collected, the HTML is sent back to the browser. The browser then reads it, parses it, and, finally, displays the page for you to look at. Because HTML is so critical for displaying web pages, the next section gives you an overview of HTML. Understanding HTML HTML is the de facto language for creating web pages and is understood by every web browser that exists today. Since the beginning of the ’90s it has been the driving force of the World Wide Web, the part of the Internet that deals with web pages. HTML documents are simple text files that contain markup, text, and additional data that influences that text. The most recent version of HTML is HTML5. Although the specification of HTML5 is still under development, a lot of mod- ern browsers support important parts of this specification, and this support increases with each new release of those browsers. Despite the fact that not all browsers support HTML5 fully, it is really the future of HTML-based applications, and therefore I use it in this book and for the Planet Wrox demo website. Don’t worry about the limited browser support too much. All major browsers sup- port all of the HTML5 features you use in this book, or support can easily be simulated by a script library called Modernizr, which you see later in the book. HTML Elements and Tags HTML uses text surrounded by angle brackets to indicate how your content should be rendered (or displayed) in the browser. The text with angle brackets is referred to as a tag; a pair of tags holding some text or other content is referred to as an element. Take another look at the HTML you saw in the previous Try It Out where you opened the source window for the page in the browser: <h2>Hello World</h2> <p>Welcome to Beginning ASP.NET 4.5 on 8/31/2012 2:13:15 AM</p> The first line of this example contains an <h2> element with an opening tag (<h2>) and a closing tag (</h2>). This element is used to signify a heading at the second level (if you scroll up a bit in the final source in the browser, you also see an <h1> element). Notice how the element is closed with a similar tag, but with an additional forward slash (/) in it: </h2>. Any text between these opening and closing tags is considered part of the element, and is thus rendered as a heading. In most brows- ers, this means the text is rendered in a larger font. Similar to the <h2> tag are tags for creating headings up to level six, such as <h1>, <h3>, and so on. Below the heading element, you see a <p> element, which is used to denote a paragraph. All text within the pair of <p> tags is considered part of the paragraph. By default, a browser renders a para- graph with some additional margin spacing at the bottom, although you can override that behavior. Many tags are available in HTML, too many to cover them all here. The following table lists some of the most important tags and describes how they can be used. For a complete list of all HTML elements, take a look at the website of the organization that maintains the HTML standard: www.w3.org/TR/html5/index.html. c01.indd 11c01.indd 11 10/8/2012 9:39:22 AM10/8/2012 9:39:22 AM
    • 12 x CHAPTER 1 GETTING STARTED WITH ASP.NET 4.5 TAG DESCRIPTION EXAMPLE <html> Used to denote the start and end of the entire page. <html> ...All other content goes here </html> <head> Used to denote a special section of the page that contains data about the page, including its title and references to external resources. The contents of this element are not directly output on screen but influ- ence the looks and behavior of the page, as you’ll see later. This element is placed inside the <html> element. <head> ...Content goes here </head> <title> Used to define the title of the page. This title will appear in the browser’s title bar. This element is placed inside the <head> element. <title> ...Welcome to Planet Wrox 4.5 </title> <body> Used to denote the start and end of the body of the page. Its content is what you see in the browser. This element is placed inside the <html> element. <body> ...Page body goes here </body> <header> Used to denote the header of a page. This element and all remaining elements in this table are placed inside the <body> element. <header> ...<img src="Logo.png" … /> </header> <section> Used to denote various sec- tions in your page. You can have multiple sections per page. <section> ...Content goes here </section> <aside> Used to denote content that is not part of the core page, but presented as an aside. <aside> ...<img src="Banner.png" … /> </aside> c01.indd 12c01.indd 12 10/8/2012 9:39:22 AM10/8/2012 9:39:22 AM
    • An Introduction to ASP.NET 4.5 x 13 TAG DESCRIPTION EXAMPLE <article> Used to denote the main piece of content in a page. <article> ...Main page content goes here </article> <footer> Denotes the footer section of a page. <footer> ...Content for footer goes here </footer> <a> Used to link one web page to another or to create links within a page. <a href="http://www.wrox.com"> Visit the Wrox site </a> <img> Used to embed images in a page. <img src="Logo.gif" /> <strong> <em> Used to format text in a bold or italic font. This is <strong>bold text</ strong> while <em>this text is in italic</em> <form> <input> <textarea> <select> Used for input forms that enable users to submit infor- mation to the server. <input type="text" value="Some Text" /> <table> <tr> <th> <td> These tags are used to cre- ate a layout with a table. The <table> tag defines the entire table, the <th> is used to denote header cells, and the <tr> and <td> tags are used to define rows and cells, respectively. <table> <tr> <td>This is a Cell in Column 1</td> <td>This is a Cell in Column 2</td> </tr> </table> <ul> <ol> <li> These three tags are used to create numbered or bul- leted lists. The <ul> and the <ol> tags define the looks of the list (either unor- dered, with a simple bullet, or ordered, with a number), and the <li> tag is used to represent items in the list. <ul> <li>First item with a bullet</li> <li>Second item with a bullet</li> </ul> <ol> <li>First item with a number</li> <li>Second item with a number</li> </ol> <span> This tag is used to wrap and influence other parts of the document. It appears as inline, so it adds no additional line break on the screen. <p>This is some normal text while <span style="color: red;">this text appears in red </span></p> (continued) c01.indd 13c01.indd 13 10/8/2012 9:39:22 AM10/8/2012 9:39:22 AM
    • 14 x CHAPTER 1 GETTING STARTED WITH ASP.NET 4.5 TAG DESCRIPTION EXAMPLE <div> Just like the <span> tag, the <div> tag is used as a con- tainer for other elements. However, the <div> acts as a block element, which causes an explicit line break before and after the <div> element by default. <div> This is some text on 1 line</div> <div> This text is put directly under the previous text on a new line. </div> <audio> <video> <source> Used to embed audio and video files in your web page. The <source> ele- ment is used to define multiple types of audio and video resources. <video src="Somevideo.mpg" /> HTML Attributes In addition to the HTML elements, the examples in the preceding table also showed you HTML attributes. Attributes contain additional information that changes the way a specific element behaves. For example, with the <img> tag that is used to display an image, the src attribute defines the source of that image. Similarly, the <span> tag contains a style attribute that changes the color of the text to red. The value of the style attribute (color: red;) is part of a cascading style sheet (CSS), which is discussed in much more detail in Chapter 3. Just as with the HTML elements, there is a long list of available attributes and the elements to which they apply on the W3C website: www.w3.org/TR/html5/index.html#attributes-1. You don’t need to memorize all these elements and attributes. Most of the time, they are generated for you automatically by VS. In other cases, where you need to enter them by hand, VS offers you IntelliSense to help you find the right tag or attribute. IntelliSense is discussed in the next chapter. HTML Comments In order to comment something out in HTML, you wrap it in comment tags, like this: <!-- This is a comment --> Code you comment out is not processed by the browser (and thus isn’t visible), but it’s still sent to the browser (and thus is viewable by the end user). Because it is still sent to the browser, it adds to the page size, so you should use comments sparingly. In later chapters you see how to comment out code at the server so it’s not sent to the client. The Rules of HTML5 The rules of HTML5 are pretty simple, and most of the time VS helps you get it right or shows you a list of errors and suggestions for how to fix them. HTML5 is actually more relaxed than the (continued) c01.indd 14c01.indd 14 10/8/2012 9:39:22 AM10/8/2012 9:39:22 AM
    • An Introduction to ASP.NET 4.5 x 15 previous version of HTML (called XHTML, which in turn was a reformulation of HTML 4.01 with XML rules) when it comes to enforcing rules. Close Your Elements Most elements in HTML must be closed. So when you start with a <div> tag, you must use </div> somewhere later in your page. Some exceptions exist (such as the <p> element if it’s directly followed by some other elements), but I prefer to consistently close my tags. This is also the case for elements that don’t have their own closing tags, like <img> or <br> (to enter a line break). In HTML5, these tags can be written as self-closing tags, where the closing slash is embedded directly in the tag itself as in <img src="Logo.gif" /> or <br />. Usage of Attributes Whenever you write an attribute in a tag, you can write the value wrapped in double quotes, single quotes, or no quotes at all. For example, when writing out the <img> tag and its src attribute, you can write it like this: <img src="Logo.gif" /> You could also use single quotes to enclose the attribute value, like this: <img src='Logo.gif' /> Both options work, as long as you use the same type of quote on both ends of the value. For values that don’t contain a space, you can also leave out the quotes: <input value=yes> It’s also sometimes necessary to nest single and double quotes. For example, when some special ASP .NET syntax requires the use of double quotes, you should use single quotes to wrap the attribute’s value: <asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' /> You see this syntax used a lot more in later chapters in this book. For consistency, this book uses double quotes where possible in all HTML that ends up in the client, as this is generally the accepted standard. Nest Your Elements Correctly When you write nested elements, make sure that you first close the inner element you opened last, and then close the outer element. Consider this correct example that formats a piece of text with both bold and italic fonts: <strong><em>This is some formatted text</em></strong> Notice how the <em> tag is closed before the <strong> tag. Swapping the order of the closing tags leads to invalid HTML: <strong><em>This is some formatted text</strong></em> Add a DOCTYPE Declaration to Your Page A DOCTYPE gives the browser information about the kind of HTML it can expect. By default, VS adds a DOCTYPE for HTML5 to your page: c01.indd 15c01.indd 15 10/8/2012 9:39:22 AM10/8/2012 9:39:22 AM
    • 16 x CHAPTER 1 GETTING STARTED WITH ASP.NET 4.5 <!DOCTYPE html> The DOCTYPE greatly influences the way browsers like Internet Explorer render the page, so if you’re seeing odd behavior on your page, check that your page has the correct DOCTYPE. You can view the complete HTML5 syntax rules at the W3C site at www.w3.org/TR/html-markup/ syntax.html. Besides HTML, an ASP.NET web page can contain other markup as well. Most pages will have one or more ASP.NET Server Controls to give them some additional functionality. The next section briefly looks at these ASP.NET Server Controls, but you get an in-depth look at them in Chapter 4. A First Look at ASP.NET Markup To some extent, the markup for ASP.NET Server Controls is similar to that of HTML. It also has the notion of tags, elements, and attributes, using the same angle brackets and closing tags as HTML does. One big difference is that the ASP.NET tags start with an asp: prefix. For example, a button in ASP.NET looks like this: <asp:Button ID="Button1" runat="server" Text="Click Me" /> Note how the tag is self-closed with the trailing slash (/) character, eliminating the need to type a separate closing tag. If you wanted to, you could use a separate closing tag, though. When a server control is processed, it returns HTML. So, the code for the same button ends up like this when rendered in the browser: <input type="submit" name="Button1" value="Click Me" id="Button1" /> The process of converting the server control to its HTML representation is similar to the code you saw earlier that displayed the current date. The server control is processed at the server by the ASP .NET handler. This processing results in HTML, which is sent to the browser, where it’s displayed. You see more of this in Chapter 4. Now that you understand the basics of an ASP.NET page and the HTML that it generates, it’s time to look at VS again. Knowing how to use the application and its many tools and windows is an important step in building fun, good-looking, functional websites. A TOUR OF THE IDE Visual Studio is by far the most extensive and feature-rich integrated development environment (IDE) for building ASP.NET web pages. The abbreviation IDE refers to the way all the separate tools you need to build complex web applications are integrated in a single environment. Instead of writing code in a text editor, compiling code at the command line, writing HTML and CSS in a separate application, and managing your database in yet another, VS enables you to perform all of these tasks, and more, from the same environment. Besides the efficiency this brings because you don’t have to constantly switch tools, this also makes it much easier to learn new areas of VS, because many of the built-in tools work in the same way. c01.indd 16c01.indd 16 10/8/2012 9:39:22 AM10/8/2012 9:39:22 AM
    • A Tour of the IDE x 17 The Main Development Area To get familiar with the many tools that are packed in VS’s interface, take a look at Figure 1-9. It shows the same screen you got after you created your first website in VS, but now it highlights some of the most important screen elements. If you are already familiar with a previous version of Visual Studio, you could skip this section and pick up again at the next Try It Out exercise later in this chapter. Main Menu Toolbar Area Solution Explorer Database Explorer Properties Grid Toolbox Document Window Tool Windows FIGURE 1-9 If you had a previous version of Visual Studio installed, your screen may look different, because Visual Studio 2012 is able to import settings from older versions. Choosing Your Development Profile Because VSEW targets people new to ASP.NET development as well as seasoned web developers, you can choose among different developer profiles: Basic Settings, Code Only, and Expert Settings. In Basic Settings mode, many menu items you don’t frequently use have been hidden or are placed in their own submenu. The Code Only profile is great for pure coding sessions where you’re not inter- ested in many of the design features of VSEW, such as Design View or the Toolbox. Expert Settings mode gives you access to the full functionality of VSEW. You can switch between settings using the Tools Í Settings menu. This book assumes you are using Expert Settings mode right from the beginning. You may not need all the features you see right from the start, but you sure will use most of them by the end of the book. Because the menu items change location depending on the profile you choose, I decided to use Expert Settings mode right away, to make it easier to refer to a specific menu item or feature. You don’t have this option in the commercial versions of Visual Studio — Expert Settings is on by default. c01.indd 17c01.indd 17 10/8/2012 9:39:22 AM10/8/2012 9:39:22 AM
    • 18 x CHAPTER 1 GETTING STARTED WITH ASP.NET 4.5 The Main Menu At the top of the application, right below the Windows title bar, you see the main menu. This menu bar contains familiar items you find in many other Windows applications, like the File, Edit, and Help menus as well as menus that are specific to VS, such as the Website and Debug menus. The menu changes dynamically depending on the task you’re working on, so you’ll see menu items appear and disappear as you work your way through the application. You can use the Help Í Set Help Preference menu to configure online and offline help. Offline help needs to be installed first, and online help requires a connection to the Internet. The Toolbar Area Right below the menu, you see the toolbar area, which is capable of showing different toolbars that give you quick access to the most common functions in VS. In Figure 1-9, only two of the toolbars are enabled, but VS comes with many other toolbars that you can use in specific task-oriented sce- narios. Some toolbars appear automatically when you’re working on a task that requires a particular toolbar’s presence, but you can also enable and disable toolbars to your liking. To enable or disable a toolbar, right-click an existing toolbar or the menu bar and choose the toolbar from the menu that appears. The Toolbox On the left of the main screen, tucked away at the border of VS, you see the tab for the Toolbox. If you click the tab, the Toolbox folds out, giving you a chance to see what it contains. If you click the little pin icon in the upper-right corner of the Toolbox (or any of the other panels that have this pin icon), it gets pinned to the IDE so it remains open. Just as with the menu bar and the toolbars, the Toolbox automatically updates itself to show con- tent that is relevant to the task you’re working on. When you’re editing a standard ASPX page, the Toolbox shows the many controls you have available for your page. You can simply drag an item from the Toolbox and drop it on a location of your page where you want it to appear. These controls are discussed in great detail in Chapter 4. Note that each Toolbox category also contains a Pointer icon. This isn’t a control itself, though. In other designers for Visual Studio (such as Win Forms) this icon is used to get out of control drawing mode, but it has little use in ASP.NET. The Toolbox contains multiple categories, with tools that you can expand and collapse as you see fit to make it easier to find the right tool. You can also reorder the items in the list, add and remove items from the Toolbox, and even add your own tools to it. Customizing the IDE is discussed later in this chapter. If the Toolbox is not visible on-screen, press Ctrl+Alt+X to open it or choose View Í Toolbox, pro- vided you have chosen the Expert Settings option in the Tools Í Settings menu. The Solution Explorer At the right of the screen, you see the Solution Explorer. The Solution Explorer is an important win- dow because it gives you an overview of the files that comprise your website. Instead of placing all your files in one big folder, the Solution Explorer enables you to store files in separate folders, creat- ing a logical and organized site structure. You can use the Solution Explorer to add new files to your site, move existing files around using drag and drop or cut and paste, rename files and delete them c01.indd 18c01.indd 18 10/8/2012 9:39:23 AM10/8/2012 9:39:23 AM
    • A Tour of the IDE x 19 from the project, and more. Much of the functionality of the Solution Explorer is hidden behind its right-click menu, which changes depending on the item you right-click. At the top of the Solution Explorer, you see a small toolbar that gives you quick access to some functionality related to your website, including refreshing the Solution Explorer window, an option to nest related files, and two buttons that enable you to copy and configure your website. Most of this functionality is discussed later in the book. You can access the Solution Explorer by choosing View Í Solution Explorer from the main menu or by pressing Ctrl+Alt+L. The Database Explorer This window, hidden behind the Solution Explorer in Figure 1-9, enables you to work with your databases. If you have a commercial version of Visual Studio, such as Visual Studio 2012 Professional, this window is called the Server Explorer and may be located at the left of your screen. You can access the Database Explorer by choosing View Í Database Explorer or by pressing Ctrl+Alt+S. The Database Explorer is discussed in more detail in the chapters about databases, starting with Chapter 12. The Properties Grid With the Properties Grid, you can view and edit the properties of many items in Visual Studio, including files in the Solution Explorer, controls on a web page, properties of the page itself, and much more. The window constantly updates itself to reflect the selected item. You can quickly open the Properties Grid by pressing F4. You can use this same shortcut to force the Properties Grid to show the details of a selected item. The Document Window The Document Window is the main area in the middle of the application. This is where most of the action takes place. You can use the Document Window to work with many different document formats, including ASPX and HTML files, CSS and JavaScript files, code files for VB and C#, XML and text files, and even images. In addition, you can use the same window to manage databases, cre- ate copies of your site, view the pages in your site in the built-in mini-browser, and much more. The Document Window is a tabbed window by default, which means it can host multiple docu- ments, each one distinguished by a tab with the filename at the top of the window. The right-click menu of each tab contains some useful shortcuts for working with the file, including saving and clos- ing it and opening the file’s parent folder in Windows Explorer. To switch between documents, you can press Ctrl+Tab, click the tab for the document you want to see, or click the down arrow in the upper-right corner of the Document Window, next to the Solution Explorer, shown in Figure 1-9. Clicking the down arrow reveals a list of open documents so you can easily select one. Another way to switch documents is to press Ctrl+Tab and then hold down the Ctrl key. On the win- dow that pops ups, you can select a document you want to work with in the right-hand column. You c01.indd 19c01.indd 19 10/8/2012 9:39:23 AM10/8/2012 9:39:23 AM
    • 20 x CHAPTER 1 GETTING STARTED WITH ASP.NET 4.5 can then use the cursor keys to move up and down in the list with open documents. This makes it super easy to select the correct file. On the same dialog box, you see a list with all active tool windows. Clicking one of the windows in the list shows it on-screen, moving it in front of other windows if necessary. To get a quick preview of a document without opening it for editing, click the file you want to see in the Solution Explorer once. You can see that a file is in preview mode by its tab, which is docked to the right of the row with tabs as opposed to the left for open files. At the bottom of the Document Window in Figure 1-9, you see three buttons called Design, Split, and Source. These buttons appear automatically when you’re working with a file that contains markup, such as ASPX and HTML pages. They enable you to open the Design View of a page (giv- ing you an idea of how the page will look in the browser), its Markup View (the HTML and other markup), or both at the same time. How this works is explained in more detail in Chapter 2, but for now, it’s important to realize you can switch among Markup, Split, and Design View by clicking one of the three buttons. The Markup View is also often called the Source View or Code View window. However, to avoid confusion with the code editor that is used to edit Code Behind files, this book uses the term Markup View exclusively. The Start Page Whenever you start up VS, the Start Page is loaded in the Document Window. With the Start Page, you can quickly create new and open existing websites and other projects. The Start Page also pro- vides a number of links to related news and information about web development. To reopen the Start Page, choose View Í Start Page. To get a feel for how you can use all these windows, the following Try It Out shows you how to build a simple web page that contains a few ASP.NET Server Controls. TRY IT OUT Creating Your First ASP.NET Web Page This Try It Out exercise guides you through creating a new website with a single page that contains a number of ASP.NET Server Controls. You see how to use windows like the Document Window and the Solution Explorer, and how to use the Toolbox and the Properties Grid to add ASP.NET Server Controls to the page and change their looks. 1. Start VSEW or Visual Studio 2012. 2. If you’re using the Express edition, choose Tools Í Settings and choose Expert Settings to turn on the developer profile that gives you access to the full feature set of VSEW. 3. On the File menu choose New Web Site. Depending on configuration, you may have to choose File Í New Í Web Site instead. This triggers the New Web Site dialog box. 4. In this dialog box, make sure that ASP.NET Empty Web Site is selected and not the ASP.NET Web Forms Site item that you used in a previous exercise. Ensure that File System is chosen in the Web Location drop-down list. Click OK to create the new site. 5. Next, right-click the new website in the Solution Explorer. Make sure you click the website (labeled WebSite2) and not the parent Solution element. It’s the highlighted element in Figure 1-5. From the context menu that appears, choose Add Í Add New Item. c01.indd 20c01.indd 20 10/8/2012 9:39:23 AM10/8/2012 9:39:23 AM
    • A Tour of the IDE x 21 6. In the new window that appears, click Web Form and type ControlsDemo as the name. The ASPX extension is added for you automatically when you click the Add button. You can leave the other settings in the dialog box at their default settings. The page should open in Markup View, show- ing you the default HTML, like the <html>, <head>, <title>, and <body> elements that VS adds there for you automatically when you create a new page. 7. Switch the page to Design View by clicking the Design button at the bottom of the Document Window. 8. If the Toolbox isn’t open yet, press Ctrl+Alt+X to open it or click the Toolbox tab to show it and then click the pin icon in the top-right corner to make the Toolbox visible at all times. Drag a TextBox and a Button from the Standard category of the Toolbox into the dashed area in the Design View of the page. You should end up with a Design View that looks similar to Figure 1-10. 9. Right-click the button in Design View and choose Properties. In the Properties Grid, locate the Text property under the Appearance category (shown in Figure 1-11) and change it from Button to Submit Information. As soon as you press Tab or click somewhere outside the Properties Grid, the Design View of the page is updated and shows the new text on the button. 10. Press Ctrl+F5 to open the page in your default browser. Note that it’s not necessary to explicitly save the changes to your page (although it’s a good idea to do this often anyway using the shortcut Ctrl+S). As soon as you press Ctrl+F5 to run the page, VS saves all changes to open documents automatically. 11. Type some text in the text box and click the button. Note that after the page has reloaded, the text is still displayed in the text box. Other than that, not much has happened because you didn’t write any code for the button yet. How It Works When you dragged the Button and the TextBox from the Toolbox on the page in Design View, VS added the corresponding code for you in Markup View automatically. Similarly, when you changed the Text property of the button in the Properties Grid, VS automatically updated the markup for the con- trol in Markup View. Instead of using the Properties Grid, you could also have typed the text directly between the quotation marks of the Text property in Markup View. After changing the Text property, your page should contain this code in Markup View: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Submit Information" /> When you press Ctrl+F5 to view the page in the browser, the web server receives the request, the page is processed by the ASP.NET run time, and the resulting HTML for the page is sent to the browser. After you type in some text and click the button, the same process is more or less repeated: The web server receives the request, the page is processed, and the result gets sent back to the browser. When you click the button, you cause a postback to occur, where any information contained in the FIGURE 1-10 FIGURE 1-11 c01.indd 21c01.indd 21 10/8/2012 9:39:23 AM10/8/2012 9:39:23 AM
    • 22 x CHAPTER 1 GETTING STARTED WITH ASP.NET 4.5 page — such as the text you typed in the text box — is sent back to the server. ASP.NET reacts to the postback by rendering the page again. However, this time it prepopulates controls, like the TextBox, with the values that were sent to the page. Take a look at the resulting HTML for the page after the postback, using the browser’s View Source command (rerun the page from VS by pressing Ctrl+F5 if you already closed it). You should see code similar to this: <input name="TextBox1" type="text" value="Hello World" id="TextBox1" /> <input type="submit" name="Button1" value="Submit Information" id="Button1" /> Just as with the earlier example, you can see that the resulting HTML is substantially different from the original ASPX markup. Postbacks are an important concept in ASP.NET, and you see more about them in other chapters, including Chapter 4. VSEW hosts many more windows and tool panels than those you have seen so far. The next section briefly touches upon some of the windows you’ll most frequently use when building ASP.NET web pages. All of the windows mentioned are accessible from the main View menu in VS or VSEW if you’re using the Expert Settings mode. Informational Windows In addition to the windows that are visible by default when you start VS, many more windows are available. You see most of them in action in the remainder of this book, but some are worth high- lighting now. You access all windows that are discussed next from the main View menu. The Error List The Error List gives you a list of the things that are currently somehow broken in your site, includ- ing incorrect markup in your ASPX or HTML files and programming errors in VB or C# files. This window can even show you errors in XML and CSS files. The Error List shows its messages in three categories — Errors, Warnings, and Messages — that signify the severity of the problem. Figure 1-12 shows the Error List for a page that has some problems with its CSS and XHTML. FIGURE 1-12 The Output Window When you try to build your site using the Build menu, the Output window tells you whether or not the build succeeded. If the build failed, for example because you have a programming error, it tells you why the build failed. In the commercial versions of Visual Studio, the Output window is used c01.indd 22c01.indd 22 10/8/2012 9:39:23 AM10/8/2012 9:39:23 AM DownloadfromWow!eBook<www.wowebook.com>
    • Customizing the IDE x 23 for other information as well, including the status of external plug-in programs. Building — or com- piling — websites is discussed later in this book, including in Chapter 19, which deals with deploy- ment of your website. The Find Results Window The Find and Replace features of VS are invaluable tools when it comes to managing the content of your site. You will often need to replace some text in the current document or even in the entire site. Find in Files (Ctrl+Shift+F) and Replace in Files (Ctrl+Shift+H) both output their results in the Find Results window, as shown in Figure 1-13. FIGURE 1-13 Because having several informational windows open at the same time may take up precious screen space, it’s often a good idea to dock them. This way, only one of them is visible at a time, while you still have quick access to the others. You learn how to customize the IDE, including the docking of windows, next. CUSTOMIZING THE IDE Although the standard setup of Visual Studio and its tool windows is pretty useful, there’s a fair chance you want to customize the IDE to your liking. You may want to move some of the windows to a location where they are easier to reach, or you may want to open additional windows you fre- quently use. Visual Studio is fully customizable and enables you to tweak every little detail of the IDE. In the next section, you learn how to perform the most common customization tasks. Rearranging Windows To give each window the location it deserves, you can drag and drop them in the main IDE. Simply grab a window’s title bar or its bottom tab and drag it in the direction of the new location. Once you start dragging, you see that Visual Studio gives you visual cues as to where the window will end up (see Figure 1-14). If you drag the window over one of the four square indicators at the sides of the middle indicator, the window will be docked next to the existing window. Once you drop it, the window pops to its new location. If you drop the window on the square in the middle of the large indicator, the window docks with that window, sharing the same screen space. Each window has its own tab, as you can see with the windows at the bottom of Figure 1-14. In addition to docking windows with others in the IDE, you can also have floating windows. To change a docked window into a floating one, drag it away from its current location and drop it somewhere in the IDE without hitting one of the visual cues on the screen. You can also choose Window Í Float from the main menu or right-click the window’s title bar and choose Float. c01.indd 23c01.indd 23 10/8/2012 9:39:23 AM10/8/2012 9:39:23 AM
    • 24 x CHAPTER 1 GETTING STARTED WITH ASP.NET 4.5 FIGURE 1-14 To restore a floating panel to its previous docked location, right-click its title bar and choose Dock or choose Window Í Dock from the main menu. Make sure you don’t choose Dock as Tabbed Document for the tool windows, like the Toolbox or the Solution Explorer, or they’ll end up in the main Document Window. This makes it difficult to use these tool windows together with an open file because the two windows will share the same space. Modifying the Toolbox You can modify the Toolbox as well. By default, the items are sorted alphabetically, but you can reorder them using drag and drop. To do this, open the Toolbox (press Ctrl+Alt+X) and drag an item (such as the TextBox under the Standard category) to a different location. You can also delete items from the Toolbox by right-clicking them and choosing Delete from the context menu. Don’t worry about items getting lost forever; you can reset the Toolbox again by choosing Reset Toolbox from the same menu. You can also add your own items to the Toolbox. The most common use for this is code snippets. Simply highlight some text or code in the Document Window and drag it to the Toolbox. You can then right-click the item and choose Rename Item to give it a more meaningful name that you can easily recognize. To avoid cluttering up the Toolbox with your own code snippets, consider creating a separate cat- egory for them. You can do this by choosing Add Tab from the Toolbox’s right-click menu. Enter a name and press Enter, and your Toolbox tab is ready for use. In the next Try It Out exercise, you get the chance to play around with the Visual Studio IDE so you can customize it to your liking. c01.indd 24c01.indd 24 10/8/2012 9:39:23 AM10/8/2012 9:39:23 AM
    • Customizing the IDE x 25 TRY IT OUT Customizing the IDE In this exercise you practice opening and rearranging the windows in the VS IDE. Don’t be afraid to mess things up. A little later in this chapter, instructions are given on how to reset the IDE to the way it was when you opened it the first time. 1. If you closed your website since the previous Try It Out, open it again, or create a new one using the File menu. 2. From the View menu, choose Error List to open the Error List window. If you don’t see the Error List item directly, choose Tools Í Settings Í Expert Settings first. Notice how the Error List gets docked below the Document Window by default. 3. From the same View menu, choose Task List. By default, it is docked in the same space as the Error List, with the tabs for both windows next to each other. 4. Click the tab of the Task List and, while holding down your mouse button, drag the Task List away from its location in the direction of the Document Window. Once you release the window, it appears as a floating window in the IDE. To restore the window, drag it back on the center square of the Error List. To change the order in which tabs appear in a tab group, drag a tab over the other tabs and release it at the desired location. 5. If you want, you can repeat the previous steps for other windows that are visible in the IDE by default or for the ones you find under the View menu. Spend some time familiarizing yourself with all the different windows and how you can arrange them on-screen. Because you’ll be working a lot with these windows in the remainder of this book, it’s good to be familiar with their locations. 6. Next, open the ControlsDemo.aspx page (or add a new ASPX first if you created a new website) from the Solution Explorer by double-clicking it. When the page opens, the Toolbox becomes vis- ible automatically. If it doesn’t, press Ctrl+Alt+X to open it. 7. Right-click the Toolbox and choose Add Tab. Type HTML Fragments as its new name and press Enter. This adds a new category to the Toolbox that behaves just like all the others. 8. With the Document Window showing your ASPX page in Markup View, type <h1> directly after the opening <div> tag. Note that Visual Studio automatically inserts the closing </h1> for you. You should end up with code in Markup View looking like this: <form id="form1" runat="server"> <div> <h1></h1> </div> 9. Highlight the opening and closing <h1> tags, and then drag the selection from the Markup View window onto the new Toolbox tab you created in step 7. The selection shows up as Text: <h1></h1>. 10. Right-click the Toolbox item you just created, choose Rename Item, and type Heading 1 as the name. 11. Put your cursor in the Document Window again and press Ctrl+K directly followed by Ctrl+D to format the document in the Document Window. Alternatively, choose Edit Í Format Document c01.indd 25c01.indd 25 10/8/2012 9:39:23 AM10/8/2012 9:39:23 AM
    • 26 x CHAPTER 1 GETTING STARTED WITH ASP.NET 4.5 from the main menu. This formats the document according to the rules you have set in the Text Editor Options dialog box. Formatting is also available for a number of other document types, including C# and VB.NET code, and CSS and XML files. From now on, whenever you need a heading in your document in Markup View, simply place the cursor in the Document Window where you want the heading to appear and double-click the appropriate heading in the Toolbox. NOTE This exercise serves as an example of adding code to the Toolbox. For an <h1> element, you might prefer to type the code directly in the code editor. Alternatively, you could use a code snippet. Enter h1 in the editor and then press Tab. Visual Studio expands the code for the heading to <h1></h1> and positions your cursor between the two tags so you can start typing the heading right away. How It Works Most of the steps in this Try It Out are self-explanatory. You started off by opening a few windows that you frequently need when building websites. You then used the drag-and-drop features of the IDE to rearrange the window layout according to your personal preferences. You then added an HTML fragment to a custom tab in the Toolbox. When you drag any markup to the Toolbox, Visual Studio creates a Toolbox item for it that contains the selected markup. Whenever you need a copy of that markup in your page, simply double-click the item or drag it from the Toolbox into Markup View. This is a great time saver for HTML fragments that you frequently use. You typically use this technique for larger blocks of code; for elements like the <h1>, Visual Studio has a better tool called Code Snippets, which you meet later in this book. At the end you used Visual Studio’s document formatting option to change the layout of the code in the document. This helps to keep the code organized and easier to read. You can fully change how the code is formatted by using the Options dialog box accessible through Tools Í Options. Then expand the path Text Editor Í HTML Í Formatting, and click Tag Specific Options. Besides the window layout and the Toolbox, Visual Studio enables you to customize a lot more in the IDE. The following section explains how to customize three other important IDE features: the Document Window, toolbars, and keyboard shortcuts. Customizing the Document Window Visual Studio gives you great flexibility with regard to how text is displayed in the Document Window. You can change things like font size, font color, and even the background color of the text. You can access the Font and Colors settings by choosing Tools Í Options, and then choosing Environment Í Fonts and Colors. One thing I like to customize in the Document Window is the tab size, which controls the number of spaces that are inserted when indenting code. To change the tab size, choose Tools Í Options, and then under Text Editor choose All Languages Í Tabs. I usually set the Tab and Indent Size c01.indd 26c01.indd 26 10/8/2012 9:39:23 AM10/8/2012 9:39:23 AM
    • Customizing the IDE x 27 to 2 spaces, leaving the other settings in the Tab panel untouched. Another thing I like to customize is the number of line breaks before and after HTML elements. The Options window gives you full control over this: Select Text Editor Í HTML Í Formatting and then click Tag Specific Options. In the list on the left you can select a tag and then with the settings on the right you can control how the tag is formatted. The Preview box makes it easy to see how the various settings change the formatting. With the exception of the Tab Size being set to 2 and the number of line breaks around a few HTML elements, all screen shots in this book show the default setup of VSEW. Customizing Toolbars You can customize toolbars in three ways: you can show or hide the built-in toolbars, you can add and remove buttons on existing toolbars, and you can create your own toolbars with buttons you often use. Enabling and Disabling Toolbars You disable and enable existing toolbars by right-clicking any existing toolbar or the menu bar and then selecting the appropriate item from the list. Once the toolbar is displayed, you can use its drag grip at its left to drag it to a new location within the Toolbar area. Editing Existing Toolbars If you feel that an existing toolbar is missing an important button or that it contains buttons you rarely use, you can customize the buttons on the toolbar. To do this, right-click any toolbar or the menu bar, choose Customize, switch to the Commands tab, and select the toolbar you want to modify from the Toolbar drop-down. With the command buttons at the right, you can add new and remove existing commands, or change their order. Creating Your Own Toolbars Creating your own toolbar is useful if you want to group some functions that you frequently use. To create a new toolbar, open the Customize window as explained in the preceding section. Click the New button and type a name for the toolbar. Then switch to the Commands tab and modify your toolbar as you would do with existing toolbars. Customizing Keyboard Shortcuts Another setting many developers like to change is keyboard shortcuts. Keyboard shortcuts are a great way to save time because they enable you to perform a task with a simple keyboard command instead of reaching for the mouse and selecting the appropriate item from the menu. To change the keyboard shortcuts, choose Tools Í Options, expand Environment, and click Keyboard. Locate the command for which you want to change the shortcut in the list of commands. Because this list contains many items, you can filter the list by typing a few letters from the command. For example, typing print in the Show Commands Containing field gives you a list of all print-related commands. Next, in the Press Shortcut Keys field, type a new shortcut and click Assign. Visual Studio enables you to enter a double shortcut key for a single command. For example, you can bind the command Close All Documents to the command Ctrl+K, Ctrl+O. To perform this command, you need to press c01.indd 27c01.indd 27 10/8/2012 9:39:24 AM10/8/2012 9:39:24 AM
    • 28 x CHAPTER 1 GETTING STARTED WITH ASP.NET 4.5 both key combinations in rapid succession. Although a double shortcut key may seem like overkill, it greatly increases the number of available shortcut keys. Resetting Your Changes Don’t worry if you feel that you have messed up Visual Studio by trying out the numerous custom- ization options. You have many ways to restore Visual Studio to its previous state. Resetting the Window Layout The command Reset Window Layout, accessible from the Window menu, resets all windows to the position they were in when you first started Visual Studio. This command is useful if you misplaced too many windows and ended up with a cluttered IDE. Resetting the Toolbox If you removed an item from the Toolbox by mistake or even deleted an entire tab, you can reset the Toolbox to its original state by right-clicking the Toolbox and choosing Reset Toolbox. You need to think twice before you use this command because it also deletes all your custom code snippets. Resetting All Settings If you followed along with the previous Try It Out exercises, and then started experimenting with the customization possibilities, your IDE is now probably in one of two states: It either looks exactly the way you want it, or it looks like a complete mess. In the latter case, it’s good to know that it is easy to clean up the chaos. To completely revert all Visual Studio settings to the way they were right after installation, choose Tools Í Settings Í Import and Export Settings or Tools Í Import and Export Settings, depending on the version of VS you’re using. Then choose the Reset All Settings option and click Next. If you want, you can create a backup of the existing settings; otherwise, choose No, Just Reset Settings. You get another screen that enables you to choose among a number of settings collections. Choose Expert Settings or Web Development because these options give you access to all the features you need to follow along with this book. Finally, click Finish. This action causes all settings to be reset to their defaults, including the window layout, Toolbox and Toolbox customizations, shortcut keys, and everything you may have changed in the Visual Studio Options dialog box. So, use this com- mand only when you’re really sure you want a fresh, new setup of Visual Studio. With some basic knowledge about ASP.NET pages and Visual Studio, it’s time for some real action. In the next chapter, you see how to create ASP.NET websites and web pages in much more detail. You learn how to organize your site in a logical and structured way, how to add the many different types of files to your site and how to use them, and how to connect the pages in your site. However, before you proceed to the next chapter, there is one more important topic you need to look at: the sample application that comes with this book. THE SAMPLE APPLICATION Building websites is what this book is all about, so it makes a whole lot of sense that this book comes with a complete and functional sample site that is used to showcase many of the capabilities of ASP.NET. c01.indd 28c01.indd 28 10/8/2012 9:39:24 AM10/8/2012 9:39:24 AM
    • The Sample Application x 29 The sample site you build in this book is called Planet Wrox, a site that serves as an online commu- nity for people interested in music. The site offers the following features to its visitors: ‰ Reviews about CDs and concerts that have been posted on the site by the administrator. ‰ The Gig Pics section, an online photo album where users can share pictures taken at concerts. ‰ The ability to switch between the different graphical themes that the site offers, giving you a chance to change the look and feel of the site without altering the content. ‰ The ability to store musical preferences that influence the information users see on the site. ‰ Access to bonus features for registered users. The site enables the administrator (that is, you, the owner of the site) to do the following: ‰ Add and maintain the reviews. ‰ Manage the different musical genres in the system. ‰ Manage photo albums created by visitors to the site. Figure 1-15 shows the Planet Wrox homepage. FIGURE 1-15 Figure 1-16 shows another page from Planet Wrox, but with a different theme applied. This page enables users to enter their personal information and specify preferences with regard to their favor- ite musical genres. c01.indd 29c01.indd 29 10/8/2012 9:39:24 AM10/8/2012 9:39:24 AM
    • 30 x CHAPTER 1 GETTING STARTED WITH ASP.NET 4.5 FIGURE 1-16 You can find an online running example of the site at www.PlanetWrox.com. There you can play around with the site from an end user’s perspective. You can also download the source for the sample application and all other examples from this book from the Wrox website at www.wrox.com/remtitle.cgi?isbn=1118311809. By the end of this book, you’ll be able to build all of the functionality from the sample site (and hopefully even more) in other websites. Don’t worry if it sounds like an awful lot of complex things. I guide you, step by step, from the beginning of the application all the way to the last feature. As long as you keep having fun doing this, I’m sure you’ll make it all the way. PRACTICAL TIPS ON VISUAL STUDIO Most of the chapters in this book end with a short section of useful tips. These are tips that either didn’t fit in anywhere in the text or encourage you to further explore or test out things. Sometimes they may seem irrelevant or hard to understand at first, but you’ll find that as you make your way through this book and look back at tips from previous chapters, things start to make sense. Don’t worry if you don’t understand certain things completely the first time you see them. Give the idea some thought and revisit the topic a few days later. Hopefully, by letting the ideas sink in a little, things start to make more sense automatically. This applies not only to the Practical Tips section, but to the entire book. c01.indd 30c01.indd 30 10/8/2012 9:39:24 AM10/8/2012 9:39:24 AM
    • Summary x 31 ‰ Before you move on to the next chapter, play around with Visual Studio some more. Add a couple of pages to your site, drag and drop some controls from the Toolbox onto your pages, and view them in your browser. That way, you’ll have a better understanding of the tools and the many controls available when you start the next chapter. ‰ Familiarize yourself with the many options to tweak the Visual Studio IDE. When building websites, you spend most of your time in this IDE, so it makes sense to tweak it as much as possible to your liking. Don’t be afraid to mess it up; you can always revert to previous settings. ‰ Take some time to browse through the settings you find in the Options dialog box of Visual Studio (accessible through the Tools Í Options menu). Many of the settings are self-explana- tory and can really help in further tweaking the IDE. SUMMARY This chapter covered a lot of important ground to get you started with ASP.NET 4.5 and Visual Studio. It started off with a brief history of the Microsoft .NET Framework in general and ASP .NET in particular. You then learned how to acquire and install Visual Studio, which is the most extensive and versatile tool available for creating ASP.NET 4.5 web pages. To enable you to work with it effectively, this chapter showed you how to use and customize the main features of the IDE. In subsequent chapters, you use and extend this knowledge to work with the many tools found in VS. It’s important to understand how a page in Visual Studio makes it to your web browser. Some knowledge of the web server that serves the request and how the page is processed to deliver the final HTML in the browser is critical to understanding ASP.NET. This chapter gave you a short introduction to the way a web page is requested and served to the browser. In the next chapter, you get a much more detailed explanation of creating websites. EXERCISES 1. Explain the differences between the markup of a page in Visual Studio and the final HTML page in the browser. 2. Imagine you have a number of HTML fragments that you expect to use a lot throughout the site. What’s the best way to make these fragments available in Visual Studio? 3. Name three ways you can reset some or all of the IDE customization settings. 4. If you want to change the property of a control on your page, for example the text of a button, which two options do you have available to make the change? You can find answers to these exercises in Appendix A. c01.indd 31c01.indd 31 10/8/2012 9:39:24 AM10/8/2012 9:39:24 AM
    • 32 x CHAPTER 1 GETTING STARTED WITH ASP.NET 4.5 WHAT YOU LEARNED IN THIS CHAPTER Attribute Extra information in a tag to define or change its behavior Element A pair of tags holding some text or other content HTML HyperText Markup Language: the language that browsers use to display a web page HTTP HyperText Transfer Protocol: the protocol by which web browsers and web servers communicate IDE Integrated development environment: an integrated collection of applica- tions and tools to develop applications JavaScript A programming language used to interact with a web page in the client’s browser Tag Text surrounded by angle brackets to create HTML elements Visual Studio 2012 The development environment to build .NET applications Visual Studio Express 2012 for Web The free version of Visual Studio that enables you to build ASP.NET web applications c01.indd 32c01.indd 32 10/8/2012 9:39:24 AM10/8/2012 9:39:24 AM
    • Building an ASP.NET Website WHAT YOU WILL LEARN IN THIS CHAPTER: ‰ The different project types you can choose from as a starting point for your ASP.NET websites ‰ The different project templates that are available to jump-start your site development ‰ The numerous file types available in ASP.NET and what they are used for ‰ Ways to create structured websites that are easy to manage, now and in the future ‰ How to use the designer tools to create formatted web pages WROX.COM CODE DOWNLOADS FOR THIS CHAPTER You can find the wrox.com code downloads for this chapter on the Download Code tab at www.wrox.com/remtitle.cgi?isbn=1118311809. The code is in the Chapter 2 download. To create good-looking, functional, and successful websites, you have to understand a number of important technologies and languages, including HyperText Markup Language (HTML), ASP.NET, cascading style sheets (CSS), a server-side programming language such as C# or VB, and a client-side language such as JavaScript. This and upcoming chapters provide a solid foundation in these technologies, so you should be comfortable with the most important con- cepts once you’ve finished this book. Besides these technologies, you also have to understand the Visual Studio IDE that was intro- duced in the previous chapter. You need to know how to create sites, add pages, and manage all the toolbars and windows that Visual Studio (VS) offers you. In addition, you need to know how to build and design web pages in VS with HTML and server controls. 2 c02.indd 33c02.indd 33 10/8/2012 9:43:36 AM10/8/2012 9:43:36 AM
    • 34 x CHAPTER 2 BUILDING AN ASP.NET WEBSITE This chapter shows you, in detail, how to create and manage your websites. It also shows you how to create your ASP.NET web pages and add markup to them, enabling you to create useful web pages that can present information to users and react to their response. Although you already created your first ASP.NET website in the previous chapter, this chapter starts off with another in-depth look at creating a new website. Because you have many choices to make when you start a new site, it’s important to understand all the different options and pick the right one for your scenario. CREATING WEBSITES WITH VISUAL STUDIO 2012 The preceding chapter gave you a quick overview of creating a website in VS. You simply chose New Web Site from the File menu, selected a language, selected the standard ASP.NET Web Forms Site template, and clicked OK. However, there’s more to the New Web Site dialog box than you saw in the previous chapter. You may have noticed that you can choose among a number of different tem- plates that enable you to create different kinds of sites. But before looking at the different templates on which you can base your new website, you need to know a little more about the different project types that are available in VS. Different Project Types In Visual Studio 2012 you can choose between two types of projects for creating ASP.NET Web Forms websites: Web Application Projects and Web Site Projects. Web Application Projects Web Application Projects make it easier for developers who work in teams or who need more con- trol over the contents of the site and their compilation and deployment processes to build websites with VS. The whole website is managed as a project, with a single project file that keeps track of all the content of the website. In VS, you create a new Web Application Project through the File Í New Project dialog box. In that dialog box, click your preferred programming language (either Visual Basic or Visual C#) and click the Web category, where you’ll find a number of ASP.NET web application templates. One of the available project templates is the ASP.NET MVC 4 Web Application, which creates an application based on the Model View Controller pattern, another popular style of web application development. MVC is not used or discussed in this book, but if you want to learn more, check out www.asp.net/mvc. Web Site Projects Web Site Projects represent a project in VS for a website. You create a new Web Site Project by choosing File Í New Web Site or File Í New Í Web Site from Visual Studio’s main menu. A Web Site Project site is simply a Windows folder with a bunch of files and subfolders in it. There is no collective file (known as the project file with a .vbproj or .csproj extension) that keeps track of all the individual files in the website. You just point VS to a folder, and it instantly opens it as a website. This makes it very easy to create copies of the site, move them, and share them with others, because no dependencies exist with files on your local system. Because of the lack of a central project file, Web Site Projects are usually simply referred to as websites, which is the term I use in the remainder of this book. c02.indd 34c02.indd 34 10/8/2012 9:43:42 AM10/8/2012 9:43:42 AM
    • Creating Websites with Visual Studio 2012 x 35 Choosing between Web Site Projects and Web Application Projects Because you have two options to choose from, you may be wondering which project type you should pick. In general, the Web Site Project is a bit easier to work with. Because it’s just a folder, it’s easier to copy the files to a different location, such as another development workstation or a production server. Also, changes to the code files are picked up by the web server and applied automatically without a formal deployment process. The Web Application Project, on the other hand, works better if you work with a team of developers on the same site, because it dictates a more formal develop- ment and deployment process and has better support for working with Source Control versioning systems, such as Microsoft’s Team Foundation Server. This book uses the Web Site Project model because it’s easier to work with if you’re new to ASP .NET. However, you’ll find that sites built using the Web Application Project model have a lot in common with Web Site Projects, which means you can use the knowledge you gain from this book to build sites with the Web Application Project model as well. You must use the Web Site Project model if you want to follow along with this book. When not referring to a specific project type, I’ll use the terms website and web application interchangeably throughout this book when referring to websites in general. Now that you know about the different project models, the next thing to consider is the different website templates and their options. Choosing the Right Website Template The New Web Site dialog box in VS contains different website templates, each one serving a distinct purpose. Figure 2-1 shows the New Web Site dialog box in VS. You can open this dialog box by choosing File Í New Web Site or File Í New Í Web Site, depending on your version of VS. If your dialog box doesn’t look like Figure 2-1, make sure you chose File Í New Web Site and not File Í New Project. FIGURE 2-1 c02.indd 35c02.indd 35 10/8/2012 9:43:42 AM10/8/2012 9:43:42 AM
    • 36 x CHAPTER 2 BUILDING AN ASP.NET WEBSITE In the left-hand section you can choose between Visual Basic and Visual C# as the programming language for your site. The section in the middle shows the ASP.NET website templates that are installed by default. Each of them is discussed in the next section. When you have created your own templates (which you learn how to do in Chapter 6), or have templates installed from other parties, they show up in this area as well. The ASP.NET Empty Web Site template is used throughout this book for the Planet Wrox website. The others are described briefly in the following sections so you know how they can be used. The exact list of installed templates on your system depends on the version of Visual Studio and the installed components. Don’t worry if you have other templates as long as you have the ASP.NET Web Forms Site and the ASP.NET Empty Web Site items. ASP.NET Web Forms Site This template enables you to set up a basic ASP.NET website. It contains a number of files and fold- ers to jump-start the development of your site. The different file types are all discussed later in this chapter. The special App_Data folder and the functionality of the pages in the Account folder are discussed later in this book. This template is a good starting point once you start developing real-world ASP.NET websites. ASP.NET Web Site (Razor v1 / Razor v2) You use these templates to create sites using Microsoft’s Web Pages framework. You can learn more about Web Pages in my book Beginning ASP.NET Web Pages with WebMatrix (Wrox, 2011, ISBN: 978-1-118-05048-4). ASP.NET Empty Web Site The ASP.NET Empty Web Site template gives you nothing but a single configuration file (Web .config). The ASP.NET Empty Web Site template is useful if you have a bunch of existing files you want to use to create a new website or when you want to create your site from scratch. You use this template as the basis for the sample website you build in the book and add files and folders as you progress through the book. ASP.NET Dynamic Data Entities Web Site This template enables you to create a flexible yet powerful website to manage data in a database without a lot of manual code. This template is not discussed in this book, but you learn more about the Microsoft ADO.NET Entity Framework that is used by the template in Chapter 14. WCF Service This template enables you to create a website containing one or more Windows Communication Foundation (WCF) Services. A WCF Service is somewhat similar to a web service in that it enables you to create methods that are callable over a network. However, WCF Services go much further than simple web services and offer you a lot more flexibility. You see how to create and consume a web service from a browser in Chapter 10. c02.indd 36c02.indd 36 10/8/2012 9:43:42 AM10/8/2012 9:43:42 AM
    • Creating Websites with Visual Studio 2012 x 37 Although it seems you have to make a clear choice up front for the right website template, this isn’t really the case. Because an ASP.NET website in VS is essentially just a reference to a folder, it’s easy to add types from one template to another. For example, it’s perfectly acceptable (and very common) to add a web service file to a standard ASP.NET Web Forms Site or an ASP.NET Empty Web Site, as you see in Chapter 10. Creating and Opening a New Website You have a number of different ways to create new and open existing websites. The choices you have here are largely influenced by the way you access the website (either on your local machine with Visual Studio on it or on a remote machine), and whether you want to use IIS Express (the built-in web server that ships with VS) or the full version of IIS—the web server that comes with Windows. All the examples in this book assume that you open sites from your local hard drive and that you use IIS Express, a trimmed down version of IIS, because it’s very convenient to develop sites with it. However, Chapter 19 shows you how to use and configure the full version of Internet Information Services, or IIS for short. This advanced web server comes with most editions of Windows and is mostly used for production hosting of your websites on the server editions of Windows, because it’s capable of serving web pages in high-traffic scenarios. Creating New Websites The next Try It Out section guides you through creating the Planet Wrox website, which is the proj- ect you work on in this book. All exercises in the remainder of the book assume you have this web- site open in VS, except where stated otherwise. The exercise instructs you to store your website in a folder called C:BegASPNETSite. Take note of this folder name, because it’s used throughout this book. If you decide to use a different folder, be sure to use your own location whenever you see this folder name in the book. Also make sure you don’t use special characters like the hash (#) or insert a space in the folder name because you’ll run into trouble when developing your site. Finally, make sure you don’t create this folder under your Windows Documents folder (typically at C:Users UserNameDocuments), because you’ll run into problems later when accounts other than your own need access to your site. TRY IT OUT Creating a New ASP.NET 4.5 Website 1. Start by creating a folder called BegASPNET in the root of your C drive using Windows Explorer or My Computer. Inside the folder, create another folder called Site. You should end up with a folder called C:BegASPNETSite. If you followed the instructions from the “Introduction” sec- tion of this book and unpacked the source for this book, you already have the BegASPNET folder, which in turn contains the Source and Resources folders. You still need to create the Site folder, though. If you want to follow along with VB.NET and C# at the same time, you can create two folders, BegASPNETVB and BegASPNETCS, and use two instances of Visual Studio. 2. Start Visual Studio and choose File Í New Web Site or File Í New Í Web Site, depending on your version of VS. c02.indd 37c02.indd 37 10/8/2012 9:43:42 AM10/8/2012 9:43:42 AM
    • 38 x CHAPTER 2 BUILDING AN ASP.NET WEBSITE COMMON MISTAKES Don’t mistakenly create a new Web Application Project using File Í New Project, because this project template is not compatible with the exercises in this book. 3. In the target framework drop-down list at the top of the screen, select .NET Framework 4.5. 4. In the Installed Templates area on the left, choose between Visual Basic and Visual C#. All the examples in this book are shown in both programming languages, so you can choose the one you like best. 5. In the area in the middle select ASP.NET Empty Web Site. 6. In the Web Location drop-down list, make sure that File System is selected. The other two options (HTTP and FTP) enable you to open a site running on IIS (either on your local machine or on a remote server using the so-called Microsoft FrontPage Server Extensions) and open a site from an FTP server, respectively. 7. Click the Browse button next to the location text box, browse to C:BegASPNETSite (the folder you created in the first step of this exercise), and click Open. Your final screen should look like the one in Figure 2-2, except that you may have chosen Visual C# instead of Visual Basic. FIGURE 2-2 8. Click OK and VS creates the new site for you. c02.indd 38c02.indd 38 10/8/2012 9:43:42 AM10/8/2012 9:43:42 AM
    • Creating Websites with Visual Studio 2012 x 39 How It Works As soon as you click OK, VS creates a new, empty website for you. This new website contains nothing but a configuration file (called Web.con- fig). In the Solution Explorer, your website now looks like Figure 2-3. If you don’t see the top-level Solution node, choose Tools Í Options in VS, and in the Projects and Solutions category select Always Show Solution. Because a website based on the Empty Web Site template is just a simple Windows folder that VS looks at, the actual folder on disk contains the same file. No additional files are used to create the site, as shown in Figure 2-4, which shows File Explorer displaying the files in the folder C:BegASPNETSite. FIGURE 2-4 If you don’t see the .config extension of the web file, don’t worry. You see how to view file exten- sions in a later exercise. As you progress through this book, you’ll add new files and folders to the site. These additional files and folders show up in the Solution Explorer and will appear in the Windows folder at C: BegASPNETSite as well. Opening websites based on the Web Site Project template is very similar to creating new ones. In the next section, you get a quick overview of opening existing sites in VS. Opening Existing Websites Just as with creating new sites, opening an existing site in VS gives you a few options with regard to the source location of the website. You can choose to open a site from the local filesystem, from a local IIS web server, from a remote server using FTP, from a remote site using the Microsoft FrontPage Server Extensions, or from a central Source Control system such as Microsoft’s Team Foundation Server. Figure 2-5 shows the Open Web Site dialog box in VS. FIGURE 2-3 c02.indd 39c02.indd 39 10/8/2012 9:43:43 AM10/8/2012 9:43:43 AM
    • 40 x CHAPTER 2 BUILDING AN ASP.NET WEBSITE FIGURE 2-5 To get to this dialog box, choose File Í Open Web Site in VS (don’t accidentally choose File Í Open Project because that menu item is used to open Web Application Projects instead). All the examples in the book assume that you always open the Planet Wrox website from the local filesystem, using the File System button, which is the first button in the left column of the window. Then in the right pane, locate your website (C:BegASPNETSite in this example) and click the Open button. The site you created in the previous Try It Out is a very bare-bones site. To make it more useful, you need to add files to it. The many file types you have at your disposal and the way they are added to the site are the next topics of discussion. WORKING WITH FILES IN YOUR WEBSITE An ASP.NET 4.5 Web Forms Site consists of at least a single Web Form (a file with an .aspx exten- sion), but usually it consists of a larger number of files. Many different file types are available in VS, each offering a distinct functionality. In the next section, you see the most important file types that are used in VS. In addition, you learn a few different ways to add these files to your site. c02.indd 40c02.indd 40 10/8/2012 9:43:43 AM10/8/2012 9:43:43 AM
    • Working with Files in Your Website x 41 The Many File Types of an ASP.NET 4.5 Website To give you an idea of how many different files you can use in ASP.NET, Figure 2-6 shows the dia- log box that enables you to add new files to the site (accessible by right-clicking your website in the Solution Explorer and choosing Add Í Add New Item or by choosing Website Í Add New Item from the main menu). FIGURE 2-6 To make it easier to find the type of file you’re looking for, you can use the search box at the top- right corner of the dialog box. Simply enter a few letters of the type you’re looking for and hit Enter. VS filters the list of files to those matching your search phrase. The files you can add to a site can be grouped in a few different categories. The most important files—the ones you use throughout the examples in this book—are discussed next. Web Files Web files are specific to web applications and can either be requested by a browser directly, or are used to build up part of the web page that is requested in the browser. The following table lists the various web files you typically use in an ASP.NET Web Forms website and their extensions, and describes how each file is used. c02.indd 41c02.indd 41 10/8/2012 9:43:43 AM10/8/2012 9:43:43 AM DownloadfromWow!eBook<www.wowebook.com>
    • 42 x CHAPTER 2 BUILDING AN ASP.NET WEBSITE FILE TYPE EXTENSION DESCRIPTION Web Form .aspx The workhorse of any ASP.NET website; represents the pages that your users view in their browsers. Master Page .master Enables you to define the global structure and the look and feel of a website. You see how it can be used in Chapter 6. Web User Control .ascx Contains page fragments that can be reused in multiple pages in your site. Chapter 8 is entirely devoted to user controls. HTML Page .htm /.html Can be used to display static HTML in your website. Style Sheet .css Contains CSS code that enables you to style and format your website. You learn more about CSS in Chapter 3. Web Configuration File .config Contains global configuration information that is used throughout the site. You see how to use the Web.config later in this book, starting with Chapter 4. Site Map .sitemap Contains a hierarchical representation of files in your site in an XML format. The site map is used for navigation and is discussed in Chapter 7. JavaScript File .js Contains JavaScript that can be executed in the client’s browser. Skin File .skin Contains design information for controls in your website. Skins are discussed in Chapter 6. The next Try It Out exercise shows you how to add a new master page to the site, which is used throughout the book. TRY IT OUT Adding Files to Your Site 1. If it is not still open, open the Planet Wrox website you created earlier by choosing File Í Open Web Site. Make sure that you open the site from the filesystem, locate the folder that contains your site (C:BegASPNETSite), and click the Open button. 2. In the Solution Explorer, right-click your site and choose Add Í New Folder. COMMON MISTAKES Make sure you click the actual site and not the Web.config file or the Solution node at the top (see Figure 2-3) or you won’t get the correct menu item. c02.indd 42c02.indd 42 10/8/2012 9:43:43 AM10/8/2012 9:43:43 AM
    • Working with Files in Your Website x 43 3. Type MasterPages as the name of the folder and press Enter. Then right-click this new folder and choose Add Í Add New Item. Alternatively, you can choose File Í New File or Website Í Add New Item from Visual Studio’s main menu, or you can click the new folder in the Solution Explorer once to put the focus on it and then press Ctrl+Shift+A. 4. In the dialog box that appears, click Master Page and type Frontend as the name. VS automati- cally adds the .master extension for you when you add the file. Verify that under Installed Templates you have selected the language you want to use for this site and that Place Code in Separate File in the bottom-right corner is checked. Finally, click the Add button. The master page is added to the site, and is opened automatically for you in the Document Window. How It Works This simple exercise showed you how to add a new item to your website. Although at this stage the site isn’t very exciting yet, the file you added forms the basis for the rest of the book. The next sections briefly look at the remainder of the file types. Code Files Adding code files to the site is identical to how you add web files. The following table describes the various types of code files. FILE TYPE EXTENSION DESCRIPTION WCF Service .svc Can be called by other systems, including browsers, and can contain code that can be executed on your server. WCF services are covered in Chapter 10. Class .cs /.vb Can contain code to program your website. Note that Code Behind files (discussed later) also have this extension because they are essentially class files. C# uses files with the .cs extension and Visual Basic uses .vb files. Global Application Class .asax Can contain code that is fired in response to interesting things that happen in your site, such as the start of the application or when an error occurs somewhere in the site. You see how to use this file in Chapters 11 and 18. Besides the Code Files category, there is one more group of files worth looking into: Data Files. c02.indd 43c02.indd 43 10/8/2012 9:43:44 AM10/8/2012 9:43:44 AM
    • 44 x CHAPTER 2 BUILDING AN ASP.NET WEBSITE Data Files Data files are used to store data that can be used in your site and in other applications. The group consists of the XML files, database files, and files related to working with data. FILE TYPE EXTENSION DESCRIPTION XML File .xml Used to store data in XML format. In addition to plain XML files, ASP.NET supports a few more XML-based files, two of which you briefly saw before: Web.config and the site map. SQL Server Database .mdf Files with an .mdf extension are databases that are used by Microsoft SQL Server. Databases are discussed in Chapter 12 and later. ADO.NET Entity Data Model .edmx Used to access databases declaratively, without the need to write a lot of repetitive code. Technically, this is not a data file, because it does not contain the actual data. However, because it is tied to the database so closely, it makes sense to group it under this header. You learn more about the ADO.NET Entity Framework in Chapter 14. As you saw in the previous Try It Out, adding a new file of any of these types is really easy. It’s just as easy to add existing files to the site. Adding Existing Files Not every file you create in your website has to be brand new. In some cases it makes sense to reuse files from other projects. For example, you may want to reuse a logo or a CSS file across multiple sites. You can easily add existing files by right-clicking the website in the Solution Explorer and choosing Add Í Add Existing Item. In the dialog box that appears, you can browse for the files, and optionally select multiple files by holding down the Ctrl key. Finally, when you click Add, the files are added to the website. You can also use copy and paste to copy files from a folder on your local disk to a website in VS. Simply highlight the files in Windows Explorer, press Ctrl+C to copy the files, switch to VS, click the website in the Solution Explorer (or on a subfolder of your site), and press Ctrl+V. The files are then copied into your website’s folder. However, there is an even easier way to add files to the site, which can be a great time saver when you need to add multiple existing files and folders to your site: drag and drop. The following Try It Out shows you how this works. TRY IT OUT Adding Existing Files to Your Site 1. In Windows, minimize all open applications, right-click your desktop, and choose New Í Text Document. If you don’t see this option, simply create a new text document using Notepad and save it on your desktop. c02.indd 44c02.indd 44 10/8/2012 9:43:44 AM10/8/2012 9:43:44 AM
    • Working with Files in Your Website x 45 2. Rename the file Styles.css. Make sure the .txt extension is replaced by .css. If you don’t see the initial .txt extension and the icon of the file doesn’t change from a text file to a CSS file (by default this is the same icon as a text file with a gear symbol on top of it, but you may have soft- ware installed that changed the icon for CSS files), Windows is configured to hide extensions for known file types. If that’s the case, open up Windows Explorer in Windows 7, click the Organize button, and then choose Folder and Search Options. Switch to the View tab and deselect the option labeled Hide Extensions for Known File Types. For Windows 8 you find the option called File Name Extensions on the View tab of the Ribbon bar of the File Explorer, shown in Figure 2-4. You now may need to change the name of the file from Styles.css.txt to Styles.css. When you change the file extension from .txt to .css, Windows may give you a warning that the file becomes unusable if you proceed. You can safely answer Yes to this question to continue. 3. Rearrange VS so you can see part of the desktop with the CSS file as well. You can use the Restore Down button next to the Close button on the Windows title bar of VS to get it out of full screen mode. 4. Click the CSS file on the desktop and, while holding down the mouse button, drag the file into the Solution Explorer. Make sure you drag the file into the Solution Explorer and not into other parts of VS, or the file won’t be added. For example, when you drag it into the Document Window, VS simply opens the file for you, but doesn’t add it to the site. 5. When you release the mouse while over the website node or an existing file in the Solution Explorer, the CSS file is added to your site. NOTE If you are using Windows 7 and run VS as an administrator, this might not work because Windows doesn’t allow the Windows Explorer and VS to com- municate. In that case, add existing files using the Add Existing Item menu dis- cussed earlier or use copy and paste. How It Works Although this seems to be a simple exercise that uses basic Windows skills, it serves to show that VS creates a copy of the file when it adds it to the site. So, the original Styles.css file on the desktop is not affected when you make changes to the copy in VS. This way, it’s easy to drag and drop files from existing websites into your new one without affecting the originals. The same applies to files you add using the Add Existing Item dialog box in VS. If you have added files to your website’s folder outside of VS, they may not show up right away. You can get a fresh copy of the file list by clicking the Refresh button on the Solution Explorer’s toolbar. c02.indd 45c02.indd 45 10/8/2012 9:43:44 AM10/8/2012 9:43:44 AM
    • 46 x CHAPTER 2 BUILDING AN ASP.NET WEBSITE Organizing Your Site Because of the many files that make up your site, it’s often a good idea to group them by function in separate folders. For example, all style sheet files could go in a folder called Styles, .js files could go in Scripts, user controls could go in a Controls folder, and master pages could be stored in a folder called MasterPages. This is a matter of personal preference, but structured and well-orga- nized sites are easier to manage and understand. The next Try It Out explains how you can move files around into new folders to organize your site. TRY IT OUT Organizing Your Website 1. Right-click the Planet Wrox site in the Solution Explorer and choose Add Í New Folder. 2. Type Styles as the new folder name and press Enter. 3. Create another folder, called Controls. These two folders are used in the remainder of this book. 4. Drag the Styles.css file that you added earlier and drop it into the Styles folder. If everything went well, your Solution Explorer should look like Figure 2-7. FIGURE 2-7 If your Solution Explorer looks different from the one shown in Figure 2-7, follow this Try It Out again until your site looks exactly the same, with the same folder structure and files in it. Future Try It Out exercises in this book assume you have the correct folders and files in your website. How It Works Structure and organization are important to keep your sites manageable. Although you may be tempted to add all of your files to the root of your project, it’s better not to do this. With a very small site, you may not notice any difference, but as soon as your site begins to grow, you’ll find it becomes a lot harder to manage when it lacks structure. Placing related files in separate folders is the first step to an organized site. Storing files of the same type in a single folder is only one way to optimize your site. In later chapters, you see that separate folders are also used to group files with similar functionality. For example, all files that are accessible only by an administrator of the site are grouped in a folder called Management. c02.indd 46c02.indd 46 10/8/2012 9:43:44 AM10/8/2012 9:43:44 AM
    • Working with Web Forms x 47 The drag-and-drop features of VS make it easy to reorganize your site. Simply pick up one file or multiple files and drop them in their new location. If you continue to apply these kinds of organiza- tion practices while expanding your site, you’ll find that tomorrow or six months from now, you won’t have any problems locating the right file when you need it. Special File Types Some of the files listed in the previous section require that you put them in a special folder instead of the proposed optional organizational folder structure. The IDE warns you when you try to add a file outside of its special folder, and offers to create the folder and put the file there. For example, when you try to add a class file (with a .vb or .cs extension), you get the warning shown in Figure 2-8. FIGURE 2-8 When you get this dialog box, always click Yes. Otherwise, your file won’t function correctly. You get similar dialog boxes for other file types, including skin and database files. Now that you have a good understanding of the different types of files that make up your website, it’s time to look at one of them in much more detail: .aspx files, also known as Web Forms. WORKING WITH WEB FORMS Web Forms, represented by .aspx files, are the core of any ASP.NET 4.5 Web Forms website. They are the actual pages that users see in their browsers when they visit your site. As you saw in the previous chapter, Web Forms can contain a mix of HTML, ASP.NET Server Controls, client-side JavaScript, CSS, and programming logic. To make it easier to see how all this code ends up in the browser, VS offers a number of different views on your pages. The Different Views on Web Forms VS enables you to look at your Web Form from a few different angles. When you have a file with markup—like a Web Form or master page—open in the Document Window, you see three buttons at the bottom-left corner of the window. With these buttons, visible in Figure 2-9, you can switch between the different views. This figure shows a master page, which you’ll learn more about in Chapter 6. c02.indd 47c02.indd 47 10/8/2012 9:43:44 AM10/8/2012 9:43:44 AM
    • 48 x CHAPTER 2 BUILDING AN ASP.NET WEBSITE FIGURE 2-9 Source View is the default view when you open a page. It shows you the raw HTML and other markup for the page, and is very useful if you want to tweak the contents of a page and you have a good idea of what you want to change and where. As I explained in the previous chapter, I use the term Markup View rather than Source View to refer to the markup of ASPX and HTML pages. The Design button enables you to switch the Document Window into Design View, which gives you an idea of how the page will end up. When in Design View, you can use the Visual Aids and Formatting Marks submenus from the main View menu to control visual markers like line breaks, borders, and spaces. Both submenus offer a menu item called Show that enables you to turn all the visual aids on or off at once. Turning both off is useful if you want to have an idea of how the page ends up in the browser. You should, however, use Design View only to get an idea of how the page will end up. Although VS has a great rendering engine that renders the page in Design View pretty well, you should always check your pages in different browsers as well, because what you see in VS is the markup for the page before it gets processed. Server controls on the page may emit HTML that changes the look of the page in the browser. Therefore, it’s recommended to view the page in the browser as often as possible so you can check if it’s going to look the way you want it. It’s also recommended to test your site in as many different browsers as you can get your hands on, because there may be small differences between them in the way they render a web page. The Planet Wrox website has been developed and tested against recent versions of Microsoft Internet Explorer, Firefox, Google Chrome, Safari, and Opera. You’ll see screenshots of these browsers at various places in the book. The Split button enables you to look at Design View and Markup View at the same time, as you can see in Figure 2-10. Split View is great if you want to see the code that VS generates when you add controls to the Design View of your page. The other way around is very useful too: When you make changes to the markup of the page in Markup View, you can see how it ends up in Design View. Sometimes Design View becomes out of sync with Markup View. If that’s the case, a message appears at the top of Design View. Simply clicking the message or saving the entire page is enough to update the Design window. c02.indd 48c02.indd 48 10/8/2012 9:43:44 AM10/8/2012 9:43:44 AM
    • Working with Web Forms x 49 FIGURE 2-10 You can cycle through the three different modes using the Ctrl+Page Up and Ctrl+Page Down keys. If you want your pages to open in a different view than Markup View, choose Tools Í Options. Then expand HTML Designer, and in the General category, set your preferred view. Alternatively, enter HTML Designer General in the Quick Launch text box (which you can access by pressing Ctrl+Q) at the top-right of VS and then click the item in the list that appears. In addition to the HTML and other markup you see in the Markup View window, a Web Form can also contain code in either C# or Visual Basic .NET. Where this code is placed depends on the type of Web Form you create. The next section explains the two options you have in more detail. Choosing between Code Behind and Pages with Inline Code Web Forms come in two flavors: either as an .aspx file with a Code Behind file (a file named after the Web Form with an additional .vb or .cs extension) or as .aspx files that have their code embedded, often referred to as Web Forms with inline code. Although you won’t see much code until Chapter 5, it’s important to understand the difference between these types of Web Forms. At first, Web Forms with inline code seem a little easier to understand. Because the code needed to program your website is part of the very same Web Form, you can clearly see how the code relates to the file. However, as your page gets larger and you add more functionality to it, it’s often easier if you have the code in a separate file. That way, it’s completely separate from the markup, enabling you to focus on the task at hand. In the next exercise, you add two files that demonstrate the difference between Code Behind and inline code. TRY IT OUT Adding Web Forms with Code to Your Site The files you add in this exercise aren’t needed for the final application. To avoid cluttering up the proj- ect, you should put them in a separate Demos folder. c02.indd 49c02.indd 49 10/8/2012 9:43:45 AM10/8/2012 9:43:45 AM
    • 50 x CHAPTER 2 BUILDING AN ASP.NET WEBSITE 1. In the Solution Explorer, right-click your website and choose Add Í New Folder. Name the folder Demos and press Enter. 2. Right-click the Demos folder and choose Add Í Add New Item. In the dialog box that appears, choose your preferred programming language on the left, click the Web Form template, and name the file CodeBehind.aspx. Make sure that the check box for Place Code in Separate File is selected. Finally, click the Add button. The page should open in Markup View so you can see the HTML for the page. 3. At the bottom of the Document Window, click the Design button to switch the page from Markup View into Design View. The page you see has a white background with a small, dashed rectangle at the top of it. The dashed rectangle represents the <div> element you saw in Markup View. 4. From the Toolbox, drag a Label control from the Standard category and drop it in the dashed area of the page. Remember, you can open the Toolbox with the shortcut Ctrl+Alt+X if it isn’t open yet. In Design View, your screen should now look like Figure 2-11. FIGURE 2-11 5. Double-click somewhere in the white area below the dashed line of the <div> element. VS switches from Design View into the Code Behind of the file and adds code that fires when the page loads in the browser: VB.NET Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub C# protected void Page_Load(object sender, EventArgs e) { } Although this odd syntax may look a little scary at this point, don’t worry about it too much now. In most cases, VS adds it for you automatically, as you just saw. In later chapters, you see exactly how this code works, but for now it’s important to realize that the code you’re going to place between the lines that start with Protected Sub and End Sub in Visual Basic and between the curly braces in C# will be run when the page is requested in the browser. All code examples you see from now on include a Visual Basic (VB.NET) and a C# version, so always pick the one that matches your programming language. c02.indd 50c02.indd 50 10/8/2012 9:43:45 AM10/8/2012 9:43:45 AM
    • Working with Web Forms x 51 6. Place your cursor in the open line in the code that VS created and add the bolded line of code that assigns today’s date and time to the label, which will eventually show up in the browser: VB.NET Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load Label1.Text = "Hello World; the time is now " & DateTime.Now.ToString() End Sub C# protected void Page_Load(object sender, EventArgs e) { Label1.Text = "Hello World; the time is now " + DateTime.Now.ToString(); } Note that as soon as you type the L for Label1, you get a list with options to choose from. This is part of Visual Studio’s IntelliSense, a great tool that helps you rapidly write code. Instead of typ- ing the whole word Label1, you simply type the letter L or the letters La and then you pick the appropriate item from the list, visible in Figure 2-12. FIGURE 2-12 To complete the selected word, you can press Enter or Tab or even the period. In the latter case, you immediately get another list that enables you to pick the word Text simply by typing the first few letters, completing the word by pressing the Tab or Enter key. This feature is a real pro- ductivity tool because you can write code with a minimum of keystrokes. IntelliSense is avail- able in many other file types as well, including ASPX, HTML, CSS, JavaScript, and XML. In many cases, the list with options pops up automatically if you begin typing. If it doesn’t, press Ctrl+Spacebar to invoke it. If the list covers some of your code in the code window, press and hold the Ctrl key to make the window transparent. 7. Right-click the CodeBehind.aspx page in the Solution Explorer and choose View in Browser (Internet Explorer). Depending on the default browser you’ve configured for your computer, the browser name in the parentheses may be different. I’ll simply refer to this menu item as View in Browser from now on. 8. Click Yes if you get a dialog box that asks if you want to save the changes, and then the page will appear in the browser, similar to the browser window you see in Figure 2-13. c02.indd 51c02.indd 51 10/8/2012 9:43:45 AM10/8/2012 9:43:45 AM
    • 52 x CHAPTER 2 BUILDING AN ASP.NET WEBSITE FIGURE 2-13 If you don’t see the message with the date and time appear or you get an error on the page in the browser, make sure you saved the changes to all open pages. To save all pages at once, press Ctrl+Shift+S or click the Save All button on the toolbar (the one with the multiple floppy disk symbols). Additionally, make sure you typed the code for the right language. When you created this new page, you chose a programming language that applies to the entire page. You can’t mix languages on a single page, so if you started with a Visual C# page, make sure you entered the C# code snippet in step 6. 9. Setting up a page with inline code is very similar. Start by adding a new Web Form to the Demos folder. Call it CodeInline.aspx and make sure you uncheck the Place Code in Separate File option. 10. Just as you did in steps 3, 4, and 5, switch the page into Design View, drag a label inside the <div> element, and double-click the page somewhere outside the <div> that now contains the label. Instead of opening a Code Behind file, VS now switches your page into Markup View and adds the Page_Load code directly in the page. 11. On the empty line in the code block that VS inserted, type the bolded line you see in step 6 of this exercise. Make sure you use the correct programming language. You should end up with the fol- lowing code at the top of your .aspx file: VB.NET <script runat="server"> Protected Sub Page_Load(sender As Object, e As EventArgs) Label1.Text = "Hello World; the time is now " & DateTime.Now.ToString() End Sub </script> C# <script runat="server"> protected void Page_Load(object sender, EventArgs e) { Label1.Text = "Hello World; the time is now " + DateTime.Now.ToString(); } </script> 12. Right-click the page in the Solution Explorer and choose View in Browser. Alternatively, press Ctrl+F5 to open the page in your browser. You should see a page similar to the one you got in step 7. How It Works At run time, pages with inline code behave the same as pages that use Code Behind. In both cases, the ASP.NET run time sees the Page_Load code and executes any code it finds in it. In the Try It Out, this c02.indd 52c02.indd 52 10/8/2012 9:43:45 AM10/8/2012 9:43:45 AM
    • Working with Web Forms x 53 meant setting the Text of Label1 to a welcome message and today’s date and time. The biggest dif- ference between the two options is where the code is stored. With pages with inline code, all code and markup is stored in the same file on disk. When using Code Behind, the VB or C# code you write is stored in a separate file named after the Web Form. Because pages with Code Behind are easier to manage, I’ll use them exclusively for the Planet Wrox website. In this example, the C# code looks very similar to the VB.NET code. The code that sets the Label’s text is almost identical in the two languages. One difference is that VB.NET uses an ampersand (&) to glue two pieces of text together, but C# uses the plus (+) character. You can also use the plus char- acter in VB.NET to concatenate strings together, but with a few caveats, as you’ll learn in Chapter 5. The other difference is that in C# code lines must be terminated with a semicolon (;) to indicate the end of a unit of code, but Visual Basic uses the line break. If you want to split a long line of code over multiple lines in Visual Basic, you can use the underscore ( _) character. In earlier versions, VB.NET required the underscore in a lot of different places. However, in recent versions of Visual Basic, the designers of the language have greatly reduced the number of places where you must use an underscore. One place where you do need the underscore if you want to split code over multiple lines is right before the Handles keyword that you saw earlier: Protected Sub Page_Load(sender As Object, e As EventArgs) _ Handles Me.Load Label1.Text = "Hello World; the time is now " & DateTime.Now.ToString() End Sub Note that in your pages you don’t have to use the underscore to break a long line. However, I’ll add it to some of the examples in this book because the book’s pages are not wide enough to show the entire code statement on a single line. You’ll see more of these underscores in other Visual Basic examples in the remainder of this book. If you decide to manually type the underscore to make your own code more readable, don’t forget to type a space before the underscore or your code won’t work. In C#, you don’t need this character because the language itself allows you to break long lines simply by pressing Enter. This is because C# uses a semicolon to denote the end of a line instead of a line break in the source. You opened the page in your browser using the right-click View in Browser option or by pressing Ctrl+F5. With the View in Browser option, you always open the page you right-click. With the Ctrl+F5 shortcut, you open the page that is currently the active document in the Document Window, the page that is currently selected in the Solution Explorer, or the file that has been set as the Start Page for the website. Additionally, all open files are saved automatically, and the site is checked for errors before the requested page is opened in the browser. You can assign a page as the Start Page by right-clicking it in the Solution Explorer and choosing Set As Start Page. If you want to control this behavior at a later stage, right-click the website in the Solution Explorer and choose Property Pages. In the Start Options category, you can indicate that you want the currently active page to open, or you can assign a specific page, as shown in Figure 2-14. c02.indd 53c02.indd 53 10/8/2012 9:43:46 AM10/8/2012 9:43:46 AM
    • 54 x CHAPTER 2 BUILDING AN ASP.NET WEBSITE FIGURE 2-14 In the previous exercise, you learned how to add a page that contains a simple Label control. Additionally, you saw how to write some code that updates the label with today’s date and time. You can ignore this code for now; it only served to demonstrate the differences between Code Behind and inline code. In Chapter 5, you learn more about programming in Visual Basic and C#. To make compelling pages, you obviously need a lot more content than just a simple Label control that shows today’s date and time. The next section shows you how to add content and HTML to your pages and how to style and format it. Adding Markup to Your Page You have a number of ways to add HTML and other markup to your pages. First of all, you can simply type it in the Markup View window. However, this isn’t always the best option, because it forces you to type a lot of code by hand. To make it easier to insert new HTML in the page and to apply formatting to it, the Design View window offers a number of helpful tools. These tools include the Formatting toolbar and the menu items Format and Table. For these tools to be active, you need to have the document in Design View. If you’re working in Split View mode, you have to make sure that the Design View part has the focus, or you’ll find that most of the tools are not available. Inserting and Formatting Text You can type text in both Design View and in Markup View. Simply place the cursor at the desired location and start typing. When you switch to Design View, the Formatting toolbar becomes avail- able, with the options shown in Figure 2-15. c02.indd 54c02.indd 54 10/8/2012 9:43:46 AM10/8/2012 9:43:46 AM
    • Working with Web Forms x 55 Target Rule Reuse Existing Style Show Overlay Italic Block Format Font Size Bold Underline Align Text Hyperlink Background Color Foreground Color FIGURE 2-15 Many of the buttons on the toolbar function exactly the same as in other editing environments. For example, the B button formats your text with a bold font. Similarly, the I and the U buttons itali- cize and underline your text, respectively. The drop-down list labeled Block Format enables you to insert HTML elements like <p> for paragraphs, <h1> through <h6> for headings, and <ul>, <ol>, and <li> for lists. You can choose an item from the drop-down list directly to have it inserted in your page, or you can select some text first and choose the appropriate block element from the list to wrap the selected text inside the tags. In the next Try It Out, you see how to work with these tools to create the homepage of the Planet Wrox website. TRY IT OUT Adding Formatted Text In this Try It Out, you create a Web Form called Default.aspx and add some basic content to it. 1. Add a new Web Form with the Add New Item dialog box to the root of the site and call it Default.aspx. Make sure you check off the Place Code in Separate File option and click Add. Switch to Design View using the Design button at the bottom of the Document Window. 2. Click inside the dashed rectangle until you see the glyph showing that the <div> element is cur- rently active. At the same time, the tag navigator at the bottom of the code window should high- light the last block with the text <div> on it, as shown in Figure 2-16. FIGURE 2-16 3. Type Hi there visitor and welcome to Planet Wrox and highlight the text using the mouse. From the Block Format drop-down list (visible in Figure 2-15) choose Heading 1 <h1>. Note that a small glyph with the text h1 appears right above the text, to indicate that VS created a heading for you automatically. Figure 2-17 shows the Design View with the <h1> element. c02.indd 55c02.indd 55 10/8/2012 9:43:46 AM10/8/2012 9:43:46 AM
    • 56 x CHAPTER 2 BUILDING AN ASP.NET WEBSITE FIGURE 2-17 4. Position your cursor at the end of the heading after the word Wrox and press Enter. A new para- graph (indicated by a small glyph with the letter p on it) is inserted for you so you can directly start typing. 5. Type the text shown in Figure 2-18 (or make up your own) to welcome the visitor to Planet Wrox. Notice how the text www.PlanetWrox.com turns blue as soon as you type the comma to indi- cate VS has recognized it as a web address and has turned it into a link. You can press Enter to start a new paragraph. Select the text “paying a visit,” click the Foreground Color button on the Formatting toolbar, and select a different color in the dialog box that appears. Then select some other text, such as “reviews and concert pictures,” and click the Bold button. When you’re done, your Design View should show something similar to Figure 2-18. FIGURE 2-18 The code for the homepage should now look more or less similar to the following (the code has been reformatted a bit to fit the space in the book): <div> <h1>Hi there visitor and welcome to Planet Wrox</h1> <p> We&#39;re glad you&#39;re <span class="auto-style1">paying a visit</span> to <a href="http://www.PlanetWrox.com">www.PlanetWrox.com</a>, the coolest music community site on the Internet. </p> <p> Feel free to have a look around; there are lots of interesting <strong>reviews and concert pictures</strong> to be found here. </p> </div> c02.indd 56c02.indd 56 10/8/2012 9:43:46 AM10/8/2012 9:43:46 AM
    • Working with Web Forms x 57 At the top of the file you should also see a <style> element, which is discussed next. 6. Open the page in your browser by pressing Ctrl+F5, or by right-clicking the page in the Solution Explorer and choosing View in Browser. How It Works When you use the various Formatting toolbar buttons, like Foreground Color, VS inserts the appro- priate HTML and CSS code for you. For example, when you click the B button, VS inserts a pair of <strong> tags around the selected text. When you click the I button, VS adds a pair of <em> tags to italicize the text. In this exercise, VS also inserted a class attribute (shown in the previous code exam- ple) that points to a class called auto-style1 when you changed the text color. The code for this style has been added to the top of your file and looks similar to this: <style type="text/css"> .auto-style1 { color: #FF0000; } </style> Your code may look slightly different if you chose a different color. The code you see here is explained in the next chapter. For now, just remember that this code sets the color of the text it is applied to as red. If the opening curly bracket is on the same line as the class, choose Tools Í Options Í Text Editor Í CSS Í Formatting and set the Formatting Style to Expanded. This is just a matter of preference and doesn’t change the effect of the code. Note that VS replaced the apostrophe character (’) in “we’re” in the welcome message with its HTML- compatible variant: &#39;. Using this kind of code enables you to insert characters in your page that a browser may have trouble displaying, or that have special meaning within HTML itself, like the ampersand character (&), which is written as &amp;. When you type text in Design View, VS automati- cally inserts the coded equivalents of relevant characters for you; however, if you type in Markup View directly, you’ll have to do this yourself. Don’t worry if your code looks different from what is shown here. Many settings in VS influence the code that is generated for you. So far, the exercises have been concerned with adding and styling text in your page. However, VS enables you to insert other HTML elements as well, like tables and bullets. The next section shows you how this works. Adding Tables and Other Markup HTML tables are great if you need to present structured or repeating data, like a list of products in a shopping cart, photos in a photo album, or input controls in a form. There is a lot of debate on the Internet about whether you should use tables to lay out your page as well. For example, if your page contains a header with a logo, a main content area, and a footer at the bottom, you could use a table with three rows to accomplish this. In general, it’s considered bad practice to use tables for this purpose because they add a lot of extraneous markup to the page and are often difficult to main- tain. Besides, quite often the same result can be accomplished using CSS, which you learn about in the next chapter. Despite the disadvantages that tables may bring, they are still an invaluable asset in your HTML toolbox when it comes to displaying tabular or otherwise structured information. c02.indd 57c02.indd 57 10/8/2012 9:43:47 AM10/8/2012 9:43:47 AM
    • 58 x CHAPTER 2 BUILDING AN ASP.NET WEBSITE TRY IT OUT Using the Format and Table Menus In this exercise, you learn how to add tables to your page using the Table menu and how to add rows and columns. Additionally, you learn how to add other structured elements, such as bulleted lists. 1. In the Demos folder, create a new Web Form called TableDemo.aspx. Make sure it uses Code Behind by checking the Place Code in Separate File option. 2. Switch the page to Design View, click inside the dashed rectangle that represents the standard <div> tag in the page, and choose Table Í Insert Table. The Insert Table dialog box appears, as shown in Figure 2-19. FIGURE 2-19 3. Set Rows to 3 and leave Columns set to 2. Leave all other settings at their defaults and click OK. The table gets inserted in the page. 4. If you see only a single table cell, and not the entire table with three rows and two columns, you need to enable Visual Aid for tables. To do this, choose View Í Visual Aids Í Visible Borders from the main menu to turn the borders on. Your Design View should now look like Figure 2-20. FIGURE 2-20 c02.indd 58c02.indd 58 10/8/2012 9:43:47 AM10/8/2012 9:43:47 AM
    • Working with Web Forms x 59 5. Drag the right border of the very first cell in the table to the left. You’ll see a visual indicator showing the width of the cell. Keep dragging it to the left until it has a width of 200 pixels, as in Figure 2-21. FIGURE 2-21 6. To add more rows or columns to the table, you can right-click an existing cell. From the pop- up menu that appears, choose Insert to add additional rows or columns at different locations. Similarly, you can use the Delete, Modify, and Select options to delete rows or columns, merge cells, and make selections. For this exercise, you don’t need to add additional rows or columns, although it’s okay if you have already done so. 7. Place your cursor in the first cell of the first row and type the words Bulleted List. 8. Place your cursor in the second cell using the mouse. Alternatively, you can press Tab to move the cursor to the next cell. From the Format menu, choose Bullets and Numbering. 9. Switch to the Plain Bullets tab, click the picture with the round, solid bullets (see Figure 2-22), and click OK. FIGURE 2-22 10. Type some text, like your favorite musical genre (Punk, Rock, Techno, and so on), and press Enter. VS inserts a new bullet for you automatically, so you can continue to add new items to the list. Add two more genres, so you end up with three bullets. c02.indd 59c02.indd 59 10/8/2012 9:43:47 AM10/8/2012 9:43:47 AM
    • 60 x CHAPTER 2 BUILDING AN ASP.NET WEBSITE 11. Repeat steps 7 through 10, but now create a numbered list. First, type Numbered List in the first cell of the second row, then position your cursor in the second cell of the same row, and choose Format Í Bullets and Numbering. Switch to the Numbers tab (visible in Figure 2-22 behind the Plain Bullets tab) and click the second picture in the first row, which shows a standard numbered list, and click OK. Type a few items for the list, pressing Enter after each item. 12. Open the page in the browser by pressing Ctrl+F5. You should see a screen similar to Figure 2-23. FIGURE 2-23 How It Works When you visually insert page elements like tables or lists through the available menus, VS inserts the required markup for you in Markup View. When you insert a table, VS adds a <table> element and a number of <tr> and <td> elements to define rows and cells, respectively. It also applies a class attri- bute pointing to a CSS style that defines the table’s width. It created another style for the <td> elements when you dragged the column width to be 200 pixels. Similarly, when you insert a list, VS inserts an <ol> element for numbered or ordered lists and a <ul> element for bulleted or unordered lists. Within these elements, <li> elements are used to define each item in the list. Besides the HTML tags you have seen thus far, there is another important tag you need to look at: the <a> tag, which is used to create links between pages. Connecting Pages An important part of any website is the links that connect the pages in your site. Links enable your visitors to go from one page to another, in the same site or to a completely different site on the Internet. You have a few ways to create links between pages, including: ‰ The HTML <a> element, explained in this chapter. ‰ Using the <asp:HyperLink> control, discussed in Chapter 7. ‰ Programmatically through code. This is discussed later in the book. The following exercise shows you how easy it is to link from one page to another. c02.indd 60c02.indd 60 10/8/2012 9:43:47 AM10/8/2012 9:43:47 AM
    • Working with Web Forms x 61 TRY IT OUT Linking Pages In this Try It Out, you modify the TableDemo.aspx page you created earlier by adding text that links to another page. Once you run the page in the browser and click that link, the new page replaces the old one. 1. Open the TableDemo.aspx page from the Demos folder. 2. If necessary, switch to Design View. 3. In the first cell of the third row, type the text Link. 4. In the second cell of the same row, type the text Go to the homepage of Planet Wrox and highlight it with your mouse. 5. On the Formatting toolbar, click the Convert to HyperLink button. It’s located near the end of the toolbar and has a link icon and a small arrow on it. 6. In the dialog box that appears, click the Browse button, browse to the Default.aspx page in the root of your site, and click OK. Next, click OK again to close the Hyperlink dialog box. The Design View of your page should look similar to the one displayed in Figure 2-24. FIGURE 2-24 7. Switch to Markup View and notice how the HTML for the link has been inserted: <a href="../Default.aspx">Go to the homepage of Planet Wrox</a> Note that the href attribute points to the page you want to link to. 8. If you want to change the page being linked to from Markup View, click somewhere between the opening and closing quotes of the href attribute and press Ctrl+Spacebar. A dialog box pops up that enables you to select another page within your site. Alternatively, you can click the Pick URL option and browse for the new page somewhere in your site. 9. Right-click the TableDemo.aspx page in the Solution Explorer and choose View in Browser. When the page has finished loading, click the Go to the homepage of Planet Wrox link. The request is sent to the web server and, as a response, you now get the homepage of the website. c02.indd 61c02.indd 61 10/8/2012 9:43:47 AM10/8/2012 9:43:47 AM
    • 62 x CHAPTER 2 BUILDING AN ASP.NET WEBSITE How It Works Links between pages are likely one of the most important elements in a web page, because they enable you to create a connection between a page in your site and another page, whether that page lives in your own site or on a completely different server somewhere on the Internet. For simple links that should appear somewhere in your page, the HTML <a> tag with an href attribute set is the easiest to set up. When the user clicks such a link, the browser requests the new page from the server and displays it. The double dots (..) in the href’s value are a way to refer to the parent directory. The full href attribute means “go up one level in the folder hierarchy and then select the file Default.aspx.” You see a lot more about links and how they work in Chapter 7. You’re not limited to linking to pages in your own site. If you want to link to external pages instead, simply replace the href attribute value with the full address of the page, as shown in the following example: <a href="http://www.wrox.com">Go to the Wrox homepage</a> For external links, it’s important to include the http:// prefix; otherwise, the browser goes out look- ing for a file or folder called www.wrox.com on your own website. You’ll use the things you learned in this chapter about page creation and formatting in the next chapter, which deals with designing your web pages using CSS. Besides the visual tools, like the Formatting toolbar and the Table menu, Visual Studio has another great way to quickly insert code in your pages: code snippets. Code snippets enable you to insert large chunks of code with just a few keystrokes. You see code snippets at work in the next chapter. PRACTICAL TIPS ON WORKING WITH WEB FORMS Here are some tips for working with Web Forms: ‰ Favor Web Forms with Code Behind over those with inline code. Although at first you may not notice a big difference in working with them, as your site and pages start to grow, you’ll find that it’s easier to work with a page where the code is separated from the markup. ‰ Spend some time familiarizing yourself with the different menu items of the Format and Table menus. Most of them generate HTML elements that are inserted into your page. Take a look at the HTML elements and attributes that have been generated for you, and try to change them directly in the code, and through the menus and toolbars. This way, you get a good feel for the various tags available and how they behave. ‰ Experiment with links to connect pages in your site. Notice how VS creates different links depending on the location of the page you are linking to. Chapter 7 deals with linking and the various ways to address pages in your site in much more detail. c02.indd 62c02.indd 62 10/8/2012 9:43:48 AM10/8/2012 9:43:48 AM
    • Summary x 63 SUMMARY This chapter introduced you to some important topics that help you build maintainable and struc- tured ASP.NET websites. Understanding the differences between the various project types and tem- plates enables you to kick-start a web project with just the files you need. The same applies to the different file types you can add to your site. Because each file type serves a specific purpose, it’s important to realize what that purpose is and how you can use the file. One common activity that you’ll perform when building ASP.NET web pages is adding markup to the page. As you saw in this and the previous chapter, markup comes in a few flavors, including plain HTML and ASP.NET Server Controls. Knowing how to add this markup to your page using the numerous menu options and toolbars that VS offers is critical in building good-looking web pages. Now that you have a solid understanding of creating and modifying Web Forms, it’s time to look at how you can turn those dull black-and-white pages with a few controls into attractive web pages. The next chapter shows you how to work with the many CSS tools found in VS to create the desired effect. EXERCISES 1. Name three important files in the Web Files category that you can add to your site. Describe the purpose of each file. 2. What do you need to do to make a piece of text both bold and italicized in your web page? What will the resulting HTML look like? 3. Name three different ways to add existing files to an ASP.NET website in VS. 4. What are the different views that VS offers you for your ASPX pages? Does VS offer other views as well? You can find answers to these exercises in Appendix A. c02.indd 63c02.indd 63 10/8/2012 9:43:48 AM10/8/2012 9:43:48 AM DownloadfromWow!eBook<www.wowebook.com>
    • 64 x CHAPTER 2 BUILDING AN ASP.NET WEBSITE WHAT YOU LEARNED IN THIS CHAPTER Code Behind A page model where server-side code is stored in a separate code file Design View Gives you a graphical representation of your page File Types ASP.NET supports many different file types, including Web Forms (.aspx), master pages (.master), CSS files (.css), JavaScript (.js), and SQL Server databases (.mdf) Inline Code A page model where server-side code is stored in the same file as the markup Markup View Enables you to look at the markup of your page Project Templates Jump-start your web development by setting up a site targeting a specific scenario Project Types Visual Studio offers two project types: Web Application Projects and Web Site Projects Split View Enables you to look at Markup View and Design View at the same time Web Form Presents the user interface of your website at the client c02.indd 64c02.indd 64 10/8/2012 9:43:48 AM10/8/2012 9:43:48 AM
    • Designing Your Web Pages WHAT YOU WILL LEARN IN THIS CHAPTER: ‰ What CSS is and why you need it ‰ How CSS looks and how to write it ‰ The different ways to add CSS code to your ASP.NET pages and to external files ‰ The numerous tools that VS offers you to quickly write CSS WROX.COM CODE DOWNLOADS FOR THIS CHAPTER You can find the wrox.com code downloads for this chapter on the Download Code tab at www.wrox.com/remtitle.cgi?isbn=1118311809. The code is in the Chapter 3 download. The pages you created in the previous two chapters look pretty plain and dull. That’s because they lack styling information and therefore default to the standard layout that the browser applies. To spruce up your pages, you need a way to change their presentation in the browser. The most common way to do this is by using the cascading style sheets (CSS) language. CSS is the de facto language for formatting and designing information on the web, including ASP.NET web pages. With CSS you can quickly change the appearance of your web pages, giving them that great look that your design or corporate identity dictates. Solid support for working with CSS was initially added in Visual Web Developer (VWD) 2008, one of the predecessors of VS Express 2012 for Web. This support has been further enhanced in the previous version of Visual Studio, VWD 2010. The new VS 2012 builds on top of this CSS support and improves it in a number of ways, making the CSS editor a first- class citizen in VS, with editor features similar to other languages such as C# and VB. The CSS tools enable you to create your CSS code visually, making it much easier to style your pages without the need to know or remember every little detail of CSS. 3 c03.indd 65c03.indd 65 10/8/2012 9:46:45 AM10/8/2012 9:46:45 AM
    • 66 x CHAPTER 3 DESIGNING YOUR WEB PAGES To understand the relevance of and need for CSS in your ASP.NET websites, you need to understand the shortcomings of HTML first. The next section looks at the problems that plain HTML presents, and how CSS is able to overcome these issues. WHY DO YOU NEED CSS? In the early days of the Internet, web pages consisted mostly of text and images. The text was for- matted using plain HTML, using tags like <b> to make the text bold, and the <font> tag to influ- ence the font family, size, and color. Web developers soon realized that they needed more power to format their pages, so CSS was created to address some of HTML’s styling shortcomings. Problems of HTML Formatting One of the problems with using HTML for formatting is that it offers only a limited set of options to style your pages. You can use elements like <i>, <b>, and <font> to change the appearance of text and use attributes like bgcolor to change the background color of HTML elements. You also have a number of other attributes at your disposal for changing the way links appear in your page. Obviously, this feature set isn’t rich enough to create the attractive web pages that your users expect and demand. Another problem of HTML with a lot more impact on how you build your web pages is the way the styling information is applied to the page. By design, HTML forces you to embed your formatting in your HTML document, making it harder to reuse or change the design later. Consider the following example: <p><font face="Arial" color="red" size="+1"> This is red text in an Arial type face and slightly larger than the default text. </font></p> The problem with this code snippet is that the actual data (the text in the <p> element) is mixed with the presentation (the formatting of the text with the <font> tag in this example). Ideally, the two should be separated, so each of them is easier to change without affecting the other. Imagine you used the <p> and <font> elements to mark up the first paragraph of every page in your site. What happens when you decide to change the color of the font from red to dark blue? Or what if your corporate identity dictates a Verdana font instead of Arial? You would need to visit each and every page in your site, making the required changes. Besides maintainability, another problem with HTML formatting is the fact that you can’t eas- ily change the formatting at run time in the user’s browser. With the HTML from the previous code snippet, there is no way to let your visitor change things like the font size or color, a common request to help people who are visually impaired. If you want to offer your visitors an alternative version of the page with a larger font size or a different color, you’d need to create a copy of the original page and make the necessary changes. The final problem with HTML formatting is that the additional markup in your page adds consider- ably to the size of the page. This makes it slower to download and display because the information needs to be downloaded with each page in your website. It also makes it harder to maintain your pages because you’d need to scroll through large HTML files to find the content you need. c03.indd 66c03.indd 66 10/8/2012 9:46:50 AM10/8/2012 9:46:50 AM
    • An Introduction to CSS x 67 To summarize, formatting with HTML suffers from the following problems: ‰ Its feature set severely limits the formatting possibilities that your pages require. ‰ Data and presentation are mixed within the same file. ‰ HTML doesn’t enable you to easily switch formatting at run time in the browser. ‰ The required formatting tags and attributes make your pages larger and thus slower to load, display, and maintain. Fortunately, CSS enables you to overcome all of these problems. How CSS Fixes Formatting Problems CSS is designed to format your web pages in almost every possible way. It offers a rich set of options to change every little aspect of your web page, including fonts (size, color, family, and so on), colors and background colors, borders around HTML elements, positioning of elements in your page, and much more. CSS is widely understood by all major browsers today, so it’s the language for visual presentation of web pages and very popular among web developers. CSS overcomes the problem of mixed data and presentation by enabling you to define all format- ting information in external files. Your ASPX or HTML pages can then reference these files and the browser will apply the correct styles for you. With this separation, the HTML document contains what you want to display, and the CSS file defines how you want to display it, enabling you to change or replace one of the two documents, leaving the other unmodified. In addition, you can place CSS directly in an HTML or ASPX page, which gives you a chance to add small snippets of CSS exactly where you need them. You should be cautious when placing CSS directly in an HTML or ASPX page, because you can then no longer control style information from a single, central location. Because you can place all CSS code in a separate file, it’s easy to offer the user a choice between dif- ferent styles—for example, one with a larger font size. You can create a copy of the external style sheet, make the necessary changes, and then offer this alternative style sheet to the user. You see how this works in Chapter 6 when ASP.NET Themes are discussed. Another benefit of a separate style sheet file is the decrease in bandwidth that is required for your site. Style sheets don’t change with each request, so a browser saves a local copy of the style sheet the first time it downloads it. From then on, it uses this cached copy instead of requesting it from the server over and over again. Sometimes this caching can work against you when the browser doesn’t download the latest CSS files with your changes. If you find that the browser is not picking up the changes you made to a CSS file, use Ctrl+F5 or Ctl+R in the browser (not in VS) to get a fresh copy from the server. Now that you have seen why CSS is so important, it’s time to find out how it looks and how to use it. AN INTRODUCTION TO CSS In terms of syntax, CSS is an easy language to learn. Its “grammar” consists of only a few concepts. That makes it relatively easy to get started with. What makes CSS a bit more difficult is the way all major browsers render a page. Although virtually every modern desktop browser understands CSS, c03.indd 67c03.indd 67 10/8/2012 9:46:50 AM10/8/2012 9:46:50 AM
    • 68 x CHAPTER 3 DESIGNING YOUR WEB PAGES they all have their quirks when it comes to displaying a page according to the CSS standard. This standard, maintained by the same organization that maintains the HTML standard, the World Wide Web Consortium, or W3C for short, comes in three different versions: 1.0, 2.1, and 3.0. From these three versions, 2.1 is the most applicable today. It contains everything that version 1.0 contains but also adds a lot of possibilities on top of that. It’s also the version that VS uses and generates by default. Version 3.0 is currently under development and it’s expected to take some time before the major browsers have solid support for it. Before you look at the actual syntax of CSS, it’s a good idea to see an example first. In the following exercise, you write a simple ASPX page that contains some CSS to format the contents of the page. This helps in understanding the CSS language, which is discussed in full detail in the section that follows. TRY IT OUT Writing Your First CSS In this Try It Out you write some CSS that changes the appearance of a header and two paragraphs. You’ll hand code the page for now; the second half of this chapter shows you how to use the CSS tools available in VS. 1. In the Demos folder of the Planet Wrox project, create a new Web Form called CssDemo.aspx. For this exercise, it doesn’t matter if you choose inline code or Code Behind. 2. Make sure the page is in Markup View and then locate the closing </title> tag in the source. Position your cursor at the end of the line and press Enter to create an empty line between the <title> and <head> tags. On this new line type the word style and then press Tab. VS completes the <style> element for you. Press Enter twice to create some room between the tags and then complete the block as follows: <title></title> <style type="text/css"> </style> </head> NOTE This code completion feature uses code snippets that enable you to associate a piece of code (like the <style> element) with an identifier (like style in this example). Code snippets are very useful for inserting pieces of code quickly by typing only the short identifier. Many more code snippets are available, and where appropriate I’ll point them out throughout this book. Instead of using the style code snippet, you can also type the full code yourself. Note that as soon as you type the opening angle bracket (<), a list pops up that enables you to select the <style> tag. The same applies to the type attribute; simply type the letters ty and the type attribute is preselected in the list. All you need to do to complete the word is press the Tab or Enter key. And, once more, the same help is available for the attribute value text/css. Simply select it in the list and press Tab or Enter, and the value is inserted for you automatically, nicely surrounded by the double quotes. c03.indd 68c03.indd 68 10/8/2012 9:46:50 AM10/8/2012 9:46:50 AM
    • An Introduction to CSS x 69 3. Next, between the opening and closing <style> tags, type the following bolded CSS code: <style type="text/css"> h1 { font-size: 20px; color: Green; } p { color: Blue; font-style: italic; } .RightAligned { text-align: right; } </style> Take great care when typing this code, because CSS is rather picky about syntax. The first item in the list is an h1 tag to style a heading at the first level, so it gets a size of 20 pixels and is displayed in a green font. Notice the colon between font-size and 20px and that the line is closed with a semicolon. The second item in the list simply contains the letter p and defines the look and feel for all <p> elements in the page. The last item is prefixed with a period (.) followed by the text RightAligned. This item is used to right-align some text in the page. Because CSS is case sensitive, it’s important to type this exactly as shown here, with a capital R and A, or the CSS code won’t line up with the HTML shown in the next step. Note that as soon as you type the hash symbol (#) after the color property, a color picker pops up to help you to select a color as shown in Figure 3-1. For now, just close the color picker by pressing Esc and manually complete the code. You see more of this color picker later in this chapter. 4. Scroll down in the page a bit until you see the opening <div> tag. Right after this tag, type the fol- lowing bolded code: <div> <h1>Welcome to this CSS Demo page</h1> <p>CSS makes it super easy to style your pages.</p> <p class="RightAligned"> With very little code, you can quickly change the looks of a page. </p> </div> Instead of typing in this code directly, you can also use the Formatting toolbar while in Design View to create elements like <h1> and <p>. For now, you need to switch to Markup View to add FIGURE 3-1 c03.indd 69c03.indd 69 10/8/2012 9:46:50 AM10/8/2012 9:46:50 AM
    • 70 x CHAPTER 3 DESIGNING YOUR WEB PAGES class="RightAligned", but in later exercises in this chapter you see how you can have the IDE write this code for you. 5. If you switch to Design View (or Split View), you’ll see that the designer shows your text with the formatting defined in the <style> element of the page. Figure 3-2 shows the page in Split View so you can see the code and the design at the same time. FIGURE 3-2 Although this black-and-white book makes it difficult to see different font colors, in Figure 3-2 you can see clearly that the <h1> has a larger font size. The figure also shows that all paragraphs are now displayed with an italic font. Finally, you can see that the last paragraph is aligned to the right of the window, because the class attribute on the tag is set to RightAligned. COMMON MISTAKES If you don’t see the last paragraph glued to the right bor- der of the Document Window make sure you typed RightAligned exactly the same in the <style> tag and in the class attribute. Because CSS is case sensi- tive, there’s a big difference between RightAligned and rightaligned. 6. Press Ctrl+F5 to view CssDemo.aspx in your browser. The page you see in the browser is identical to the preview you got in the Design View of VS. How It Works Although the code you typed in this exercise is relatively simple, there’s a lot going on under the hood of the browser (and the Design View of VS) to make this possible. You started by adding some styles to the <head> section of the page: <style type="text/css"> h1 c03.indd 70c03.indd 70 10/8/2012 9:46:50 AM10/8/2012 9:46:50 AM
    • An Introduction to CSS x 71 { font-size: 20px; color: Green; } ... </style> The <style> tag is used to wrap a style sheet that is embedded in the page with its type attribute set to text/css. This text/css value is currently the only applicable type for a <style> block and tells the browser to interpret the code that follows as CSS. The code block from h1 until the closing curly brace (}) between the <style> tags is called a rule set or simply a rule. The rule in this code snippet defines the appearance for all <h1> elements in your page. The h1 at the top of the code block is called a selector and is used to indicate to what element the formatting should be applied. In this case, the selector maps directly to an HTML element, but many other selectors are available, as you see in the next section. Figure 3-3 shows how the elements are related to each other. Between the curly braces you see the style information that should be applied to the heading. Each line between the curly braces is called a declaration. A declaration consists of a property, followed by a colon, and then followed by a value. The semicolon (;) at the end of a declara- tion separates it from the next declaration and is required on all declarations except for the last one in the rule set. However, for consistency, it’s a good idea to add it to all declarations, which is what I’ll do in the remainder of this book. When the browser loads this page, it also reads in the styles you defined between the <style> tags. Then, whenever it comes across an HTML element that matches the selector, it applies the CSS rules to that element. So, for the <h1> and <p> elements, their respective rules are applied. This causes the head- ing to turn green with a large font, while the paragraphs turn blue with an italic font. But why does the last paragraph turn blue and get right-aligned? In CSS, you can have rules coming from different sources. The last <p> element gets its style information from the standard p selector in the style definition. So, the p rule gives the paragraph a blue and italic font. However, it also has a class defined. This class, called RightAligned, links to a Class selector .RightAligned (note the leading period) in the style sheet and causes the text to be aligned to the right of the window. You see more of Class and other selectors in the next section. In the end, the last <p> element gets its rules from two selectors at the same time. You can make up and assign your own class names (as shown with the RightAligned class), giving you the flexibility to design your pages and elements exactly how you want them. The next section digs a lot deeper in the syntax of CSS, giving you a much more detailed view on selectors, properties, and values. hl { font-size: 20px; color: Green; } Rule Set Selector Declaration Property Value FIGURE 3-3 c03.indd 71c03.indd 71 10/8/2012 9:46:50 AM10/8/2012 9:46:50 AM
    • 72 x CHAPTER 3 DESIGNING YOUR WEB PAGES CSS — The Language As you saw in the previous Try It Out exercise, a cascading style sheet is actually a collection of rules. A rule is a combination of a selector and one or more declarations, which in turn can be broken down to a property and a value. You’re probably getting a little dizzy from all the new terms that were introduced in the past few paragraphs, so in the next section, you see most of them again, with a detailed explanation and code examples that show you what they are used for and how they work. The Style Sheet The style sheet contains all the relevant style information that should be applied to page elements. In its simplest form, a style sheet looks like this: h1 { color: Green; } A style sheet can also contain more than one rule, as you saw in the previous exercise. At the same time, each rule can contain multiple declarations, enabling you to group them under a single selector: h1 { font-size: 20px; color: Green; } The code you just saw is functionally identical to this: h1 { font-size: 20px; } h1 { color: Green; } The condensed form, where the two declarations are grouped under the same selector, is much easier to read, understand, and maintain, so it’s advisable to use this syntax as much as possible. To be able to style an element on a page, a browser has to know three things: ‰ What element of the page must be styled? ‰ What part of that element must be styled? ‰ How do you want that part of the selected element to look? The answers to these questions are given by selectors, properties, and values. c03.indd 72c03.indd 72 10/8/2012 9:46:51 AM10/8/2012 9:46:51 AM
    • An Introduction to CSS x 73 Selectors As its name implies, a selector is used to select or point to one or more specific elements within your page. A number of different selectors are available, giving you fine control over what elements you want to style. The selector answers the first question: What element of the page must be styled? The next section shows you the four most important types of selectors. The Universal Selector The Universal selector, indicated by an asterisk (*), applies to all elements in your page. You can use the Universal selector to set global settings like a font family. The following rule set changes the font for all elements in your page to Arial: * { font-family: Arial; } The Type Selector The Type selector enables you to point to an HTML element of a specific type. With a Type selector, all HTML elements of that type will be styled accordingly. h1 { color: Green; } This Type selector now applies to all <h1> elements in your code and gives them a green color. Type selectors are not case sensitive, so you can use both h1 and H1 to refer to the same heading. I prefer to use all lowercase for my Type selectors though, so that’s what you’ll see in this book. The ID Selector The ID selector is always prefixed by a hash symbol (#) and enables you to refer to a single element in the page. Within an HTML or ASPX page, you can give an element a unique ID using the id attribute. With the ID selector, you can change the behavior for that single element, like this: #IntroText { font-style: italic; } Because you can reuse this ID across multiple pages in your site (it only has to be unique within a single page), you can use this rule to quickly change the appearance of an element that you use once per page, but more than once in your site, for example, with the following HTML code: <p id="IntroText">I am italic because I have the right ID.</p> <p id="BodyText">I am NOT italic because I have a different ID.</p> In this example, the #IntroText selector changes the font of the first paragraph — which has the matching id attribute — but leaves the other paragraph unmodified. ID selectors are case sensitive, so make sure that the id attribute and the selector always use the same casing. c03.indd 73c03.indd 73 10/8/2012 9:46:51 AM10/8/2012 9:46:51 AM
    • 74 x CHAPTER 3 DESIGNING YOUR WEB PAGES Notice that the selector uses a hash symbol (#) in its name, but you don’t use this symbol in the id attribute. The Class Selector The Class selector enables you to style multiple HTML elements through the class attribute. This is handy when you want to give the same type of formatting to a number of unrelated HTML ele- ments. The following rule changes the text to red and bold for all HTML elements that have their class attributes set to Highlight: .Highlight { color: Red; font-weight: bold; } The following code snippet uses the Highlight class to make the contents of a <span> element and a link (<a>) appear with a bold typeface: This is normal text but <span class="Highlight">this is Red and Bold.</span> This is also normal text but <a href="CssDemo.aspx" class="Highlight">this link is Red and Bold as well.</a> Notice that the selector uses a period in its name, but you don’t use this period when referring to the selector in the class attribute. The class attribute is very useful because it enables you to reuse a piece of CSS for many different purposes, regardless of the HTML element that uses the class. Class selectors are case-sensitive so make sure you type them correctly (or let IntelliSense help you pick the classes from the list when possible). CSS supports more types of selectors, giving you even more control over the elements you want to target, but the four different types you just saw are the most widely used. Grouping and Combining Selectors CSS also enables you to group multiple selectors by separating them with a comma. This is handy if you want to apply the same styles to different elements. The following rule turns all headings in the page to red: h1, h2, h3, h4, h5, h6 { color: Red; } Moreover, with CSS you can also combine selectors, enabling you to hierarchically point to a spe- cific element in a page. You can do this by separating the selectors with a space. The following example targets all <p> elements that fall within a <section> element with an id of MainContent, leaving all other paragraphs unmodified. Also note there’s no space between section and #MainContent. This results in that part of the selector targeting a <section> element with an id of MainContent. section#MainContent p { font-size: 18px; } c03.indd 74c03.indd 74 10/8/2012 9:46:51 AM10/8/2012 9:46:51 AM
    • An Introduction to CSS x 75 Note that combining is very different from grouping. Grouping is just a shortcut to avoid typing the same declarations over and over again, whereas combining enables you to target specific elements in your document. With combining, you’re not limited to ID and Type selectors; you can also use it with the other selectors, as is demonstrated with the following example: section#MainContent p.Attention { font-weight: bold; } This rule changes all paragraphs with the class Attention within the <section> element with its id set to MainContent and leaves all others untouched. The following HTML snippet uses this rule to show the effect: <section id="MainContent"> <p class="Attention">My class is Attention, so my text is bold.</p> <p>My text is not bold, as it lacks the Attention class.</p> </section> <p class="Attention">I am NOT bold because I don't fall within MainContent.</p> The second question that needs to be answered to apply a certain style in your page is about what part of the element must be styled. You do this with properties. Properties Properties are the part of the element that you want to change with your style sheet. The CSS speci- fication defines a long list of properties (VS’s IntelliSense list shows more than 100 items), although you won’t use all of them in most websites. The following table lists some of the most common CSS properties and describes where they are used. PROPERTY DESCRIPTION EXAMPLE background-color background-image Specifies the background color or image of an element. background-color: White; background-image: url(Image.jpg); border Specifies the border of an element. border: 3px solid Black; color Changes the font color. color: Green; display Changes the way elements are displayed, enabling you to hide or show them. display: none; This causes the element to be hidden, and not take up any screen space. float Enables you to “float” an ele- ment in the page using a left or right float. Other content is then placed on the opposite side. float: left; This setting causes other content following a float to be placed at the top-right corner of the element. You see how this works later in the chapter. continues c03.indd 75c03.indd 75 10/8/2012 9:46:51 AM10/8/2012 9:46:51 AM
    • 76 x CHAPTER 3 DESIGNING YOUR WEB PAGES PROPERTY DESCRIPTION EXAMPLE font-family font-size font-style font-weight Changes the appearance of fonts used on your page. font-family: Arial; font-size: 18px; font-style: italic; font-weight: bold; height width Sets the height or width of elements in your page. height: 100px; width: 200px; margin padding Sets the amount of free space inside (padding) and outside (margin) of an element. padding: 0; margin: 20px; visibility Controls whether an ele- ment is visible in the page. Invisible elements still take up screen space; you just don’t see them. visibility: hidden; This causes the element to be invisible. However, it still takes up its original space in the page. It’s as if the element is still there, but completely transparent. Fortunately, VS helps you to find the right property with its many CSS tools, so you don’t have to remember them all. NOTE Many more selectors and properties are available in CSS than I have described here. For more detail on CSS, consult VS’s IntelliSense lists or take a look at www.w3schools.com/cssref/. For a property to be useful, you need to give it a value, which answers the third question: How do you want the part of the selected element to look? Values Just as with properties, values come in many flavors. The values you have available depend on the property. For example, the color attribute takes values that represent a color. This can be a named color (such as White), a hexadecimal number representing a red, green, and blue (RGB) component (such as #FF0000), or you can set it using the CSS rgb notation. The following examples are all functionally equivalent and set the color of the h1 element to red: h1 { color: Red; } h1 { (continued) c03.indd 76c03.indd 76 10/8/2012 9:46:51 AM10/8/2012 9:46:51 AM
    • An Introduction to CSS x 77 color: #FF0000; } h1 { color: rgb(100%, 0%, 0%); } You can also specify the transparency of a color using the rgba notation where the fourth parameter is a decimal number between 0 (fully transparent) and 1 (no transparency) like this: color: rgba(255, 0, 0, 0.50); Using named colors can increase the readability of your CSS code, but because you’re limited to a rela- tively short list of named colors, you often need the hexadecimal notation to get the exact color you want. Later in this chapter you see how to use the built-in color picker to create the exact color you need. Many other values are possible as well, including size units (px, em, and so on), font families, images (which take the form of url(SomeImage.jpg)), or so-called enumerations like the border-style, which enables you to set a border style such as solid, dashed, double. Using Shorthand Many of the CSS properties enable you to write a shorthand version as well as a more expanded ver- sion. Take, for example, the border property. In its shortest form, you can set the border property like this: border: 1px solid Black; This border property applies a border to all four sides of an HTML element. The border size is 1px, the style is solid (some of the other options include dashed, dotted, and double), and the border color is set to Black. This is an easy way to quickly set all four borders of the HTML to the same values. However, if you want more control over the individual borders and their properties, you can use the expanded version: border-top-width: 1px; border-top-style: solid; border-top-color: Black; border-right-width: 1px; border-right-style: solid; border-right-color: Black; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: Black; border-left-width: 1px; border-left-style: solid; border-left-color: Black; This long version causes the exact same style to be applied: a solid black border on all four sides with a thickness of 1 pixel. In most cases, you should favor shorthand notation over its expanded counterpart, because it’s much easier to read and maintain. However, if you need absolute control over the border — for example, if you want a 2-pixel dashed border on the left and top sides, and c03.indd 77c03.indd 77 10/8/2012 9:46:51 AM10/8/2012 9:46:51 AM
    • 78 x CHAPTER 3 DESIGNING YOUR WEB PAGES a green, solid border on the right and bottom sides of the HTML element — it’s good to know that you can set each border property of all four directions individually. You can also mix these options. The following example sets the border on all four sides to a 1-pixel solid black line, and then over- rides just the color of the left border: border: 1px solid Black; border-left-color: Blue; Other CSS properties that support shorthand include font, background, list-style, margin, and padding. If you’re unsure whether a property supports shorthand, consult the IntelliSense pop-up list that appears by pressing Ctrl+Space when you’re entering a property in a CSS file or a <style> block. Although at times it seems you need to write CSS by trial and error, and just hope for the right result, there’s actually a quite accurate model behind CSS that determines how items should be laid out on the page. This model is called the CSS Box Model. The CSS Box Model The CSS Box Model describes the way three important CSS properties are applied to HTML elements: padding, border, and margin. Figure 3-4 shows a graphical representation of the box model. In the middle there is an HTML element like a <p> or a <div> with a certain height and width. Just around it there is padding; the whitespace that surrounds the element within its border. Immediately after the padding you can see the border and finally on the outside there is the margin, which defines the room between an ele- ment (including its padding and border) and its surrounding elements. The three outer properties of an element — padding, border, and margin — add up to the space that an element takes up in the page. To see how this works, consider the following CSS and HTML: .MyDiv { width: 200px; padding: 10px; border: 2px solid Black; } ... <div class="MyDiv">Element</div> This renders a rectangle in the browser with the <div> element surrounded by a black border of two pixels, as shown in Figure 3-5. ElementLeft Right Padding Border Margin Top Bottom FIGURE 3-4 Element How wide is this arrow? FIGURE 3-5 c03.indd 78c03.indd 78 10/8/2012 9:46:52 AM10/8/2012 9:46:52 AM
    • An Introduction to CSS x 79 Before you read on, try answering the question: How wide is the arrow below the <div> element? If you guessed 224 pixels, you are correct. The width of the arrow is the sum of three values: the width of the actual element (200 pixels), plus the width of the padding surrounding it on both sides (two times 10 pixels), plus the width of the borders on both sides (two times 2 pixels), resulting in a total width of 224 pixels. So, if you wanted the entire box to be 200 pixels wide instead, you’d need to set the width property of the MyDiv selector to 176px. Outside the border of the element, margin could further influence the gap between this element and its surrounding elements. The example shows the effect on the width only, but the same principles apply to the height of ele- ments. Keep this box model in mind when laying out your pages. When things end up wider or taller than you anticipated, check the width, height, padding, border, and margin properties in the CSS style sheet. In the next exercise, you modify the site’s homepage that you created in the previous chapter. You add the basic layout for the site, which is then styled using a style sheet. In Chapter 6 you use this page again when you upgrade it to a master page. TRY IT OUT Styling the Planet Wrox Homepage In this exercise you modify two files. First, you add the basic layout elements to the Default.aspx page to create room for a header, a menu, the main content area, a sidebar, and a footer. Then you modify the Styles.css file from the Styles folder to change the size and location of these elements. Finally, you attach the style sheet to the page, so the style information is applied when the page is viewed in the designer or in a browser. 1. Open the Default.aspx file from the root of your website and, if necessary, switch to Markup View. 2. Modify the code within the <form> element so it ends up like this: <form id="form1" runat="server"> <div id="PageWrapper"> <header>Header Goes Here</header> <nav>Menu Goes Here</nav> <section id="MainContent"> <h1>Hi there visitor and welcome to Planet Wrox</h1> ... </section> <aside id="Sidebar">Sidebar Goes Here</aside> <footer>Footer Goes Here</footer> </div> </form> Make sure that the welcome message you added in the previous chapter ends up between the opening and closing tag of the MainContent <section> element. If you were already famil- iar with versions of HTML before HTML5, you may a bit surprised by the new elements such as header, section, and footer. These elements were introduced in HTML5 to give a better semantic structure to your documents. Refer to Chapter 1 for a quick introduction to HTML5. 3. Open the Styles.css file from the Styles folder. If you added some code to this file earlier, remove that code first. c03.indd 79c03.indd 79 10/8/2012 9:46:52 AM10/8/2012 9:46:52 AM
    • 80 x CHAPTER 3 DESIGNING YOUR WEB PAGES 4. At the top of the CSS file, type the following code that uses an ID selector to select the header element: header { } 5. Position your mouse between the curly braces, right-click, and choose Build Style from the context menu. The Modify Style dialog box shown in Figure 3-6 appears. FIGURE 3-6 6. In the Category list on the left, click Background and then open the drop-down list for the back- ground color. From the color picker that appears, click the Silver color, as shown in Figure 3-7. Alternatively, you can type the hexadecimal color code for Silver (#C0C0C0) in the background- color text box directly. 7. Switch to the Position category by clicking it in the list on the left. The panel that appears enables you to set position-related information, including the height and width. Under width, enter 844 and make sure that px is selected in the drop-down list at the right. For the height, enter 86. Click OK to dismiss the dialog box and to insert the declarations into your code, which now looks like this: header { background-color: #C0C0C0; width: 844px; height: 86px; } c03.indd 80c03.indd 80 10/8/2012 9:46:52 AM10/8/2012 9:46:52 AM
    • An Introduction to CSS x 81 FIGURE 3-7 8. Repeat steps 4 through 7, this time creating the following rules. If you prefer, you could also type in this code directly in the code editor. * { font-family: Arial; } h1 { font-size: 20px; } #PageWrapper { width: 844px; margin: auto; } nav { width: 844px; } section#MainContent { width: 664px; float: left; c03.indd 81c03.indd 81 10/8/2012 9:46:52 AM10/8/2012 9:46:52 AM
    • 82 x CHAPTER 3 DESIGNING YOUR WEB PAGES } aside { background-color: Gray; width: 180px; float: left; } footer { background-color: #C0C0C0; width: 844px; clear: both; } The float and clear properties are in the Layout category of the Modify Style dialog box, whereas the text-decoration property is in the Font category. Since the Universal selector (*) applies to all elements in your site, it’s common to move it to the top of the CSS above, even above the header selector, which you could do now. 9. When you’re done creating the rules, save and close the Styles.css file, because you’re done with it for now. 10. Open the Default.aspx file again and switch to Design View. From the Solution Explorer, drag the Styles.css file from the Styles folder onto the page. You should immediately see the Design View change to reflect the code you wrote in the style sheet. When you drop the style sheet on the page, VS inserts code in the <head> section of the page in Markup View that attaches the style sheet to the document: <head runat="server"> <title></title> <style type="text/css"> .auto-style1 { color: #FF0000; } </style> <link href="Styles/Styles.css" rel="stylesheet" type="text/css" /> </head> You can also drag an existing style sheet from the Solution Explorer directly in the <head> section of a page in Markup View. When you do that, VS adds the same <link> element although the order of the attributes could be slightly different. 11. Since the site uses HTML5, you need a browser that supports this latest HTML version for the page to render correctly. For older browsers, such as Internet Explorer 8 and below, you can use a nifty JavaScript library called Modernizr. One of the many features of this library is dynamically adding support for new HTML elements such as nav, section and aside through JavaScript. c03.indd 82c03.indd 82 10/8/2012 9:46:52 AM10/8/2012 9:46:52 AM
    • An Introduction to CSS x 83 Adding Modernizr to your site is very easy using the Package Manager Console that ships with Visual Studio. To add the library, follow these steps: 1. Choose Tools Í Library Package Manager Í Package Manager Console. 2. Type the following command and press Enter: Install-Package Modernizr 3. After a short delay, your site is expanded with a file called packages.config that keeps track of the installed packages and a Scripts folder that now contains the file modernizr- 2.6.2.js. Note: your version number could be different if a newer version of Modernizr has been released by the time you read this book. To add this library to your page, open Default.aspx in Markup View and drag the file from the Solution Explorer to the head sec- tion of the code, directly after the link to the style sheet. You should end up with this code: <link href="Styles/Styles.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="Scripts/modernizr-2.6.2.js"></script> </head> You should add the Modernizr library to your site even if you have a modern web browser. Since you can’t control the browsers visiting your site, you want to make sure everybody sees your site as intended. Adding Modernizr fixes the HTML5 compatibility issues for older browsers while hardly causing any overhead. You can learn more about Modernizr on its website at http://modernizr .com/. You’ll see a lot more about the Package Manager Console in Chapter 11. 12. Finally, save the changes to all open documents (press Ctrl+Shift+S) and then request Default .aspx in your browser. Your screen should look similar to Figure 3-8, which shows the page in Mozilla Firefox. FIGURE 3-8 c03.indd 83c03.indd 83 10/8/2012 9:46:53 AM10/8/2012 9:46:53 AM DownloadfromWow!eBook<www.wowebook.com>
    • 84 x CHAPTER 3 DESIGNING YOUR WEB PAGES How It Works The Style Builder makes it easy to select CSS properties and change their values. You don’t need to memorize every little detail about CSS, but instead you can create your CSS code visually. Once you get a better understanding of CSS and its many properties and values, you may find yourself entering CSS in the CSS file directly, because that’s often quicker to do. Note that the header, PageWrapper, nav, and footer elements have an exact width of 844 pixels. This way, the site fits nicely on screens with a size of 1024 x 768 pixels, a common screen size for many of today’s computers, without being squeezed between the Windows borders. Systems with bigger screens simply center the site in the available space. This centering is done by the PageWrapper element, which has its margin set to auto. This means that the available space on the left and right sides (but not at the top and bottom) is equally divided, effectively centering the PageWrapper element in the middle of the browser window. Note also that the MainContent section and the aside are positioned next to each other. You do this with the CSS float property: section#MainContent { width: 664px; float: left; } aside { background-color: Gray; width: 180px; float: left; } This tells the MainContent to “float” on the left side of content that follows it, effectively placing the aside to the right of it. You need to tell the aside to float as well; if you leave it out, it will be placed at the left of the page, right where it was before you applied the CSS. If you have multiple aside elements in your site (which is a common practice), you can target this aside that acts as a sidebar by adding an id attribute (such as Sidebar) just as I did with the MainContent section element and then update the CSS as follows: aside#Sidebar { ... } The combined width of the MainContent and aside elements adds up to 844 pixels, which is exactly the width of their parent element: the PageWrapper. To end the float and tell the footer element to be placed directly under the MainContent and aside elements, the clear property is used to clear any float (left or right) that may be in effect: footer { background-color: #C0C0C0; width: 844px; clear: both; } c03.indd 84c03.indd 84 10/8/2012 9:46:53 AM10/8/2012 9:46:53 AM
    • An Introduction to CSS x 85 The gray backgrounds are just temporarily added to the code, so it’s easier to see what <div> ends up where. In future exercises, you modify the CSS file again to fit the scheme of the Planet Wrox website. To tell the browser what styles to apply, you link the style sheet in the head of the page: <link href="Styles/Styles.css" rel="stylesheet" type="text/css" /> This tells the browser to look in the Styles folder for a file called Styles.css and apply all rules in that file to the current document. Once the browser has downloaded the CSS file, it applies all the styles it finds in there to your HTML elements, resulting in the layout shown in Figure 3-8. In this exercise, you saw how to link an external style sheet to a page using the <link> tag. However, you have more ways to include style sheets in your web pages. Adding CSS to Your Pages The first way to add CSS style sheets to your web pages is through the <link> element that points to an external CSS file, as you saw in the previous exercise. Take a look at the following <link> to see what options you have when embedding a style sheet in your page: <link href="StyleSheet.css" rel="Stylesheet" type="text/css" media="screen" /> The href property points to a file within your site, just as you saw in the previous chapter when you created links between two pages. The rel and type attributes tell the browser that the linked file is in fact a cascading style sheet. The media attribute is quite interesting: it enables you to target differ- ent devices, including the screen, printer, handheld devices, and even Braille and aural support tools for visually impaired visitors. The default for the media attribute is screen, so it’s OK to omit the attribute if you’re targeting standard desktop browsers. You briefly saw the second way to include style sheets at the beginning of this chapter: using embed- ded <style> elements. The <style> element should be placed at the top of your ASPX or HTML page, between the <head> tags. Within the <style> tags, you can write the exact same CSS you saw earlier. For example, to change the appearance of an <h1> element in the current page only, you can add the following code to the <head> of your page: <head runat="server"> <title></title> <style type="text/css"> h1 { color: Blue; } </style> </head> The third way to apply CSS to your HTML elements is to use inline styles with the style attribute that you saw in the previous chapter. Because the style attribute is already applied to a specific HTML element, you don’t need a selector and you can write the declaration in the attribute directly: <span style="color: White; background-color: Black;"> This is white text on a black background. </span> c03.indd 85c03.indd 85 10/8/2012 9:46:53 AM10/8/2012 9:46:53 AM
    • 86 x CHAPTER 3 DESIGNING YOUR WEB PAGES Choosing among External, Embedded, and Inline Style Sheets Because you have so many options to add style sheets to your site, what’s the best method to use? In general, you should give preference to external style sheets over embedded styles, which in turn are preferred over inline styles. External style sheets enable you to change the appearance of the entire site through a single file. Make one change to your external style sheet file, and all pages that use this style sheet pick up the change automatically. However, it’s perfectly acceptable to use embedded and inline styles as well in certain circum- stances. If you want to change the look of a single page, without affecting other pages in your site, an embedded style sheet is your best choice. The same applies to inline styles: if you only want to change the behavior of a single element in a single page, and you’re pretty sure you’re not going to need the same declaration for other HTML elements, you could use an inline style. An important thing to consider is the way that the various types of style sheets override each other. If you have multiple identical selectors with different property values, the one defined last takes pre- cedence. For example, consider a rule defined in an external style sheet called Styles.css that sets the color of all <h1> tags to green: h1 { color: Green; } Now imagine you’re attaching this style sheet in a page that also has an embedded rule for the same h1 but that sets a different color: <link href="Styles/Styles.css" rel="stylesheet" type="text/css" /> <style type="text/css"> h1 { color: Blue; } </style> With this code, the color of the actual <h1> tag in the page will be blue. This is because the embed- ded style sheet that sets the color to blue is defined later in the page, and thus overrides the setting in the external file. If you turn the styles around like this, <style type="text/css"> h1 { color: Blue; } </style> <link href="Styles/Styles.css" rel="stylesheet" type="text/css" /> the heading will be green, because the setting in the external style sheet now overrules that of the embedded style. The same principle applies to inline styles. Because they’re defined directly on the HTML elements, their settings take precedence over embedded and external style sheets. It’s also good to know that CSS generally overrules attributes on HTML elements. For example, if you have a CSS rule that sets the width and height of an image, the height and width attributes c03.indd 86c03.indd 86 10/8/2012 9:46:53 AM10/8/2012 9:46:53 AM
    • Working with CSS in Visual Studio x 87 on the img element are ignored. For example the image in this code snippet ends up as a 100-pixel square: img { height: 100px; width: 100px; } ... <img src="SomeImage.jpg" width="200px" height"200px" /> NOTE There’s a lot more to CSS than what is shown here. To learn more about CSS, pick up a copy of Beginning CSS: Cascading Style Sheets for Web Design, 3rd Edition Wrox, 2011 by Richard York and Ian Pouncey (ISBN: 978-0-470-89152-0). In general, it’s recommended that you attach external files at the top of the <head> section, followed by embedded style sheets. That way, the external file defines the global look of elements, and you can use embedded styles to overrule the external settings on a page-by-page basis. VS makes it easy to move embedded style sheets to an external CSS file, something you learn how to do in the next section, which discusses the remainder of the CSS tools in VS. WORKING WITH CSS IN VISUAL STUDIO The previous version of VS already had a number of great tools on board to make working with CSS as easy as possible, including: ‰ The CSS Properties Grid, which enables you to change property values. ‰ The Manage Styles window, which enables you to organize styles in your site, changing them from embedded to external style sheets and vice versa; reorder them; link existing style sheets to a document; and create new inline, embedded, or external style sheets. ‰ The Apply Styles window, which you can use to choose from all available styles in your site and quickly apply them to elements in your page. ‰ The Style Builder, which you can use to visually create declarations, as you saw earlier. In VS 2012, the CSS tools have been greatly enhanced and now support the following options as well: ‰ Hierarchical indenting, which makes your CSS code easier to understand. ‰ Smarter IntelliSense features, which makes it easy to enter CSS code manually. ‰ A number of helpful editor features such as the ability to easily comment and uncomment code, wrap code in collapsible regions, a color picker, and code snippets. The next sections give you a detailed look at these tools. c03.indd 87c03.indd 87 10/8/2012 9:46:53 AM10/8/2012 9:46:53 AM
    • 88 x CHAPTER 3 DESIGNING YOUR WEB PAGES Using the CSS Editor The CSS text editor in VS hosts a number of powerful features, demonstrated in the next Try It Out exercise. TRY IT OUT Trying Out the CSS Editor In this exercise you modify the Styles.css file you created earlier by adding a few new styles. Along the way you’re introduced to a number of the CSS editor features listed earlier. 1. Open the Styles.css file from the Styles folder and locate the section#MainContent selector. Right below its closing curly brace, add the following CSS selector that targets links (a elements) in the MainContent section: section#MainContent a { } 2. Between the opening and closing curly brace type color, followed by a colon (:) and then by a hash symbol (#). As soon as you type the hash symbol, VS presents you with a color picker. If you click the down arrow at the right of the color picker, it expands and shows more options, visible in Figure 3-9. This color picker has a few interesting features. Firstly, the top row of colored squares contains a list of colors that are defined in your style sheet. This is a great way to quickly pick a color you’ve already been using for another selector. The list of recognized colors is then followed by a vertical bar, which in turn is followed by some default colors that VS adds for you. In Figure 3-9 you can see two recognized colors: a light and a dark shade of gray. The other colors are all defaults. Secondly, you can mix your own color by dragging the mouse over the large square in the middle as well as over the colored vertical bar on the right. Finally, using the tiny color picker icon at the bottom right of the screen, you can quickly select a color from any other Windows application or your desktop. This is a great way to retrieve the color from an image you may have opened in some graphics program, for example. If you want to type in your own color information, simply ignore the color picker (or close it by pressing the Esc key). For this exercise, click a green square, which inserts the hexadecimal value (such as #4cff00) for the color for you. Complete the line of code by entering a semicolon and then press Enter. 3. On this new line type the letter t. This brings up the IntelliSense list and shows you all properties that start with the letter t as shown in Figure 3-10. FIGURE 3-9 c03.indd 88c03.indd 88 10/8/2012 9:46:53 AM10/8/2012 9:46:53 AM
    • Working with CSS in Visual Studio x 89 FIGURE 3-10 Next, type the letter d. The list is filtered further as you can see in Figure 3-11. FIGURE 3-11 Notice how this filtering is done in a pretty smart way. The filter does not only limit the list to properties that start with or contain the letters td (which in this case don’t exist), but it also sup- ports what is called a title case search where it lists items that have each word in the property begin with the letters you’re searching for. In this case, td matches items such as text-decora- tion as well as transition-delay. If you type tdc instead, the list would only show text-dec- oration-color. The same applies to all other CSS properties. For example, bc would give you background-color, bbw gives you border-bottom-width, and so on. This makes it extremely easy to write CSS code with only a few keystrokes. Note how some items in the list have an icon with a pair of scissors instead of the standard prop- erty icon. The scissors icon indicates a code snippet that you can expand by pressing tab twice. Doing so inserts browser-specific CSS into the file that is used for CSS properties that are not yet widely implemented by all browsers. Continue this exercise by selecting text-decoration from the list. You can double-click the value, press Enter, or press Tab, and VS completes the property for you. Next, type a colon and then underline as the value for the text-decoration property. Close the line with a semicolon. Your final code should now look like this: section#MainContent a { color: #4cff00; text-decoration: underline; } c03.indd 89c03.indd 89 10/8/2012 9:46:54 AM10/8/2012 9:46:54 AM
    • 90 x CHAPTER 3 DESIGNING YOUR WEB PAGES 4. Add two more style rules below the one you just created with the following code: section#MainContent a:visited { color: #FF0000; text-decoration: underline; } section#MainContent a:hover { color: #FFA500; text-decoration: underline; } 5. Next, choose Edit Í Format Document from the main menu. Alternatively, press Ctrl+K followed by Ctrl+D. This shortcut and menu command are available for other types of files as well, such as HTML, ASPX, Visual Basic, and C# files. When executed, they format the document according to the settings for that particular file type. In the case of CSS, it formats your code by placing the opening curly brace at a consistent location, and indenting and for- matting the individual rules. It also performs what’s called a hier- archical indent. To best understand how this works, take a look at Figure 3-12, which depicts the section#MainContent rule set as well as the new selectors for the a elements you added earlier after you’ve formatted the document. Notice how the section#MainContent a rule set has been indented below the section#MainContent rule set. This helps to understand the relationship between the two selectors used by the rule set (section#MainContent a only targets a elements within a parent section element with an id of MainContent). Likewise, the section#MainContent a:visited and section#MainContent a:hover rule sets are indented below the a element because they can be considered “children” of the a element. If you don’t like this behavior, you can turn it off using Tools Í Options Í Text Editor Í CSS Í Formatting. Alternatively, press Ctrl+Q to put focus on the Quick Launch box, type CSS Formatting and press Enter. This opens the same Options dialog box. While you’re there, spend some time browsing around the items under the Text Editor node to get an idea of how you can change the formatting of the many languages that VS supports. 6. The final two editor features worth showing here are regions and comments. If your CSS code becomes unwieldy, it may help to wrap some parts of the code that belong together in a region. A region in VS can then be collapsed to hide the code, and expanded again when you need to change it. To create a region, you wrap the code in a region / endregion pair using CSS comment syntax. For example: /*#region Name Of Region */ … Your CSS code here /*#endregion*/ For this exercise, add the opening region statement with a name of Main Content (/*#region Main Content */) right above the section#MainContent rule set, and the closing statement FIGURE 3-12 FIGURE 3-13 c03.indd 90c03.indd 90 10/8/2012 9:46:54 AM10/8/2012 9:46:54 AM
    • Working with CSS in Visual Studio x 91 (/*#endregion*/) below the section#MainContent a:hover rule set. Once the region is cre- ated, in Figure 3-13 you now see a minus (-) icon in the gutter next to the text editor. You can now collapse the region by clicking the minus icon. VS hides the code block and shows the name of the region instead, as shown in Figure 3-14. This makes it really easy to get some code out of the way when working with large code files. Note: regions are also supported by other file types such as C# and VB files although each language uses a slightly different syntax. The region feature in VS makes use of standard CSS comments syntax. This means that the browser ignores the region code as well as its name. To comment out other code (so it’s not interpreted by the browser), select some text and then press Ctrl+K followed by Ctrl+C (for Comment). The code is then commented out using /* and */, as shown in Figure 3-15. To uncomment the code again, press Ctrl+K followed by Ctrl+U (for Uncomment). Both com- mands are also available in the Edit Í Advanced menu and on the Styles toolbar. You can also start a comment manually by typing /*. VS then inserts the closing */ for you automatically. 7. Save the changes to the CSS file. You can leave the region code in, but make sure you uncomment any code you may have commented out in the preceding step. 8. Switch to the Default.aspx page and, if necessary, switch to Design View. Select the text “look around” in the paragraph. If you typed something else in an earlier Try It Out, select that text instead. At this stage, all that’s important is that you have some text to turn into a link. 9. On the Formatting toolbar, click the Convert to Hyperlink button (with the link symbol and arrow on it), click the Browse button in the dialog box that appears, and select Default.aspx in the root of the site. This way, the link points to the same page it’s defined in, which is fine for this exercise. Click OK twice to dismiss the dialog boxes. 10. Save the changes to all open documents (choose File Í Save All from the main menu or press Ctrl+Shift+S) and then request Default.aspx in your browser by pressing Ctrl+F5. You should see the page appear with the “look around” link underlined, as shown in Figure 3-16, which shows the page in Google Chrome. 11. Hover your mouse over the “look around” link; note that it turns to orange. 12. Notice how the link to www.PlanetWrox.com is green (provided you haven’t visited this site before), whereas the link to Default.aspx is red (because you’re currently viewing Default.aspx, the browser marks this page as “visited”.) If you visit the Planet Wrox website and then come back to your Default.aspx page again, the link to the Planet Wrox site will have turned red as well. Hovering over it still turns it to orange. If you want to test the page in another browser, right-click Default.aspx in the Solution Explorer and choose Browse With from the context menu. If your alternate browser is listed there already, select it from the list and then click Browse. Optionally, you can make this browser your default by clicking the Set as Default button. FIGURE 3-14 FIGURE 3-15 c03.indd 91c03.indd 91 10/8/2012 9:46:55 AM10/8/2012 9:46:55 AM
    • 92 x CHAPTER 3 DESIGNING YOUR WEB PAGES If your browser is not listed, click the Add button and then the ellipsis next to the Program Name box to search for your favorite browser. When the browser is displayed in the list, click it to select it and then click Browse to open the page in that browser. The page should now appear in your alternate browser. FIGURE 3-16 How It Works This exercise started off by showing you some of the features of the CSS editor in VS. The IntelliSense list filtering and title case search are great time savers when writing CSS code. You’ll need some time to get used to them, but once you have the hang of it you don’t want to work without them. The :hover and :visited parts on the a selector you added are probably new to you. These selec- tors are called pseudo class selectors. The a:visited selector is applied only to links that the user has already visited in the browser. The a:hover selector is applied only to the <a> tag when the user hovers the mouse over the link. When you open the page in the browser, the updated style sheet is downloaded and the browser then applies the a:visited rule set to all links in the MainContent section you visited before. When you hover your mouse over a link, the rule set section#MainContent a:hover is applied, causing the link to turn orange. Viewing your pages in different browsers is a good thing to do. Although modern browsers tend to render a page more and more similarly, subtle differences exist that you need to be aware of and handle in your HTML and CSS code. Installing a few different browsers on your system (Internet Explorer, Firefox, Safari, Opera, and Chrome, for example), assigning them to the Browse With dialog box as shown in this Try It Out, and testing your pages in these browsers as often as you can will help to ensure your pages look exactly right in the majority of the browsers. Useful as external style sheets may be, sometimes you really want to use embedded or inline styles instead. Creating and managing those styles, explained in the next section, is just as easy. c03.indd 92c03.indd 92 10/8/2012 9:46:56 AM10/8/2012 9:46:56 AM
    • Working with CSS in Visual Studio x 93 Creating Embedded and Inline Style Sheets When you’re working with a page in Design View, you often need to make minor tweaks to part of the page, like styling a piece of text, aligning an image, or applying a border to an element. At this stage, you need to make a decision about whether to create an inline, embedded, or external style sheet. As you saw earlier, you should opt for external or embedded style sheets if you envision you’re going to reuse a style later. VS doesn’t care much, though. It enables you to create styles at all three levels. Even better, it enables you to easily upgrade an embedded style to an external one, or copy inline style infor- mation to a different location, giving you great flexibility and the option to change your mind later. In the next exercise, you see how to create inline and embedded style sheets. You see later how to move those styles to an external style sheet, enabling other pages to reuse the same styles. TRY IT OUT Creating Embedded and Inline Styles in a Page In this Try It Out, you add a style rule to the <h1> element of the page, to remove the default margin that a browser draws around the heading. In addition, you style the first paragraph using a class attri- bute, giving it a different look to make it stand out from the other paragraphs on the page. 1. Go back to VS and make sure that the Default.aspx page is open in Design View. 2. Click once on the <h1> element in the Document Window to select it and then choose Format Í New Style. The New Style dialog box appears (visible in Figure 3-17), which is pretty similar to the Modify Style dialog box you saw earlier. FIGURE 3-17 c03.indd 93c03.indd 93 10/8/2012 9:46:56 AM10/8/2012 9:46:56 AM
    • 94 x CHAPTER 3 DESIGNING YOUR WEB PAGES 3. At the top of the screen, open the Selector drop-down list and choose (inline style). It’s the first item in the list. This ensures that the new style is applied as an inline style to the <h1> element. 4. Switch to the Box category, shown in Figure 3-18. This dialog box has a handy diagram that serves as a refresher on the CSS Box Model, showing you where the properties padding, border, and margin end up. By default, browsers draw some white space above or below an <h1> element, but the actual amount differs between browsers. To give each browser the same consistent settings, you can reset the padding to 0 and then apply a little bit of margin at the bottom of the heading, which creates some distance to the elements following it. To do this, set padding to 0 in the top box and clear the value from the drop-down list next to the text box. By leaving the Same for All option selected, VS creates a shorthand declaration for you. Then uncheck Same for All for the margin section, enter 0 for the top, right, and left boxes, and clear the value from the drop-down next to each value. Next, enter 10 for the bottom text box and make sure px is selected in the drop-down list. Your screen should now look like Figure 3-18. FIGURE 3-18 Click OK to close the dialog box and apply the changes to the heading. You end up with the fol- lowing <h1> element with an inline style in Markup View: <h1 style="padding: 0; margin: 0 0 10px 0"> Hi there visitor and welcome to Planet Wrox </h1> c03.indd 94c03.indd 94 10/8/2012 9:46:56 AM10/8/2012 9:46:56 AM
    • Working with CSS in Visual Studio x 95 5. Next, in Design View, select the first paragraph by clicking it. A small glyph appears to indi- cate you selected a <p> element, as visible in Figure 3-19. The Tag Selector at the bottom of the Document Window should highlight the <p> element. FIGURE 3-19 6. With the paragraph still selected, choose Format Í New Style from the main menu. This time, instead of creating an inline style, type the text .Introduction in the Selector box that is visible in Figure 3-20. Don’t forget the dot (.) in front of the selector’s name. 7. At the top of the screen, select the check box for Apply New Style to Document Selection. With this setting on, the new class you’re about to create is applied to the <p> element that you have selected. 8. From the font-style drop-down list, choose italic. Your New Style dialog box should now look like Figure 3-20. FIGURE 3-20 9. Finally, click OK. Note that the entire paragraph is now displayed with an italic font. 10. With the <p> element still selected, open the CSS Properties Grid (see Figure 3-21) by choosing View Í CSS Properties. This grid gives you an overview of all the CSS properties and shows which ones are currently active for your page. c03.indd 95c03.indd 95 10/8/2012 9:46:56 AM10/8/2012 9:46:56 AM
    • 96 x CHAPTER 3 DESIGNING YOUR WEB PAGES FIGURE 3-21 This grid shows a list of applied rules in the top part of the window in the order in which they are applied. The bottom part of the window is used to show the CSS properties for those rules. In Figure 3-21 you see the rules that are applicable to the .Introduction selector. 11. Locate the color property in the CSS Properties Grid and set it to a dark blue color, like #003399. To achieve this, open the drop-down list for the property value and choose a color from the color picker. If the color you’re looking for is not available, click the More Colors button to bring up the extended color picker, shown in Figure 3-22. FIGURE 3-22 Instead of using the color picker, you can also type a value in the Properties Grid directly. This is how many of the properties work in the CSS Properties Grid: they let you enter values directly or enable you to change the value visually using a drop-down list or a button with ellipses at the end of the property’s value box. Figure 3-23 shows the different options you have for the font-style property in a convenient drop-down list. Take special note of the three buttons at the top of the window, because they house some use- ful functionality. The first two buttons enable you to switch between categorized mode and c03.indd 96c03.indd 96 10/8/2012 9:46:57 AM10/8/2012 9:46:57 AM
    • Working with CSS in Visual Studio x 97 alphabetical mode, making it easier to find the right property. The third button enables you to dis- play the applied properties at the top of the list or at their default location in the list. FIGURE 3-23 12. Finally, save all changes and open Default.aspx in your browser (see Figure 3-24). You’ll see that the first paragraph is now displayed with a blue and italic font except for the link in the text, which is green or red depending on whether you visited that site before. Additionally, if you followed all the instructions from the previous chapter, the text “paying a visit” is red, set by the embedded CSS class. FIGURE 3-24 13. Switch back to VS and look at your page in Markup View. In the <head> section of the page, you should see the following embedded style sheet: .Introduction { font-style: italic; color: #003399; c03.indd 97c03.indd 97 10/8/2012 9:46:57 AM10/8/2012 9:46:57 AM
    • 98 x CHAPTER 3 DESIGNING YOUR WEB PAGES } </style> <link href="Styles/Styles.css" rel="stylesheet" type="text/css" /> How It Works The numerous tools that VS offers make it easy to write CSS for your website. You don’t need to hand code anything, or remember all the different properties that the CSS standard supports. Instead, you can simply choose them from different lists on the CSS Properties Grid. This grid enables you to enter values manually but also offers handy tools to select colors, files, items from drop-down lists and more. All changes you make in the Properties Grid are applied to the relevant style sheet, whether you’re working with an inline, embedded, or external style sheet. At the same time, the Design View is updated to reflect the new CSS options you have set. When you look at the <h1> element, you can see that VS created an inline style with padding set to 0 to affect all four sides at once, and margin set to 0 0 10px 0 to control all four sides individually. Once you have created a bunch of useful and reusable styles, you need a way to apply your existing styles to other pages or HTML elements. You see how this works next. Applying Styles If you have some experience with Microsoft Word, you may be familiar with the Styles dialog box, which lists all available styles and enables you to apply them to selected portions of text. This way, you can quickly apply identical formatting to blocks of text. This works similarly in VS. With the Apply Styles window — accessible by choosing View Í Apply Styles from the main menu — you can easily apply style rules to elements in the page. TRY IT OUT Using the Apply Styles Window In this exercise, you reuse the .Introduction class and apply it to the second paragraph of the page as well. That way, both paragraphs end up looking the same. 1. Still in Default.aspx, make sure you’re in Design View and then select the second paragraph of the page by clicking it. Ensure that the Tag Selector at the bottom of the Document Window shows that the <p> element is selected, and not another one like <strong> that may be part of the <p> element. If you have only one paragraph of text, create a new one first (by pressing Enter after the first paragraph in Design View), enter some text, and then select that paragraph. 2. Open the Apply Styles window by choosing View Í Apply Styles. Make sure the window is not accidentally docked in the main Document Window, but either floats or is placed at the side of the Document Window. This window shows all the selectors it finds in the current page and any attached style sheet. If you don’t see all the styles shown in Figure 3-25, click the Options button and choose Show All Styles. c03.indd 98c03.indd 98 10/8/2012 9:46:57 AM10/8/2012 9:46:57 AM
    • Working with CSS in Visual Studio x 99 FIGURE 3-25 3. Click the Introduction class in the CSS Styles list. VS adds a class attribute to the <p> tag: <p class="Introduction"> Feel free to have a <a href="Default.aspx">look around</a>; there are lots of interesting <strong>reviews and concert pictures</strong> to be found here. </p> If you want to apply multiple classes, hold down the Ctrl key while clicking one of the other classes in the list. This applies a list of classes separated by a space to the element’s class attri- bute. You can follow the same steps to apply the selected style in Markup View as well. 4. Using the Clear Styles button, you can quickly remove existing classes and inline styles from a tag. Consider the HTML fragment you saw in the previous chapter when you used the Formatting tool- bar to format text in the page. If you used the Foreground Color button, you ended up with code similar to this: We&#39;re glad you&#39;re <span class="auto-style1">paying a visit</span> To remove the class attribute, select the <span> tag in the Tag Selector, or simply click the <span> tag in Markup View and then click Clear Styles in the Apply Styles window, which you can see below the toolbar in Figure 3-25. You’ll end up with this HTML: We&#39;re glad you&#39;re paying a visit Because an empty <span> around the text has no use, VS removes it for you as well. In addition, VS also removes the auto-style1 rule because it’s no longer used by any code on the page. Removing style attributes from HTML elements works the same way. How It Works Once again, VS is able to keep all relevant windows in sync: the Design View, Markup View, and the various CSS design tools. When you apply a class from the Apply Styles window, VS adds the requested class to the selected HTML element in Markup View. It then also updates the Design View window. Similarly, when you remove a selector or a declaration from an embedded style in Design View, both the Design View and the CSS tools windows are updated. c03.indd 99c03.indd 99 10/8/2012 9:46:57 AM10/8/2012 9:46:57 AM
    • 100 x CHAPTER 3 DESIGNING YOUR WEB PAGES The final CSS functionality you need to look at in this chapter is located on the Manage Styles and Apply Styles windows. Besides helping you attach CSS files to your documents, these windows enable you to manage your styles easily. Managing Styles Because it’s so easy to add new inline and embedded styles, your pages may quickly become a mess with styles all over the place. To achieve reusability, you should move as much of your inline and embedded styles as possible to an external style sheet. This is exactly what the Apply Styles and Manage Styles windows enable you to do. TRY IT OUT Managing Styles with the Manage Styles and Apply Styles Windows Earlier in this chapter, you modified the <h1> element and applied padding and margin to the head- ing. However, Default.aspx is not the only page that could benefit from this style for a heading, so it makes sense to move it to the Styles.css file. Similarly, the Introduction class seems reusable enough to include it in the Styles.css file so other pages can access it. This Try It Out shows you how to move styles around in your site. 1. Make sure that Default.aspx is still open and switch to Markup View if necessary. 2. Locate the <h1> element and click it once. VS highlights the tag in the Tag Selector at the bottom of the Document Window to indicate it’s the active tag. 3. Open the Apply Styles window by choosing View Í Apply Styles from the main menu. Alternatively, if you have the win- dow docked with other windows, simply click its tab to make it active. Again, make sure the window is not accidentally docked in the main Document Window, but either floats or is placed at the side of the Document Window. At the bottom of the Apply Styles window, you’ll see an inline style appear (see Figure 3-26). 4. Right-click Inline Style and choose New Style Copy. The New Style dialog box appears, enabling you to create a new style based on the current selection. At the top of the window, choose h1 from the Selector drop-down list, and from the Define In drop-down list choose Existing style sheet. From the URL drop-down list, choose Styles/Styles.css. If that item isn’t available, click the Browse button to locate and select it. Your dialog box should end up like Figure 3-27. 5. Click OK to close the dialog box. VS creates a copy of the h1 style and places it in the Styles .css file. VS creates a new selector for h1 in the Styles.css file instead of adding the padding and margin info to the existing rule set. If you want, you could combine the two selectors into one manually. 6. In the Apply Styles window, right-click Inline Style again, and this time choose Remove Inline Style from the context menu. This removes the style attribute from the h1 element. FIGURE 3-26 c03.indd 100c03.indd 100 10/8/2012 9:46:57 AM10/8/2012 9:46:57 AM
    • Working with CSS in Visual Studio x 101 FIGURE 3-27 7. From the main menu, choose View Í Manage Styles. Again, make sure the window is placed beside the Document Window and not docked in the Document Window. Under the Current Page item, locate the .Introduction selector. 8. Click the .Introduction selector once, and then drag it into the area for Styles.css, for example dropping it after the h1 selector. Note that VS draws lines between the selectors as you hover over them to indicate the point where the selector will end up. Figure 3-28 shows how the .Introduction selector is dragged from the current page into Styles.css, between the h1 and #PageWrapper selectors. 9. Once you drop the selector in the Styles.css section of the Manage Styles window, the associated style is removed from your current page, and then inserted in Styles.css. Because that CSS file is included in your current page using the <link /> element, you won’t see a difference in Design View. You can now remove the empty <style> element from Default .aspx, because it’s not needed anymore. FIGURE 3-28 c03.indd 101c03.indd 101 10/8/2012 9:46:58 AM10/8/2012 9:46:58 AM
    • 102 x CHAPTER 3 DESIGNING YOUR WEB PAGES 10. If you haven’t already merged the two h1 selectors, open Styles.css and scroll down to the end of the file. Copy the two lines for the padding and margin properties to the clipboard and then delete the entire selector. Scroll up in the file and then paste the two CSS rules inside the other h1 selector. You should end up with this code: h1 { font-size: 20px; padding: 0; margin: 0 0 10px 0; } 11. Save any pending changes you may have and then open Default.aspx in your browser by pressing Ctrl+F5. Note that the paragraphs haven’t changed and still use the same blue and italic font. How It Works Unfortunately, VS doesn’t allow you to move inline styles to external style sheet files. However, by creating a copy of the existing style, and then deleting the original inline style, you can achieve the same effect. Moving embedded or external style sheets between files is a lot easier. You can simply drag a style from one file to another, and VS will automatically move the code for you. This makes it extremely easy to organize your CSS. Instead of leaving all your embedded CSS in your page because you’re afraid to touch it, you can now simply drag and drop it into an external file. This makes it a lot easier to reuse those styles in other pages, decreasing page size and page bloat, and making your site a lot easier to manage. Obviously, it’s important that the file you are moving your CSS to is attached to the pages you’re working with. PRACTICAL TIPS ON WORKING WITH CSS Follow these tips to make the most of CSS: ‰ Take some time to familiarize yourself with the many properties that CSS supports. The best way to do this is to create a brand-new page in your Demos folder, create a few HTML elements like <div> and <p> tags, and then simply experiment with all the different proper- ties. By trying out many of the properties on the CSS Properties Grid, you get a feel for what options you have available. This makes it easier later if you want to apply a certain effect to some piece of content. ‰ When creating custom CSS classes, try to come up with names that describe the behavior of the rule, rather than the look and feel. For example, a class called .Introduction to style the first paragraph of a page is a good description. It enables you to change the underly- ing values without affecting the actual meaning of the name. But classes with names like .BlueAndItalic are guaranteed to give you problems later. What if you decide to change the blue to black later? You either end up with a very odd class name not describing its own c03.indd 102c03.indd 102 10/8/2012 9:46:58 AM10/8/2012 9:46:58 AM
    • Summary x 103 behavior, or you’ll need to rename the class and then update the entire site, changing refer- ences to the old class to .BlackAndItalic. ‰ Try to create smaller and reusable rule sets that you can combine if required, rather than creating large, monolithic rules that can only be used on a single UI element. For example, instead of creating a style like this: .ImportantHeading { color: Red; font-size: 20px; font-weight: bold; } You’re better off creating a few lightweight rules that are easier to reuse: h1 { font-size: 20px; } .Attention { color: Red; font-weight: bold; } When you apply the .Attention class to a heading like this: <h1 class="Attention">, you get the exact same behavior you got when you gave it the ImportantHeading class. However, with the separate Attention class, you have created a reusable rule that you can apply to other elements that need the user’s attention, like <p> or <span> elements. SUMMARY This chapter gave you a good look at CSS, the most important language for styling your ASPX and HTML web pages. CSS enables you to overcome the limitations of HTML with respect to styling your web pages because it is designed to minimize page bloat, give you greater control over the look of your page, and generally help you create websites that load quicker and that are easier to maintain. Once you have a good understanding of the CSS terminology, you’ll find it’s easy to work with the many CSS tools that VS has on board. Tools like the Manage Styles and Apply Styles windows, the Style Builder, and the smart IntelliSense in the code editor make writing and managing CSS very easy. You can apply CSS not only to HTML as you’ve seen in this chapter, but also to ASP.NET Server Controls. The CSS you apply to those controls eventually ends up in the browser as plain HTML where the same principles apply as those you’ve seen in this chapter. The next chapter gives you a detailed look at the many available ASP.NET Server Controls. c03.indd 103c03.indd 103 10/8/2012 9:46:58 AM10/8/2012 9:46:58 AM
    • 104 x CHAPTER 3 DESIGNING YOUR WEB PAGES EXERCISES 1. What is the main benefit of using an external style over embedded style sheets? 2. Write a CSS rule that changes the appearance of all headings at level one (h1) in your page to the following: ‰ The heading uses an Arial font face. ‰ The heading should be blue. ‰ The heading must have a font size of 18 pixels. ‰ The heading has a blue, thin border at the top and left sides. For the last requirement, check out VS’s IntelliSense list in a CSS file to discover another short- hand version for the border property. 3. Which of the two following rules is easier to reuse across pages in your website? Can you explain why? #MainContent { border: 1px solid Blue; } .BoxWithBorders { border: 1px solid Blue; } 4. VS enables you to attach an external style sheet to a page in a number of different ways. Can you name two different options to do this? You can find answers to these exercises in Appendix A. c03.indd 104c03.indd 104 10/8/2012 9:46:58 AM10/8/2012 9:46:58 AM
    • Summary x 105 WHAT YOU LEARNED IN THIS CHAPTER CSS Cascading style sheets, the language used to lay out web pages in the browser CSS Box Model The model on which the dimensions of elements are calculated with regard to height, width, padding, border, and margin Declaration A combination of a property and a value that determines the styling for the element to which the declaration applies Embedded style sheets CSS code that is defined in a page in a <style /> element. Usually referred to as embedded styles. External style sheets CSS code that is defined in a separate file and then included in a page using the <link /> element Inline style sheets CSS code that is defined directly on an element using the style attribute. Usually referred to as inline styles. Rule set A combination of a selector and one or more declarations wrapped in a pair of curly braces Selector A CSS construct to point to one or more elements in the page. Different selectors exist, including the Universal selector, the ID and Class selectors, and the Type selector. c03.indd 105c03.indd 105 10/8/2012 9:46:58 AM10/8/2012 9:46:58 AM
    • c03.indd 106c03.indd 106 10/8/2012 9:46:59 AM10/8/2012 9:46:59 AM
    • Working with ASP.NET Server Controls WHAT YOU WILL LEARN IN THIS CHAPTER: ‰ What ASP.NET Server Controls are ‰ The different kinds of server controls you have at your disposal ‰ The common behavior shared among most of the server controls ‰ How the ASP.NET run time processes the server controls on your page ‰ How server controls are able to maintain their state across postbacks WROX.COM CODE DOWNLOADS FOR THIS CHAPTER You can find the wrox.com code downloads for this chapter on the Download Code tab at www.wrox.com/remtitle.cgi?isbn=1118311809. The code is in the Chapter 4 download. ASP.NET Server Controls are the workhorses of ASP.NET. Almost all the Web Forms pages you build in Visual Studio (VS) will contain one or more server controls. These controls come in all sorts and sizes, ranging from simple controls like a Button and a Label to complex controls like the TreeView and the ListView that are capable of displaying data from a data source (like a database or an XML file). You see these controls in Chapters 7, 13, and 14. The architecture of ASP.NET Server Controls is deeply integrated into ASP.NET, giving the controls a feature set that is quite unique in today’s technologies for building websites. This chapter shows you what server controls are, how they work, and which ones are available out of the box when you install VS. 4 c04.indd 107c04.indd 107 10/8/2012 9:50:55 AM10/8/2012 9:50:55 AM
    • 108 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS The chapter starts off with a general discussion of server controls. You see how to define them in your code by adding them to Design or Markup View. The section that follows gives you a thorough look at the many controls that are available in the VS Toolbox. INTRODUCTION TO SERVER CONTROLS It’s important to understand how server controls operate and how they are completely different from the way you define controls in other languages like classic ASP or PHP (another popular program- ming language for creating dynamic websites). For example, to influence the text in a text box in these languages, you would use plain HTML and mix it with server-side code. This works similarly to the example in Chapter 2 where the current date and time are displayed on the page. To create a text box with a message and the current time in it in classic ASP, you can use the following code: <input type="text" value="Hello World, the time is <%=Time()%>" /> As you can see, this code contains plain HTML, mixed with a server-side block, delimited by <% and %> that outputs the current time using the equals (=) symbol. This type of coding has a major disadvantage: the HTML and server-side code is mixed, making it difficult to write and maintain your pages. Although this is a trivial example in which it’s still easy to understand the code, this type of programming can quickly result in very messy and complex pages. Server controls work differently. In ASP.NET, the controls “live” on the server inside an ASPX page. When the page is requested in the browser, the server-side controls are processed by the ASP.NET run time—the engine that is responsible for processing requests for ASPX pages. The controls then emit client-side HTML code that is appended to the final page output. It’s this HTML code that eventually ends up in the browser, where it’s used to build up the page. So, instead of defining HTML controls in your pages directly, you define an ASP.NET Server Control with the following syntax, where the italicized parts differ for each control: <asp:TypeOfControl ID="ControlName" runat="server" /> For the controls that ship with ASP.NET 4.5 you always use the asp: prefix followed by the name of the control. For example, to create a TextBox that can hold the same welcome message and cur- rent time, you can use the following syntax: <asp:TextBox ID="Message" runat="server" /> Note that the control has two attributes: ID and runat. The ID attribute is used to uniquely identify a control on the page, so you can program against it. It’s important that each control on the page has a unique ID; otherwise the ASP.NET run time won’t understand what control you’re refer- ring to. If you accidentally type a duplicate control ID, VS signals the problem in the error list. The mandatory runat attribute is used to indicate that this is a control that lives on the server. Without this attribute, the controls won’t be processed and will end up directly in the HTML source. If you ever feel you’re missing a control in the final output in the browser, ensure that the control has this c04.indd 108c04.indd 108 10/8/2012 9:50:59 AM10/8/2012 9:50:59 AM
    • Introduction to Server Controls x 109 required attribute. Note that for non-server elements, like plain HTML elements, the runat attri- bute is optional. With this attribute, non-server controls can be reached by your programming code. You learn more about this later in the book. You can easily add the runat attribute to an existing element using a code snippet by typing runat and pressing the Tab key. The preceding example of the TextBox uses a self-closing tag where the closing slash (/) is embed- ded in the opening tag. This is quite common for controls that don’t need to contain child content such as text or other controls. However, the long version, using a separate closing tag, is acceptable as well: <asp:TextBox ID="Message" runat="server"></asp:TextBox> You can control the default behavior of closing tags per element using Tools Í Options Í Text Editor Í HTML Í Formatting Í Tag Specific Options. You can program against this text box from code that is either placed inline with the page or in a separate Code Behind file, as you saw in Chapter 2. To set the welcome message and the time, you can use the following code: VB.NET Message.Text = "Hello World, the time is " & DateTime.Now.TimeOfDay.ToString() C# Message.Text = "Hello World, the time is " + DateTime.Now.TimeOfDay.ToString(); The definition of the control in the markup section of the page is now separated from the actual code that defines the text displayed in the text box, making it easier to define and program the text box (or any other control) because it enables you to focus on one task at a time. You can either declare the control and its visual appearance in the markup section of the page, or program its behavior from a code block. In general, controls defined in Markup View are not case-sensitive, although some of the values you can set are case-sensitive. I prefer to use the capitalization as suggested by IntelliSense. Note that when using C#, properties you use in the Code Behind are case-sensitive. You see how server controls send their underlying HTML to the client in the next exercise. TRY IT OUT Working with Server Controls In this exercise, you add a TextBox, a Label, and a Button control to a page. When you request the page in the browser, these server controls are transformed into HTML, that is then sent to the client. By looking at the final HTML for the page in the browser, you’ll see how the HTML is completely dif- ferent from the initial ASP.NET markup. 1. Open the Planet Wrox project in Visual Studio. 2. In the Demos folder in the Solution Explorer, create a new Web Form called ControlsDemo.aspx. Choose your programming language and make sure the Web Form uses Code Behind. c04.indd 109c04.indd 109 10/8/2012 9:50:59 AM10/8/2012 9:50:59 AM
    • 110 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS 3. Switch to Design View. From the Standard category of the Toolbox, drag a TextBox, a Button, and a Label control onto the design surface within the dashed lines of the <div> tag that was added for you when you created the page. Type the text Your name in front of the TextBox and add a line break between the Button and the Label by positioning your cursor between the two controls in Design View and then press- ing Enter. If you’re having trouble positioning the cursor between the controls, place it after the Label control and then press the left arrow key twice. The first time you press it, the Label is selected; the second time, the cursor is placed between the two controls, enabling you to press Enter. Your Design View should now look like Figure 4-1. FIGURE 4-1 Right-click the Button control and choose Properties to open up the Properties Grid for the control. Pressing F4 after selecting the Button does the same thing. The window that appears, shown in Figure 4-2, enables you to change the properties for the control, which in turn influ- ences the way the control looks and behaves at run time. FIGURE 4-2 5. Set the control’s Text property to Submit Information and set its ID (which you’ll find all the way down at the bottom of the list wrapped in parentheses) to SubmitButton. 6. Change the ID of the TextBox to YourName using the Properties Grid. c04.indd 110c04.indd 110 10/8/2012 9:50:59 AM10/8/2012 9:50:59 AM
    • Introduction to Server Controls x 111 7. Clear the Text property of the Label using the Properties Grid. You can right-click the property’s label in the grid and choose Reset, or you can remove the text manually. Set its ID to Result. 8. Still in Design View, double-click the Button control to have VS add some code to the Code Behind of the page that will be fired when the button is clicked in the browser. You see later how to accomplish the same thing from Markup View. Add the bolded line of code to the code block that VS inserted for you: VB.NET Protected Sub SubmitButton_Click(sender As Object, e As EventArgs) Handles SubmitButton.Click Result.Text = "Your name is " & YourName.Text End Sub C# protected void SubmitButton_Click(object sender, EventArgs e) { Result.Text = "Your name is " + YourName.Text; } Note that the VB.NET example doesn’t need an underscore here to split the code over two lines. In older versions of VB.NET, the underscore was required to split this code over two lines. 9. Save the changes to the page and then open it in the browser by pressing Ctrl+F5. Don’t click the button yet, but open up the source of the page by right-clicking the page in the browser and choos- ing View Source or View Page Source. You should see the following HTML code (I changed the formatting slightly so the HTML fits on the page): <div> Your name <input name="YourName" type="text" id="YourName" /> <input type="submit" name="SubmitButton" value="Submit Information" id="SubmitButton" /> <br /> <span id="Result"></span> </div> 10. Switch back to your browser, fill in your name in the text box, and click the button. When the page is done reloading, open up the source for the page in the browser again using the browser’s right- click menu. The code should now look like this: <div> Your name <input name="YourName" type="text" value="Imar" id="YourName" /> <input type="submit" name="SubmitButton" value="Submit Information" id="SubmitButton" /> <br /> <span id="Result">Your name is Imar</span> </div> Note that the two bold lines have changed, and now show the name you entered in the text box. You can ignore the other HTML in the page for now. c04.indd 111c04.indd 111 10/8/2012 9:50:59 AM10/8/2012 9:50:59 AM DownloadfromWow!eBook<www.wowebook.com>
    • 112 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS How It Works As its name implies, an ASP.NET Server Control lives on the server in your ASPX page where it can be processed by the ASP.NET run time. When you request a page in the browser, the run time creates an in-memory representation of the ASPX file with the controls you created. When the run time is about to send the HTML to the browser, it asks each of the controls in the page for their HTML, which is then injected in the final response. For example, when the Label control is asked for its HTML the first time it loads, it returns the following: <span id="Result"></span> Although you defined the Label control with the <asp:Label> syntax, it ends up as a simple <span> element in the browser. Because the Text property of the Label control is empty, you don’t see any text between the two <span> tags. The same applies to other controls; an <asp:TextBox> ends up as <input type="text">, whereas the <asp:Button> ends up as <input type="submit">. When you click the button, the control causes a postback, which sends the information for the controls in the page to the server, where the page is loaded again. Additionally, the code that you wrote to han- dle the button’s Click event is executed. This code takes the name you entered in the text box and then assigns it to the Label control as shown in this C# example: Result.Text = "Your name is " + YourName.Text; Don’t worry about the syntax for the code that handles the button’s Click event for now. In Chapter 5, you see how this works, and why you need this code. At this stage, the Label control contains the text you entered in the text box, so when it is asked for its HTML, it now returns this: <span id="Result">Your name is Imar</span> You get a more in-depth look at postbacks later in this chapter when the ASP.NET state engine is discussed. A CLOSER LOOK AT ASP.NET SERVER CONTROLS Because you’ll be working with server controls most of the time when building your ASP.NET Web Forms pages, you need to know in detail how they work and how to use them. In the next section, you see how to add the controls to your pages and change the way they behave in the browser. In the section that follows, you get an overview of the behavior that all server controls have in common. Once you understand this shared behavior, it’s easy to apply this knowledge to other, new controls as well, enabling you to get up to speed with them very quickly. Defining Controls in Your Pages As demonstrated in the previous Try It Out, you can simply drag controls from the Toolbox onto the design surface of the page. This makes it very easy to add a bunch of controls to a page to get you c04.indd 112c04.indd 112 10/8/2012 9:51:00 AM10/8/2012 9:51:00 AM
    • A Closer Look at ASP.NET Server Controls x 113 started. However, because of the way the design surface works, it’s sometimes difficult to add them exactly where you want them. For example, it can be difficult to drag a control between the opening and closing tags of an HTML element. Fortunately, you can just as easily drag a control from the Toolbox in Markup View. Additionally, you can also type the control’s markup directly in Markup View, letting IntelliSense and code snippets help you with the different tags and attributes. You’ll also find that the Properties Grid works in Markup View. Simply click the relevant markup, and the Properties Grid is updated to reflect the tag you clicked. This makes it easy to change the properties of the control, while you can still see exactly what markup gets generated for you. If you’ve worked with older versions of VS, you’ll appreciate one great new feature in VS 2012: you can now bind handlers (such as the Click event used in the preceding exercise) directly in Markup View without switching to Design View. You’ll also be able to access the Smart Tasks panel for the controls from code. You see more of these features later in this chapter. If you look at the Properties Grid for some of the controls in a page, you’ll notice that many of them have similar properties. In the next section, you see exactly what these properties are and what they are used for. Common Properties for All Controls Most of the server controls you find in the VS Toolbox share some common behavior. Part of this behavior includes the so-called properties that define the data a control can contain and expose. You learn more about properties and other behavior types in the next chapter. Each server control has an ID to uniquely identify it in the page, a runat attribute that is always set to server to indicate the control should be processed on the server, and a ClientID that contains the client-side ID attribute that is assigned to the element in the final HTML. In versions of ASP.NET up to 3.5 this ClientID was always generated for you automatically. However, in ASP.NET 4 a new ClientIDMode property was introduced that gives you more control over the ID of an element at the client. You see how this works in later chapters. The runat attribute is technically not a property of a server control, but is necessary to indicate that the markup for the control should be processed as a server control and not end up as plaintext or HTML in the browser. Besides these properties, many of the server controls share more properties because they share the same Control base class. The next chapter digs deeper into base classes and inheritance. The fol- lowing table lists the most common shared properties and describes what they are used for. PROPERTY DESCRIPTION AccessKey Enables you to set a key with which a control can be accessed at the client by pressing the associated letter. BackColor ForeColor Enables you to change the color of the background (BackColor) and text (ForeColor) of the control. BorderColor BorderStyle BorderWidth Changes the border of the control in the browser. The similarities with the CSS border properties you saw in the previous chapter are no coincidence. Each of these three ASP.NET properties maps directly to its CSS counterpart. continues c04.indd 113c04.indd 113 10/8/2012 9:51:00 AM10/8/2012 9:51:00 AM
    • 114 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS PROPERTY DESCRIPTION CssClass Enables you to define the HTML class attribute for the control in the browser. This class name could then point to a CSS class you defined in the page or an external CSS file. Enabled Determines whether the user can interact with the control in the browser. For example, with a disabled text box (Enabled="False") you cannot change its text. Font Enables you to define different font-related settings, such as size, family and whether or not the font should be bold. Height Width Determines the height and width of the control in the browser. TabIndex Sets the client-side HTML tabindex attribute that determines the order in which users can move through the controls in the page by pressing the Tab key. ToolTip Enables you to set a tooltip for the control in the browser. This tooltip, rendered as a title attribute in the HTML, is shown when the user hovers the mouse over the element. Visible Determines whether or not the control is sent to the browser. You should really see this as a server-side visibility setting because an invisible control is never sent to the browser at all. This means it’s quite different from the CSS display and visibility properties you saw in the previous chapter that hide the ele- ment at the client. To see how all these attributes end up in the browser, consider the following markup for a TextBox server control: <asp:TextBox AccessKey="a" BackColor="Black" ForeColor="White" Font-Size="30px" BorderColor="Yellow" BorderStyle="Dashed" BorderWidth="4" CssClass="TextBox" Enabled="True" Height="40" Width="200" TabIndex="1" ToolTip="Hover text here" Visible="True" ID="TextBox1" runat="server" Text="Hello World"> </asp:TextBox> When you request the page with this control in the browser, you end up with the following HTML: <input name="TextBox1" type="text" value="Hello World" id="TextBox1" accesskey="a" tabindex="1" title="Hover text here" class="TextBox" style="color:White; background-color:Black;border-color:Yellow;border-width:4px; border-style:Dashed;font-size:30px;height:40px;width:200px;" /> This results in the text box shown in Figure 4-3. (continued) c04.indd 114c04.indd 114 10/8/2012 9:51:00 AM10/8/2012 9:51:00 AM
    • A Closer Look at ASP.NET Server Controls x 115 FIGURE 4-3 Note that most of the server-side control properties have been converted into CSS inline styles with the style attribute. When building websites, it’s quite uncommon to define a TextBox in this manner. As you learned in the previous chapter, you should avoid inline styles as much as possible, and opt for external cascading style sheets instead. You can accomplish the exact same behavior with this server-side control: <asp:TextBox ID="TextBox1" AccessKey="a" CssClass="TextBox" TabIndex="1" ToolTip="Hover text here" runat="server" Text="Hello World"> </asp:TextBox> And the following CSS class: .TextBox { background-color: Black; color: White; font-size: 30px; border-color: Yellow; border-style: Dashed; border-width: 4px; height: 40px; width: 200px; } Obviously, the second example is much easier to read, reuse, and maintain. If you want another text box with the exact same look, you simply assign TextBox to the CssClass of that control. Also, notice I left out the Enabled and Visible properties. Both default to True, so there’s no need to explicitly state that in the control declaration. Although it’s recommended to use CSS classes instead of these inline styles, it’s good to know about the server-side control properties in case you need fine control over them. If you change the control’s properties programmatically (as you learn how to do later), they still end up as inline styles, and thus possibly override settings in embedded or external style sheets. c04.indd 115c04.indd 115 10/8/2012 9:51:00 AM10/8/2012 9:51:00 AM
    • 116 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS Now that you have seen the generic behavior that all server controls share, it’s time to look at the large number of controls that ship with ASP.NET 4.5. TYPES OF CONTROLS Out of the box, ASP.NET 4.5 comes with a large number of server controls, supporting most of your web development needs. To make it easy for you to find the right controls, they have been placed in separate control categories in the VS Toolbox (accessible by pressing Ctrl+Alt+X). Figure 4-4 shows the Toolbox with all the available categories. Note that depending on your version of Visual Studio, you may have other categories as well. A handy new feature in VS 2012 is the ability to search in the Toolbox. Just type in a few letters of the control you’re looking for in the Search text box at the top of the control, and VS filters the list with controls matching your criteria. In the following sections, you see the controls in each category and the tasks for which they are designed. With the discussion of the various controls, you see a mention of the properties of a control. For example, a TextBox has a Text property (among many others), and a ListBox has a SelectedItem property. Some properties can only be set programmatically and not with the Properties Grid. Reading and changing control properties programmatically is discussed in detail in the next chapter. Standard Controls The Standard category contains many of the basic controls that almost any web page needs. You’ve already seen some of them, like the TextBox, Button, and Label controls earlier in this chapter. Figure 4-5 shows all the controls in the Standard category. Many of the controls probably speak for themselves, so instead of giving you a detailed description of them all, the following sections briefly highlight a few important ones. Simple Controls The Toolbox contains a number of simple and straightforward controls, including TextBox, Button, Label, HyperLink, RadioButton, and CheckBox. Their icons in the Toolbox give you a good clue as to how they end up in the browser. In the remainder of this book, you see these con- trols used many times. In ASP.NET 4.5 the TextMode property of the TextBox control has been expanded to support new HTML5 types such as DateTime, Email, and Number. You see more about this later in the book. c04.indd 116c04.indd 116 10/8/2012 9:51:00 AM10/8/2012 9:51:00 AM
    • Types of Controls x 117 FIGURE 4-4 FIGURE 4-5 List Controls The standard category also contains a number of controls that present themselves as lists in the browser. These controls include ListBox, DropDownList, CheckBoxList, RadioButtonList, and BulletedList. To add items to the list, you define <asp:ListItem> elements between the opening and closing tags of the control, as shown in the following example: <asp:DropDownList ID="FavoriteLanguage" runat="server"> <asp:ListItem Value="C#">C#</asp:ListItem> <asp:ListItem Value="Visual Basic">Visual Basic</asp:ListItem> <asp:ListItem Value="CSS">CSS</asp:ListItem> </asp:DropDownList> c04.indd 117c04.indd 117 10/8/2012 9:51:00 AM10/8/2012 9:51:00 AM
    • 118 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS The DropDownList enables a user to select only one item at a time. To see the currently active and selected item of a list control programmatically, you can look at its SelectedValue, SelectedItem, or SelectedIndex properties. SelectedValue returns a string that contains the value for the selected item, like C# or Visual Basic in the preceding example. SelectedIndex returns the zero-based index of the item in the list. With the preceding example, if the user had chosen C#, SelectedIndex would be 0. Similarly, if the user had chosen CSS, the index would be 2 (the third item in the list). For controls that allow multiple selections (like CheckBoxList and ListBox), you can loop through the Items collection and see what items are selected. In this case, SelectedItem returns only the first selected item in the list; not all of them. You learn how to access all the selected items in the next exercise. Note that in the browser, both the DropDownList and the ListBox control render as a <select> element. Attributes such as size and multiple set by these two controls determine the appearance and behavior of the HTML element in the browser. The BulletedList control doesn’t allow a user to make selections, and as such doesn’t support these properties. To see how to add list items to your list control, and how to read the selected values, the following exercise guides you through creating a simple Web Form with two list controls that ask users for their favorite programming language. TRY IT OUT Working with List Controls In this exercise you add two list controls to a page. Additionally, you add a button that, when clicked, displays the selected items as text in a Label control. 1. In the Demos folder, create a new Web Form called ListControls.aspx. Make sure you create a Code Behind file by checking the Place Code in Separate File option. 2. Switch to Design View and drag a DropDownList from the Toolbox onto the design surface of the page within the dashed border of the <div> element that is already present in your page. 3. Notice that as soon as you drop the DropDownList control on the page, a pop-up menu appears that is labeled DropDownList Tasks, as shown in Figure 4-6. This pop-up menu is called the Smart Tasks panel. When it appears, it gives you access to the most common tasks of the control it belongs to. In the case of the DropDownList, you get three options. The first option enables you to bind the control to a data source, which is demonstrated in Chapter 13. The second item enables you to manually add items to the list, and the last option sets the AutoPostBack property of the control. With this option checked, the control submits the page in which it is contained back to the server as soon as the user chooses a new item from the list. Note that the browser must have JavaScript enabled for this to work. FIGURE 4-6 c04.indd 118c04.indd 118 10/8/2012 9:51:01 AM10/8/2012 9:51:01 AM
    • Types of Controls x 119 The Smart Tasks panel appears only for the more complex controls that have a lot of features. You won’t see it for simple controls like Button or Label. To reopen the Smart Tasks panel, right-click the control in the designer and choose Show Smart Tag. Alternatively, click the small arrow at the top-right corner of the control, visible in Figure 4-6, or press Shift+Alt+F10 when the control is selected. You can also open the Smart Tasks panel from markup view. Simply click anywhere on the opening or closing tag of a control or other piece of markup and press Ctrl+Dot (Ctrl+.). Alternatively, hover over the tiny blue rectangle at the start of the opening tag and then click the grey arrow that appears. On the Smart Tasks panel of the DropDownList, click the Edit Items link to bring up the ListItem Collection Editor, shown in Figure 4-7. FIGURE 4-7 This dialog box enables you to add new items to the list control. The items you add through this window are added as <asp:ListItem> elements between the tags for the control. 4. Click the Add button on the left side of the screen to insert a new list item. Then in the Properties Grid on the right, enter C# for the Text property and press Tab. As soon as you tab away from the Text property, the value is copied to the Value property as well. This is convenient if you want both the Text and the Value property to be the same. However, it’s perfectly OK (and quite com- mon) to assign a different value to the Value property. c04.indd 119c04.indd 119 10/8/2012 9:51:01 AM10/8/2012 9:51:01 AM
    • 120 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS 5. Repeat step 4 twice, this time creating list items for Visual Basic and CSS. You can use the up and down arrow buttons in the middle of the dialog box to change the order of the items in the list. Finally, click OK to insert the items in the page. You should end up with the following code in Markup View: <asp:DropDownList ID="DropDownList1" runat="server"> <asp:ListItem>C#</asp:ListItem> <asp:ListItem>Visual Basic</asp:ListItem> <asp:ListItem>CSS</asp:ListItem> </asp:DropDownList> 6. In Markup View drag a CheckBoxList control from the Toolbox directly into the code window, right after the DropDownList. 7. Copy the three <asp:ListItem> elements from the DropDownList you created in steps 4 and 5 and paste them between the opening and closing tags of the CheckBoxList. You should end up with this code: <asp:ListItem>CSS</asp:ListItem> </asp:DropDownList> <asp:CheckBoxList ID="CheckBoxList1" runat="server"> <asp:ListItem>C#</asp:ListItem> <asp:ListItem>Visual Basic</asp:ListItem> <asp:ListItem>CSS</asp:ListItem> </asp:CheckBoxList> 8. Switch to Design View and drag a Button from the Toolbox in Design View to the right of the CheckBoxList control. The Button will be placed below the CheckBoxList. Next, drag a Label control and drop it to the right of the Button. Create some room between the Button and the Label by positioning your cursor between the controls and then pressing Enter twice. Double-click the Button to open the Code Behind of the page. 9. In the code block that VS added for you, add the following bolded code, which will be executed when the user clicks the button: VB.NET Protected Sub Button1_Click(sender As Object, e As EventArgs) _ Handles Button1.Click Label1.Text = "In the DDL you selected " & DropDownList1.SelectedValue & "<br />" For Each item As ListItem In CheckBoxList1.Items If item.Selected = True Then Label1.Text &= "In the CBL you selected " & item.Value & "<br />" End If Next End Sub C# protected void Button1_Click(object sender, EventArgs e) { Label1.Text = "In the DDL you selected " + c04.indd 120c04.indd 120 10/8/2012 9:51:01 AM10/8/2012 9:51:01 AM
    • Types of Controls x 121 DropDownList1.SelectedValue + "<br />"; foreach (ListItem item in CheckBoxList1.Items) { if (item.Selected == true) { Label1.Text += "In the CBL you selected " + item.Value + "<br />"; } } } Notice how in the VB.NET code the underscore is needed to split the code over two lines. VB.NET requires the underscore if you want to move the Handles keyword to its own line. 10. Save the changes to the page and then request it in the browser. Choose an item from the DropDownList, check one or more items in the CheckBoxList, and click the button. You should see something similar to Figure 4-8, which shows the page in Firefox. FIGURE 4-8 How It Works The various list controls all use <asp:ListItem> elements. That makes it easy to reuse them by copying them from one control to another. Because the DropDownList supports only one selected item at a time, it’s pretty easy to get its selected value. All it takes is a single line of code (shown in C#): Label1.Text = "In the DDL you selected " + DropDownList1.SelectedValue + "<br />"; c04.indd 121c04.indd 121 10/8/2012 9:51:01 AM10/8/2012 9:51:01 AM
    • 122 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS The CheckBoxList control enables a user to select multiple items at once. Therefore, you need a bit more code to loop over the collection of items, checking the Selected property of each item (again shown in C#): foreach (ListItem item in CheckBoxList1.Items) { if (item.Selected == true) { Label1.Text += "In the CBL you selected " + item.Value + "<br />"; } } The CheckBoxList and the other list controls have an Items collection that contains all the items you defined in the code. So, given the code from this Try It Out, CheckBoxList1 contains three items, for C#, Visual Basic, and CSS, respectively. Each ListItem in turn contains a Selected property that determines whether or not the user has checked the item in the list. Using a foreach loop (For Each in VB.NET), you can iterate over the collection of ListItem elements, testing the Selected property one by one. If the item was selected in the list, its Selected property is true (True in VB) and its Value is appended to the text of the Label. Notice the use of += (&= in VB.NET) in the last code example to assign the Value of the list item together with the text to the Label control’s Text property. The += and &= syntax is shorthand for this: Label1.Text = Label1.Text + "In the CBL you selected" + item.Value + "<br />"; This code takes the current text from the Label control, appends the literal text "In the CBL you selected" to it, then appends the value of the item using item.Value and finally appends the literal text "<br />". It then reassigns the entire string back to the Text property of the label. Using the += syntax is often a bit easier to write and understand, but the longer version is common as well. Both VB.NET and C# have support for a for each loop, although both languages use a slightly different syntax. In the next chapter, you learn a lot more about looping and other language constructs. Also of note is the way the ListItems are set up. In the first example, before the Try It Out, you saw ListItem elements with both a value and text: <asp:ListItem Value="C#">C#</asp:ListItem> <asp:ListItem Value="Visual Basic">Visual Basic</asp:ListItem> <asp:ListItem Value="CSS">CSS</asp:ListItem> When you add items to the list yourself with the ListItem Collection Editor, you don’t get the Value attributes: <asp:ListItem>C#</asp:ListItem> <asp:ListItem>Visual Basic</asp:ListItem> <asp:ListItem>CSS</asp:ListItem> You didn’t get the Value attribute because you didn’t supply an explicit value for the item in the ListItem Collection Editor. If you omit the Value, the text between the opening and closing tags of the ListItem is used implicitly as the value, which is fine in many cases. However, it’s also quite com- mon to have a different Value and Text property in the list. For example, when you have a list with countries, you could use the full name of the country as the Text (like The Netherlands) and use the official country code (nl) as the Value for the drop-down list. You see the list controls at work in other chapters in this book. c04.indd 122c04.indd 122 10/8/2012 9:51:01 AM10/8/2012 9:51:01 AM
    • Types of Controls x 123 Container Controls Quite often it’s desirable to group related content and controls. You can do this by putting the controls (and other markup) in one of the container controls, like the Panel, the PlaceHolder, the MultiView, or the Wizard. For example, you can use the PlaceHolder or the Panel control to hide or show a number of controls at once. Instead of hiding each control separately, you simply hide the entire container that contains all the individual controls and markup. Both of these controls have their own advantages and disadvantages. The good thing about the PlaceHolder control is that it emits no HTML of its own into the page, so you can use it as a container without any side effects in the final page. However, it lacks design-time support, making it hard to manage the controls inside the PlaceHolder at design time in VS. In contrast, the Panel enables you to easily access all con- trols and other content it contains but renders itself as a <div> element. In many cases this isn’t a problem, and can even be useful as you can target that div using CSS at the client, so usually you’re best off with the Panel control because of its design-time support. The MultiView (which can contain one or more <asp:View> elements) and the Wizard are similar in that they enable you to split up a long page into multiple areas, making it easy to fill in a long form, for example. The Wizard has built-in support for moving from page to page using Previous, Next, and Finish buttons, whereas the MultiView must be controlled programmatically. A Closer Look at the Panel Control In the following exercise, you use a Panel control to create a container for other controls and markup. You only add some text for now, but in a subsequent Try It Out exercise you add ASP.NET controls to the panel. TRY IT OUT Using the Panel Control In this exercise you see how to use the Panel control as a container for some simple text. In addition, you use a CheckBox to control the visibility of the Panel at the server. 1. Start by creating a new Web Form with Code Behind called Containers.aspx in the Demos folder. 2. Switch the page into Design View and drag a CheckBox and a Panel control from the Toolbox on the design surface into the dashed <div> element. 3. Give the CheckBox control a meaningful description by setting its Text property to Show Panel and set its AutoPostBack property to True using the Properties Grid. Rather than choosing True from the drop-down list for the property, you can also double-click the AutoPostBack property or its value to toggle between False and True. 4. Set the Visible property of the Panel control to False using the Properties Grid. This hides the Panel control when the page first loads. 5. Inside the Panel control, type some text (for example, I am visible now). Note that the panel behaves like the rest of VS’s design surface. You can simply add text to it, select and format it, and add new controls to it by dragging them from the Toolbox. The code for the panel should end up like this in Markup View: <asp:Panel ID="Panel1" runat="server" Visible="False"> I am visible now </asp:Panel> c04.indd 123c04.indd 123 10/8/2012 9:51:02 AM10/8/2012 9:51:02 AM
    • 124 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS 6. If necessary, switch to Markup View and locate the code for the CheckBox. Position your cursor right before the closing forward slash (/) and type On, followed by Ctrl+Space. This brings up IntelliSense, as shown in Figure 4-9. FIGURE 4-9 Select OnCheckChanged by pressing Tab or Enter. Next, type an equals sign (=), which brings up IntelliSense again as shown in Figure 4-10. Note that if you’re using C#, you may also see a Page_ Load item in the list of event handlers. FIGURE 4-10 Select the <Create New Event> item and press Tab. VS completes the code as follows: OnCheckedChanged="CheckBox1_CheckedChanged" Although this auto-completion is nice, VS has done something else that’s much more useful: when you pressed Tab, it also added the handler code for you in the Code Behind. To see that code, press F7 to switch to Code View. NOTE I have wanted this feature since the very first version of Visual Studio for .NET, and I am really glad it has been added. With this new feature, the need to switch to Design View and set up the handler by double-clicking a control (as you did in an earlier exercise) or using the Events tab of the Properties Grid (as you see later) has been greatly reduced. This is great for people who prefer hand-coding over the Design View and is especially useful in more complex pages where Design View isn’t that useful anyway. c04.indd 124c04.indd 124 10/8/2012 9:51:02 AM10/8/2012 9:51:02 AM
    • Types of Controls x 125 Note that there is a subtle difference between adding the handler using Markup View and Design View if you’re using VB.NET. If you use Markup View, the handler is added to the markup (OnCheckedChanged="CheckBox1_CheckedChanged") and code is added to the Code Behind. When you use Design View, the code in Markup View is not affected, and the code in the Code Behind is annotated with the Handles keyword to indicate which event (for instance, the click on a button, the check changed event of a check box, and so on) the code responds to. At run time, however, there is no difference. 7. Next, add the following bolded line within the handler code that VS added for you: VB.NET Protected Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Panel1.Visible = CheckBox1.Checked End Sub C# protected void CheckBox1_CheckedChanged(object sender, EventArgs e) { Panel1.Visible = CheckBox1.Checked; } 8. Save all your changes and then request the page in the browser by pressing Ctrl+F5. 9. When the page first loads, all you see is the check box and the text beside it. When you look at the HTML for the page in the browser (right-click the page and choose View Source or View Page Source depending on your browser), you’ll only see the check box; there’s no code for the Panel control at this stage sent to the browser. When you click the check box to place a checkmark in it, the page reloads and now shows the text you entered in step 5. WARNING If nothing happens, go back to the source of the page in VS and ensure that AutoPostBack is set to True on the CheckBox control. If you look at the HTML in the browser, you’ll see that the text you typed in step 5 is wrapped in a <div> element with an id of Panel1: <div id="Panel1"> I am visible now </div> How It Works In step 4 of this exercise you set the Visible property of the Panel control to False. This means that when the page loads, the control is not visible on the server and thus its HTML never makes it to the browser. When you then check the check box, a postback occurs, which sends the information con- tained in the form to the server. At the server, some code is run that is fired whenever the check box changes its state from checked to unchecked or vice versa. Inside that code block, the following code is executed (shown in C#): Panel1.Visible = CheckBox1.Checked; c04.indd 125c04.indd 125 10/8/2012 9:51:02 AM10/8/2012 9:51:02 AM
    • 126 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS This means that the Panel is only visible when the check box is checked. When it isn’t, the Panel is hidden automatically. As you can see, it’s easy to add text and other markup to the Panel control in VS. Right now, you only added some plaintext, but in the next section you see how to add a Wizard control and how to use it. Magic with the Wizard Control The Wizard control is a great tool for breaking apart large Web Forms and presenting them as bite- sized chunks of information to the user. Instead of confusing your user with one page with many con- trols and text on it, you can break the page apart and present each section on a separate wizard page. The Wizard control then handles all navigation issues by creating Next, Previous, and Finish buttons automatically. In the following exercise you use a wizard to ask a user for her name and favorite programming language. Although the example itself is pretty trivial, and you could have placed both questions on the same page without confusing the user, the example shows how the wizard works and why it’s useful. You can easily apply the same techniques to your own, possibly larger, Web Forms. TRY IT OUT Using the Wizard to Create Easy-to-Use Forms In this Try It Out, you place a Wizard inside the panel you created in the previous exercise that enables a user to fill in a form that is spread over a couple of pages. The wizard will have two steps where a user can enter details, and a results page that shows the data the user has provided. 1. Make sure you still have Containers.aspx page open in Design View. Remove the text “I am vis- ible now” that you entered in the previous Try It Out, and then drag a Wizard control from the Toolbox inside the Panel. Drag its right edge further to the right, increasing the total width of the control to 500px. Your page now looks similar to Figure 4-11. 2. Open the Wizard’s Smart Tasks panel (click the arrow in its upper right-hand corner) and choose Add/Remove WizardSteps. In the dialog box that follows, click the Add button to insert a third wizard step, shown in Figure 4-12. FIGURE 4-11 c04.indd 126c04.indd 126 10/8/2012 9:51:02 AM10/8/2012 9:51:02 AM
    • Types of Controls x 127 FIGURE 4-12 3. Click the first WizardStep labeled Step 1 in the Members list on the left and change its Title from Step 1 to About You. Set the Title of the other two steps to Favorite Language and Ready, respectively. 4. Change the StepType of the second step (now labeled Favorite Language) to Finish, and of the last step to Complete. You can leave the StepType of the first step set to Auto. Click OK to close the WizardStep Collection Editor. 5. In Design View, click About You in the list at the left to make it the active step and drag a Label and a TextBox to the right side of the Wizard. You need to drag them inside the gray rectangle that’s in the upper-right corner of the Wizard, or the controls won’t end up inside the Wizard. Set the Text property of the Label to Type your name and change the ID of the TextBox to YourName. When you’re done, your Wizard looks like Figure 4-13. 6. Click the Favorite Language item in the list on the left to make it the active step. Add a DropDownList to the rectangle with the gray border on the right part of the wizard step. Rename the DropDownList by setting its ID to FavoriteLanguage. Open the Smart Tasks panel of the DropDownList control and choose Edit Items. Add the same three items you added in an earlier c04.indd 127c04.indd 127 10/8/2012 9:51:03 AM10/8/2012 9:51:03 AM
    • 128 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS Try It Out: for C#, Visual Basic, and CSS, respectively. If you want, you can copy the three items from the page ListControls.aspx and paste them between the <asp:DropDownList> tags inside the second step. You should end up with the following code for the second step: </asp:WizardStep> <asp:WizardStep runat="server" Title="Favorite Language" StepType="Finish"> <asp:DropDownList ID="FavoriteLanguage" runat="server"> <asp:ListItem>C#</asp:ListItem> <asp:ListItem>Visual Basic</asp:ListItem> <asp:ListItem>CSS</asp:ListItem> </asp:DropDownList> </asp:WizardStep> <asp:WizardStep runat="server" StepType="Complete" Title="Ready"> FIGURE 4-13 7. For the final step, switch to Markup View. If you try to switch to the last step in Design View, you may notice that the Wizard disappears. If that happens, switch to Markup View and set ActiveStepIndex to 0 again on the opening tag of the Wizard control. Inside the last WizardStep labeled Ready, drag a label control from the Toolbox and rename it by setting its ID to Result. Alternatively, inside the code for the last step, type the word label and then press Tab to execute a code snippet for inserting a Label. Then add the ID attribute manually. 8. Double-click the Wizard in Design View and add the following bolded code, which will be executed when the user clicks the Finish button on the last step of the wizard. If you’re having problems getting VS to create the correct code for you, as you see it in the next snippet, select the Wizard, press F4 to open up the control’s Properties Grid, and then click the button with the lightning bolt on it (the fourth but- ton from the left on the toolbar of the Properties Grid), as shown in Figure 4-14. This part of the Properties Grid is often referred to as the Events tab of the Properties Grid. Locate and double-click FIGURE 4-14 c04.indd 128c04.indd 128 10/8/2012 9:51:03 AM10/8/2012 9:51:03 AM
    • Types of Controls x 129 FinishButtonClick in the Action category. With both methods, you should end up with some code for Wizard1_FinishButtonClick that you need to extend with the following code: VB.NET Protected Sub Wizard1_FinishButtonClick(sender As Object, e As WizardNavigationEventArgs) Handles Wizard1.FinishButtonClick Result.Text = "Your name is " & YourName.Text Result.Text &= "<br />Your favorite language is " & FavoriteLanguage.SelectedValue End Sub C# protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e) { Result.Text = "Your name is " + YourName.Text; Result.Text += "<br />Your favorite language is " + FavoriteLanguage.SelectedValue; } 9. Switch back to Design View and open the Properties Grid for the Wizard and make sure its ActiveStepIndex is set to 0. The designer remembers the last step you designed and stores the value in the ActiveStepIndex of the Wizard in Markup View. To make sure the Wizard starts on the first page, you should always set the ActiveStepIndex back to 0 (or click the first step in the Wizard control in Design View) before you save your changes and run the page. 10. Save all changes, close all open browser windows, and press Ctrl+F5 to open the page in the browser. Select the check box to make the Panel visible and enter your name on the first wizard page. Click Next and choose your favorite programming language. Notice how there’s now a Previous button available that enables you to go back to the first step of the wizard if you want to change your name. Instead of clicking the Next and Previous buttons, you can also click the links on the left of the wizard in the browser. When you click the Finish button, you’ll see the results of the information you entered in the wizard (see Figure 4-15). FIGURE 4-15 c04.indd 129c04.indd 129 10/8/2012 9:51:03 AM10/8/2012 9:51:03 AM DownloadfromWow!eBook<www.wowebook.com>
    • 130 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS How It Works The Wizard control takes care of most of the hard work for you. It handles the navigation, determines when to show the correct buttons (Next, Previous, and Finish), and ensures that in the resulting page the values for the controls you added in the wizard steps are still available so you can show them with the label. It does this with a concept called View State, something you learn more about toward the end of this chapter. All you have to do is define the steps and set their StepType. You set the StepType of the first step to Auto. With this setting, the Wizard figures out what buttons to show. Because it’s the first step in the wizard and there’s no previous step to go to, it leaves out the Previous button (this is the equivalent of setting the StepType to Start manually.) You set the StepType of the second step to Finish, which tells the Wizard to draw a Previous button and a Finish button. When you click the Finish button, the Wizard arrives at the last step with its StepType set to Complete. On this step, the navigation buttons are hid- den, and all you see is the label with the result, which was assigned with the code in the Code Behind of the page. In Chapter 5, you learn more about the code in the Code Behind that makes this possible. In addition to the controls you have seen in the previous sections, a few other controls are worth examining. Not all of them are discussed here in detail because they aren’t used any further in this book. A good source of information about these controls is the Microsoft Developer Network (MSDN) site at http://msdn.microsoft.com. To find information about controls on this site, use your favorite search engine and then search for ControlName Control MSDN. For example, to find more information on the Wizard control you’d search for Wizard Control MSDN. Typically, the MSDN site is at the top of the search results. Other Standard Controls This section briefly discusses the remainder of the controls in the Standard category of the Toolbox. You see many of them used in the sample application in the rest of the book. LinkButton and ImageButton The LinkButton and the ImageButton controls operate similarly to an ordinary Button control. Both of them cause a postback to the server when they are clicked. The LinkButton presents itself as a simple <a> element, but posts back (using JavaScript) instead of requesting a new page. The ImageButton does the same, but displays an image that the user can click to trigger the postback. Image and ImageMap These controls are pretty similar in that they display an image in the browser. The ImageMap enables you to define hotspots on the image that, when clicked, either cause a postback to the server or navi- gate to a different page. Calendar The Calendar control presents a rich interface that enables a user to select a date. You see more of it toward the end of this chapter when the ASP.NET state engine is discussed. c04.indd 130c04.indd 130 10/8/2012 9:51:03 AM10/8/2012 9:51:03 AM
    • Types of Controls x 131 FileUpload The FileUpload control enables a user to upload files that can be stored on the server. You see more of this control in Chapter 14. Literal, Localize, and Substitute All three controls look a little like the Label control because they can all display static text or HTML. The biggest advantage of the Literal is that it renders no additional tag itself; it displays only what you assign to its Text property, and is thus very useful to display HTML or JavaScript that you build up in the Code Behind or that you retrieve from a database. The Localize control is used in multilingual websites and is able to retrieve its contents from trans- lated resource files. The Substitute control is used in advanced caching scenarios and enables you to update only parts of a page that is otherwise cached completely. Both of these controls fall outside the scope of this book, but for a good discussion of them you may want to get a copy of Wrox’s Professional ASP.NET 4.5 in C# and VB (ISBN: 978-1-118-31182-0). AdRotator The AdRotator control enables you to display random advertisements on your website. The ads come from an XML file that you create on your server. Because it lacks advanced features like click tracking and logging that are required in most but the simplest scenarios, this control isn’t used much in today’s websites. HiddenField The HiddenField control enables you to store data in the page that is submitted with each request. This is useful if you want the page to remember specific data without the user seeing it on the page. Because the field does show up in the HTML source of the page, and is thus accessible to the end user, you should never store any sensitive data in it. XML The XML control enables you to transform data from an XML format to another format (like XHTML) for display on a page. Check out Professional ASP.NET 4.5 for a detailed description. Table The <asp:Table> control is in many respects identical to its HTML <table> counterpart. However, because the control lives at the server, you can program against it, creating new columns and rows dynamically and adding dynamic data to it. This concludes the discussion of the controls in the Standard category of the Toolbox. In most web pages, you’ll be working with at least a few of these controls. The remainder of this section dis- cusses the other categories of the Toolbox. Because most of them are used in some form in the remain- der of this book, this chapter just briefly describes their purpose so you get a rough idea what they are used for. You’ll find cross-references to the other chapters where you can find out more information about them. c04.indd 131c04.indd 131 10/8/2012 9:51:03 AM10/8/2012 9:51:03 AM
    • 132 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS HTML Controls The HTML category of the Toolbox contains a number of HTML controls that look similar to the ones found in the Standard category. For example, you find the Input (Button) that looks like the <asp:Button>. Similarly, there is a Select control that has the <asp:DropDownList> and <asp:ListBox> as its counterparts. In contrast to the ASP.NET Server Controls, the HTML controls are client-side controls and end up directly in the final HTML in the browser. You can expose them to server-side code by adding a runat="server" attribute to them. This enables you to program against them from the Code Behind of a Web Form, to influence things like their visibility. The HTML controls have a lot less functionality than the ones in the Standard category. For exam- ple, the Select control lacks design-time support for adding new items to the list with the ListItem Collection Editor. This forces you to write the items by hand in the Markup View of VS. Because the controls in the Standard and HTML category look quite like each other, the next sec- tion discusses their differences and gives you some idea of when to favor one category over the other. How to Choose between Standard and HTML Controls There seems to be some overlap between the controls in the Standard and HTML categories of the Toolbox. So which ones should you choose and when? Generally, the true server controls in the Standard category offer you a lot more functionality, both in terms of design-time support in VS and what they can do at run time. But this functionality comes at a price. Because of their increased complexity, the server controls take a little more time to process. However, on most websites you probably won’t notice the difference. Only when you have a high-traffic website with lots of controls on the page do the HTML controls give you a slightly better performance and consume less memory on the server when compared to the server controls. In most scenarios, favor the server controls over their HTML counterparts. Because server controls offer more functionality, they give you more flexibility in your pages, enabling you to create a richer user experience. Also, the better design-time support makes it worth choosing these controls. Choose the HTML controls if you’re really sure that you don’t need the functionality that the server controls offer you. The remainder of this section quickly guides you through the other categories in the Toolbox. Data Controls Data controls were introduced in ASP.NET 2.0, and offer an easy way to access various data sources like databases, XML files, and objects. Instead of writing lots of code to access the data source as you had to do in earlier versions of ASP.NET, you simply point your data control to an appropriate data source, and the ASP.NET run time takes care of most of the difficult issues for you. You see a lot more about these controls in Chapter 13 and onward. c04.indd 132c04.indd 132 10/8/2012 9:51:04 AM10/8/2012 9:51:04 AM
    • Types of Controls x 133 Validation Controls Validation controls enable you to rapidly create Web Forms with validation rules that prohibit users from entering invalid data. For example, you can force users to enter values for required fields and check whether the entered data matches a specific format like a valid date or a number between 1 and 10. They even allow you to write custom code to create validation routines that are not covered by the standard controls. The beauty of the validation controls is that they can execute both on the client and the server, enabling you to create responsive and secure web applications. Chapter 9 digs much deeper into these controls. Navigation Controls The controls you find under the Navigation category of the Toolbox are used to let users find their way through your site. The TreeView control presents a hierarchical display of data and can be used to show the structure of your site, giving easy access to all the pages in the site. The Menu control does a similar thing and provides options for horizontal and vertical fold-out menus. The SiteMapPath control creates a “breadcrumb trail” in your web pages that enables your users to easily find their way up in the hierarchy of pages in your site. You see all of these controls in action in Chapter 7, which deals with navigation in websites exclusively. Login Controls Just like the data and navigation controls, the login controls were introduced in ASP.NET 2.0 and are still strongly present in ASP.NET 4.5. With very little effort, login controls enable you to create secure websites where users need to sign up and log in before they can access specific parts of the website (or even the entire website). In addition, they provide the tools for users to change their pass- word, or request a new password if they forget the old one, and enable you to display different data depending on the logged-in status and role of the user. Chapter 16 provides more details about the security features and login controls of ASP.NET. Ajax Extensions The Ajax Extensions enable you to create flicker-free web applications that are able to retrieve data from the server from client-side JavaScript without a full postback. You can find the full details on them in Chapter 10. WebParts ASP.NET WebParts are a set of controls that enables an end user of a web page to change the appearance and behavior of a website. These controls are outside the scope of this book. c04.indd 133c04.indd 133 10/8/2012 9:51:04 AM10/8/2012 9:51:04 AM
    • 134 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS Dynamic Data The controls in this category are used in Dynamic Data websites. Dynamic Data sites enable you to quickly build a user interface to manage data in a database. These controls are not discussed fur- ther in this book. To learn more about them, check out Sams’ ASP.NET Dynamic Data Unleashed, Oleg Sych and Randy Patterson, 2012 (ISBN: 978-0-672-33565-5). THE ASP.NET STATE ENGINE In the previous chapter, you created a page with a TextBox and a Button control. In the Try It Out, you ran this page in the browser, typed some text, and clicked the button. The button caused a postback to the server, and when the page reloaded, the text was still present in the text box. You pretty much did the same thing with the Wizard control in this chapter, where the values from the text box and the drop-down list were maintained as well. If you’re familiar with other web technologies like ASP or PHP, this probably surprised you. In those languages, you often need to write lots of code to make this happen. So why and how does this work automatically in ASP.NET? The text in the text box is maintained by the ASP.NET state engine, a feature that is deeply inte- grated into the ASP.NET run time. It enables controls to maintain their state across postbacks, so their values and settings remain available after every postback of the page. What Is State and Why Is It Important? To understand state, it’s important to realize that, by design, HTTP—the protocol used to request and serve pages in a web browser—is stateless. What this means is that the web server does not keep track of requests that have been made from a specific browser. As far as the web server is concerned, each request you make to the server by browsing to a page and clicking links to other pages stands on its own. The web server has no recollection of pages you requested previously. This poses some interesting problems. Consider, for example, a simple login page that enables you to log in to a website, like your favorite web mail program. You can see a sample of the login box in Figure 4-16. Now imagine that you try to log in with a correct username but with an incorrect password. The page will then inform you that your login attempt failed. Ideally, you would also want your username to be filled in for you automatically, and you’d want the Remember Me Next Time check box to retain its selection as well. That way, it’s easy for the user to enter the correct password and click the Log In button again. This is just a trivial example, but it’s easy to come up with many more scenarios where it’s useful if controls are able to maintain their own state. However, by default, a web page or a control cannot do this on its own. Because each request is a standalone request, the server won’t fill in the text boxes again after a postback, but will simply FIGURE 4-16 c04.indd 134c04.indd 134 10/8/2012 9:51:04 AM10/8/2012 9:51:04 AM
    • The ASP.NET State Engine x 135 serve the page the same way it did when it first loaded it. In other web technologies, like classic ASP or PHP, you could work around this by manually writing code that prepopulates controls after a postback. Fortunately, ASP.NET makes this much easier for you by integrating this functionality in the ASP.NET feature set. How the State Engine Works The state engine in ASP.NET is capable of storing state for many controls. It can store state not only for user input controls like a TextBox and a CheckBox, but for other controls like a Label and even a Calendar. This is best demonstrated by a demo. The following exercise shows you how to create a page with controls that are capable of maintaining their state. The sections that follow then explain how ASP.NET is able to do this. TRY IT OUT Examining the ASP.NET State Engine In this exercise you add Label, Button, TextBox, and Calendar controls to the page. These controls are used to demonstrate some of the inner workings of ASP.NET, including postbacks and the way ASP.NET maintains state. 1. Under the Demos folder, create a new page called State.aspx. Make sure it uses Code Behind, and don’t forget to choose your preferred programming language. 2. Switch the page to Design View, click inside the dashed <div> to put the focus on it, and then choose Table Í Insert Table from the main menu. Set Rows to 3 and Columns to 2 and click OK to insert a table with three rows and two columns. 3. In the first cell of the first row, drag a Label control from the Toolbox. In the first cell of the sec- ond row, drag a Calendar control. 4. Note that as soon as you drop the Calendar control in the cell, its Smart Tasks panel pops up as shown in Figure 4-17. FIGURE 4-17 c04.indd 135c04.indd 135 10/8/2012 9:51:04 AM10/8/2012 9:51:04 AM
    • 136 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS In the case of the Calendar control, you only get one option on this panel, Auto Format, which enables you to change the appearance of the calendar. Click the link, choose from one of the pre- defined color schemes, like Simple, and click OK. 5. In the first cell of the last row, drag a TextBox control. 6. Next, drag Button controls into the right column of the first two rows of the table. 7. Click the Button in the first row and press F4 to open the Properties Grid. Set the Button’s Text property to Set Date and its ID to SetDate. You’ll find the ID property all the way at the end of the list with properties, or at the beginning if you have the list with properties sorted alphabetically. 8. Repeat the previous step for the other button but call it PlainPostback and set its Text property to Plain Postback. When you’re done, the page should look like Figure 4-18 in Design View. 9. Double-click the Set Date button in Design View and add the following bolded code on the empty line between the code lines that VS inserted for you: VB.NET Protected Sub SetDate_Click(sender As Object, e As EventArgs) Handles SetDate.Click Label1.Text = DateTime.Now.ToString() End Sub C# protected void SetDate_Click(object sender, EventArgs e) { Label1.Text = DateTime.Now.ToString(); } There’s no need to write code for the Plain Postback button. 10. Open the page in the browser by pressing Ctrl+F5. Select a date on the calendar by clicking one of the days. Notice that as soon as you click the date, the page reloads, caused by a postback. You learn more about this in the How It Works section that follows this exercise. 11. Enter some text in the TextBox control and then click the Set Date button a few times. Again, the page is posted back to the server and the Label is updated with today’s date and time each time you click the button. The TextBox still shows the text you entered. Wait a few seconds, and then click the Plain Postback button. Once again, a postback occurs, and the page reloads. Now take a look at the text for the Label. It still contains the date and time that was dis- played when you last clicked the Set Date button. Click the Plain Postback button a few more times and notice that the Label doesn’t change. The TextBox should still display the text you entered. 12. Go back to VS and open the Properties Grid for the Label control in Design View. Locate the EnableViewState property and set it to False by selecting that value from the drop-down list or by double-clicking the property name or its value. Repeat this step for the TextBox control. 13. Repeat steps 10 and 11 by reopening the page in the browser and clicking the calendar and the buttons. This time, when you click the Plain Postback button, you’ll see that the Label control defaults to its initial text: Label. The TextBox, however, still displays the text you entered. c04.indd 136c04.indd 136 10/8/2012 9:51:04 AM10/8/2012 9:51:04 AM
    • The ASP.NET State Engine x 137 FIGURE 4-18 How It Works To understand how this all works, you need to look at a few important elements. First, open up the page in the browser again and view its HTML source. You can do this by right-clicking the page in the browser and choosing the View Source or View Page Source menu item. Near the top of the window, you see the following <form> element: <form method="post" action="State.aspx" id="form1"> ... </form> The HTML <form> element is used to enable a user to submit information from the browser to the server. A user can enter information using controls like text boxes, drop-down lists, check boxes, and so on. A form can be submitted in two ways: with POST (as shown in the previous <form> element) or with GET. In the former case, all data from the form is added to the body of the request and then sent to the server. In the case of the GET method, all the data is appended to the actual address of the request. The intricacies of the differences are not that important right now; what’s important to understand is what the <form> element is used for: it encapsulates form controls whose values are submitted back to the server en masse. When a control like a Button is clicked, it causes a postback to the server. During this postback, all the relevant information in the form is submitted back to the server where it can be used to rebuild the page. By default, all your ASP.NET Web Forms always use the POST method to send data to the server. Also, by default, an entire ASP.NET page always contains exactly one form. Because this is so common, a c04.indd 137c04.indd 137 10/8/2012 9:51:04 AM10/8/2012 9:51:04 AM
    • 138 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS new page (or Master Page as you learn in Chapter 6) created in VS already contains the <form> ele- ment, so you don’t have to add it yourself. Finally, it’s important to understand that an ASP.NET Web Form by default always submits back to itself. In other web environments, like classic ASP and PHP, it’s not uncommon to set the action attribute of the page to a second page that then processes the data the user has submitted. However, with an ASP.NET page, you’ll find that even if you set the action attri- bute in the code explicitly, the ASP.NET run time will revert it to the name of the current page. NOTE ASP.NET supports a feature called Cross Page Postbacks that enables you to submit from one page to another. To learn more about this concept, search the MSDN site for Cross Page Postbacks or get yourself a copy of Professional ASP.NET 4.5 from Wrox. The next thing to look at is ASP.NET’s View State functionality implemented with the hidden __VIEWSTATE field that you see in the HTML source bolded in the following snippet: <form method="post" action="State.aspx" id="form1"> ... <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="IXcrUZ51B9YmtdoSL9csn2+VrYx5oW32kAw0oRXGsf3F0/W0l6/upieH7Nht1f hyr99U0IRRKmjvYk4FdH5E9ZRucaja0xPkwCyRoNBI3KkidqR5eAVX86D qOfEl584eSB0ff3IF4o3Y+ZqD7qZp3A==" /> </div> Although at first the text appears to contain nothing more than random characters, it actually contains useful information. To protect the information stored in this field, ASP.NET has converted the page state in the preceding string. If you were able to look inside the value of the fields, you’d find a value for the Label1 control with the current date and time. When your ASP.NET page loads, the ASP.NET run time fills this hidden field with information about the page. For example, it added the value for the Text property of the Label1 control when you caused a postback by clicking the Set Date button. Similarly, it contains the selected date for the Calendar control. When the page is then submitted back by a postback, the value in this hidden __VIEWSTATE field is sent with the request. Then, when ASP.NET creates the new page on the server, the information from the __VIEWSTATE field is read and applied to the controls in the page. This way, a control like the Label is able to maintain its text even after the page has been posted back to the server. The TextBox doesn’t need View State, though. It’s able to maintain its value because the browser sub- mits it to the server with each postback. To reiterate, here’s a rundown of the process that took place in the preceding Try It Out. 1. You requested the page in the browser by opening it from within VS. 2. The browser got the page from the server by making a request for it. 3. The ASP.NET run time read the page from disk, processed it, and sent the resulting HTML to the browser. At this stage, all the controls were set to their default values that were defined in the markup of the page. For example, the Text of the Label control is set to Label. c04.indd 138c04.indd 138 10/8/2012 9:51:05 AM10/8/2012 9:51:05 AM
    • The ASP.NET State Engine x 139 4. After the page got displayed in the browser, you clicked the Set Date button. This caused a post- back to the server. 5. At the server, the page was reconstructed again, similar to the first time it loaded, described in step 3. At this stage, all the controls contain their default values. So, again, the Label1 control had its Text property set to Label. Shortly after the defaults have been set, the run time overrides these defaults for controls it finds in View State. However, because this was the first postback and the Label control’s Text property hadn’t changed yet, its value was not present in View State. So the Text property just contained the default word Label. 6. While still processing the same request, the ASP.NET run time fired the code in SetDate_Click. As you have seen, this code changed the Text property of the Label control to the current date and time. The ASP.NET run time sees this change and stores this new value in View State as well, so it stays available for subsequent postbacks. 7. Next, you entered some text and clicked the Plain Postback button. Just as with the other but- ton, this caused a postback to occur. The page was constructed again, and all defaults are set. Again, this means that the Text property of the Label1 control simply contains the word Label. However, shortly after that, during the same processing cycle, the ASP.NET run time processes the View State, restoring control values it finds in the hidden __VIEWSTATE field. In this example, it found the Text property with the current date and time, and assigned it again to the Label control. Because the Plain Postback button doesn’t change the Text of the Label anymore, the Text prop- erty doesn’t change: it contains the date and time from the previous postback. The Text property of the TextBox control is set using the value submitted to the server; that is, this control does not use View State to maintain its value. At the end, the entire page is sent to the browser, where the label correctly displays its previous value. 8. Finally, you turned off the View State for the Label and TextBox controls by setting EnableViewState to False. With this setting turned off, the ASP.NET run time doesn’t track the Label control anymore. So when you click the Plain Postback button, the ASP.NET run time doesn’t find any information for the label in View State, which eventually results in the label dis- playing its own default text: the word Label. Not All Controls Rely on View State You have to understand that not all controls rely on View State all the time. A number of controls are able to maintain some of their own state, as you saw with the TextBox control in the preced- ing exercise. These controls include, among others, the TextBox, CheckBox, RadioButton, and DropDownList controls. They are able to maintain their values because they are rendered as stan- dard HTML form controls in the browser. For example, a TextBox server control ends up like this in the browser: <input name="TextBox1" type="text" value="Initial Text" id="TextBox1" /> When a page with such a TextBox in it is posted back, the browser also sends the value of the con- trol back to the server. The ASP.NET run time can then simply look at that value to prepopulate the text box again, instead of getting the value from View State. Obviously, this is more efficient c04.indd 139c04.indd 139 10/8/2012 9:51:05 AM10/8/2012 9:51:05 AM
    • 140 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS than storing the value in View State too. If that were the case, the value would get sent to the server twice: once in the text box and once in View State. Especially with large values, this could quickly increase the page’s size, and thus its load time. For some features—such as tracking changes made at the client—these controls still need to store their values in View State as well, and do so on a need- to-have basis. In addition to View State, controls support the concept of Control State. Controls use that mecha- nism to keep track of data they absolutely need to operate correctly. You cannot disable Control State but since only limited amounts of data are stored in Control State, this is not a problem. A Note about View State and Performance Because the View State engine adds a considerable amount of information to the page, it’s often a good idea to turn it off when you don’t need it. This way, you can minimize the size of the hidden __VIEWSTATE field, which means the page becomes smaller and thus loads faster in the browser. Note that when you turn of View State you still see the hidden __VIEWSTATE field because Control State uses the same field to store its data. Turning off View State is easy, and you can do it at three different places: ‰ At the website level—You can do this in the Web.config file in the root of the site by modi- fying the <pages> element under <system.web>, setting the enableViewState attribute to false: <pages enableViewState="false"> ... </pages> ‰ At the page level—At the top of each page you find the page directive, a series of instructions that tell the ASP.NET run time how the page should behave. In the page directive you can set EnableViewState to False: <%@ Page Language="VB" AutoEventWireup="False" CodeFile="State.aspx.vb" Inherits="Demos _ State" EnableViewState="False" %> This option is useful for pages where you’re sure you don’t need View State at all. ‰ At the control level—Each ASP.NET Server Control enables you to set EnableViewState individually, giving you the option to turn it off for some controls, while leaving it on for others. Once you’ve turned off View State at a higher level (Web.config or page level), setting EnableViewState to True again at a lower level (the page or a specific control) has no effect. However, using the ViewStateMode property you can still accomplish this as follows: ‰ Do not turn off View State in the Web.config file. ‰ At the page level, set EnableViewState to True and ViewStateMode to Disabled like this: <%@ Page Language="C#" … EnableViewState="True" ViewStateMode="Disabled" %> This turns off View State for all controls in the page except for those that explicitly enable it again by setting the ViewStateMode to Enabled. c04.indd 140c04.indd 140 10/8/2012 9:51:05 AM10/8/2012 9:51:05 AM
    • Practical Tips on Working with Controls x 141 ‰ For the controls you want to give View State support, set the ViewStateMode to Enabled, like this: <asp:Label ID="Label1" runat="server" Text="Label" ViewStateMode="Enabled" /> If you want to see this at work in your demo page, modify the page directive of State.aspx as in the previous example by setting EnableViewState to True and ViewStateMode to Disabled. Then create a second Label in the page and set ViewStateMode for the first to Enabled: <asp:Label ID="Label1" runat="server" Text="Label" ViewStateMode="Enabled" /> <asp:Label ID="Label2" runat="server" Text="Label" /> In the Code Behind of the page, assign today’s date and time to the second label as well: VB.NET Label1.Text = DateTime.Now.ToString() Label2.Text = DateTime.Now.ToString() C# Label1.Text = DateTime.Now.ToString(); Label2.Text = DateTime.Now.ToString(); Finally, run steps 10 and 11 of the last Try It Out exercise. You’ll notice the first Label maintains its text, whereas the second defaults back to the text Label. PRACTICAL TIPS ON WORKING WITH CONTROLS The following list presents some practical tips on working with controls: ‰ Spend some time trying out the different controls in the Standard category. Although many of them are used and discussed throughout the book, it’s good to know how you should use them and how they operate. By experimenting with them now in a few sample pages, you have a head start when the controls reappear in later chapters. ‰ Consider turning off View State for controls that don’t need it. In many cases, you hardly notice the difference, but especially with the data-driven controls discussed in Chapter 13 and onward, disabling View State can seriously decrease the size of your web page, resulting in shorter load times and improved user experience. ‰ Before you design a complex Web Form with multiple controls to accept user input, step back from your computer and take a piece of paper and a pen to draw out the required functionality. By thinking about the (technical) design of your application before you start coding, it’s much easier to create a consistent and well-thought-out user interface. Making considerable changes later in the page if you’ve taken a wrong route will always take more time than doing it (almost) right the first time. ‰ Experiment with the View State mechanism to get a better understanding of how it works. Create a couple of pages similar to the one you created in the last exercise. Then turn off View State at the page or control level and see how the page behaves. Take note of the con- trols, such as TextBox, that are capable of maintaining their value even with View State off. c04.indd 141c04.indd 141 10/8/2012 9:51:05 AM10/8/2012 9:51:05 AM
    • 142 x CHAPTER 4 WORKING WITH ASP.NET SERVER CONTROLS SUMMARY This chapter gave you a good look at the large set of ASP.NET Server Controls. Because these con- trols are so important and used throughout every ASP.NET application, it’s really critical that you understand what controls you have available in the Toolbox, what they are used for, how they work, and how they maintain their own state. One of the biggest inventions in ASP.NET is the state engine that enables controls to maintain their state across postbacks. The state engine is a real time-saver and frees you from writing loads of tedious and boring code in every single web page to replicate this behavior. However, you should turn View State off when possible to improve performance. This chapter also introduced you to some trivial server-side code in Visual Basic and in C#. The next chapter gives you a much better understanding of programming ASP.NET pages. You see how a programming language looks, what elements it contains, and how to write code yourself to use in your ASP.NET pages. And best of all, the examples are presented in Visual Basic and C#, so you’re not stuck with a language you may not like. EXERCISES 1 . Name the mechanism that enables server controls to maintain their state. 2. How is the ASP.NET run time able to keep track of control state between postbacks? 3. Name a difference between an <asp:DropDownList> and an <asp:ListBox>. 4. What property do you need to cause a postback to the server when you change the checked state of a CheckBox in the browser? 5. Many server controls have a common set of properties that affects their looks at run time. Name three properties that change styling elements such as color, borders, and size. 6. Instead of setting individual control properties like BackColor and ForeColor, it’s better to set a single CSS-related property. What’s the name of this property and what benefit does it give you? You can find answers to these exercises in Appendix A. c04.indd 142c04.indd 142 10/8/2012 9:51:05 AM10/8/2012 9:51:05 AM
    • Summary x 143 WHAT YOU LEARNED IN THIS CHAPTER __VIEWSTATE The hidden form field that is used to transfer the state from the server to the client and back. Container controls Server controls that serve as a container by wrapping other content and controls. Events tab The part of the Properties Grid that lets you set up handlers for control events such as Click for a Button. List controls Server controls that present a list of items to the user. Controls include the DropDownList, CheckBoxList, and more. POST and GET methods Different methods to submit data from the client to the server. With POST the data is added to the body of the request, whereas with GET the data is appended to the address of the requested page. Postback The process of sending form data from a client browser back to the server. Server Controls The work horses of ASP.NET, used to build up the user interface of a web page in the browser. Smart Tasks panel The action panel that appears for some controls to help you accomplish common tasks. View State The mechanism that enables the ASP.NET controls to store state at the client. c04.indd 143c04.indd 143 10/8/2012 9:51:05 AM10/8/2012 9:51:05 AM
    • c04.indd 144c04.indd 144 10/8/2012 9:51:06 AM10/8/2012 9:51:06 AM DownloadfromWow!eBook<www.wowebook.com>
    • Programming Your ASP.NET Web Pages WHAT YOU WILL LEARN IN THIS CHAPTER: ‰ How to work with data types, variables, objects, and collections in a programming environment ‰ Different ways to make decisions in your code ‰ The options available for creating blocks of functionality that can easily be reused ‰ Different ways to write well-organized and documented code ‰ What object orientation is, and how you can use it in your applications WROX.COM CODE DOWNLOADS FOR THIS CHAPTER You can find the wrox.com code downloads for this chapter on the Download Code tab at www.wrox.com/remtitle.cgi?isbn=1118311809. The code is in the Chapter 5 download. In the previous four chapters, you created a number of Web Forms that contained mostly ASP .NET Server Controls and plain HTML. Only a few of the examples contained actual pro- gramming code, written in either C# or Visual Basic (VB.NET), and most of that code was pretty straightforward. However, not all of your pages will always be so simple, and the abil- ity to read, understand, and write code is a critical asset in your web development toolkit. This chapter teaches you the basics and beyond of programming for web applications. Just as with all the other samples in the book, this entire chapter covers both VB.NET and 5 c05.indd 145c05.indd 145 10/8/2012 9:52:13 AM10/8/2012 9:52:13 AM
    • 146 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES C#. For every concept or piece of theory introduced in this chapter, you see an example in both VB.NET and C# at the same time. Which language you prefer is entirely your decision. NOTE To get the most out of this chapter, it’s recommended that you actually try out the code. You can test most of the examples with a simple ASPX page. Drag a Label and a Button on your page and double-click the Button in Design View. Then type the sample code on the open line of the code block that VS added for you and press Ctrl+F5. After the page has finished loading, click the button and the code will be executed. Some of the examples call fictitious code and won’t run correctly. They only serve to illustrate the topic being discussed. INTRODUCTION TO PROGRAMMING To get started with programming, it’s critical to understand a common set of terms shared by pro- grammers in all types of languages and applications. The remainder of this chapter introduces you to a relatively large number of terms and concepts. Most of the terminology comes with code exam- ples so you can see how they are used in real code. It’s also important to realize this is not a complete introduction to programming. Not every detail of a programming language is covered. Instead, this chapter focuses on the key concepts that you need to understand to successfully build day-to-day websites. Once you get the hang of that you’ll find it’s easier to deepen your knowledge about programming by learning the more exotic features of your favorite programming language. NOTE If you’re interested in learning a lot more about programming in VB.NET or C#, find Beginning Visual Basic 2012 (ISBN: 978-1-1183-1181-3) or Beginning Microsoft Visual C# 2012 (ISBN: 978-1-1183-1441-8), both published by Wrox. You add the code you write in this and coming chapters either to the Code Behind of a web page, or in a separate class file placed in the special App_Code folder. When the ASP.NET run time processes the request for a page containing code, it compiles any code it finds in the page, Code Behind, or class files first. When code is compiled, it is being transformed from a human-readable programming language (like C# or VB.NET) into Microsoft Intermediate Language (MSIL), the language that the .NET Framework run time can understand and execute. The result of the compilation process of an ASP.NET website is one or more assemblies — files with a DLL extension — in a temporary folder on your system. This compilation process takes place only the first time the page is requested after it has been created or changed. Subsequent requests to the same page result in the same DLL being reused for the request. Fortunately, in ASP.NET websites, compilation takes place behind the scenes, so you usually don’t have to worry about it. To get started with programming, the first concepts that you need to look at are data types and vari- ables, because they are the building blocks of any programming language. c05.indd 146c05.indd 146 10/8/2012 9:52:19 AM10/8/2012 9:52:19 AM
    • Data Types and Variables x 147 NOTE The .NET Framework used by ASP.NET is huge and contains thousands of types with hundreds of thousands of members. Clearly, you cannot memorize all the types in the framework, so you need to make good use of resources like IntelliSense and the online help. Navigating the MSDN site (http://msdn .microsoft.com/en-us/library/) can sometimes be a daunting task. However, I often find that searching for something like typeName type .NET MSDN brings up exactly what I need. So, if I wanted to learn more about the string class, I’d type string class .NET MSDN in my favorite search engine. Nine out of ten times the first result is a link to the relevant page on the MSDN website, where I can learn more about the class — where it’s defined and located and how to use it. DATA TYPES AND VARIABLES At first when you think about data that is used in some programming environment, you may not realize that each piece of data has a data type. You may think that a computer would store the text Hello World in exactly the same way as today’s date or the number 26; as a series of characters, for example. However, to be able to effectively work with data, many programming languages have dif- ferent data types, and each data type is constrained to a specific type of information. Out of the box, the .NET Framework comes with a long list of data types that enable you to work with numbers (such as Int32, Int16, and Double), text strings (Char and String), dates (DateTime), true/false constructs (the Boolean), and more. A list of the most common types is supplied later in this section. For each major type of data there is a special data type. To work with that data, you can store it in a variable that you need to declare first using the required data type. In VB.NET you use Dim myVariable As DataType, whereas in C# you use DataType myVariable to declare a variable. A valid variable name typically consists of letters, numbers, and underscores, and cannot start with a number. These rules apply to other identifiers as well, such as classes and methods, which you see later. The following example shows you how to declare two variables: an Integer (int in C#) to hold a number and a String (string in C#) to hold a piece of text: VB.NET ' Declare a variable of type Integer to hold medium sized whole numbers. Dim distanceInMiles As Integer ' Declare a variable to hold some text like a first name. Dim firstName As String C# // Declare a variable of type int to hold medium sized whole numbers. int distanceInMiles; // Declare a variable to hold some text like a first name. string firstName; These two code examples also contain comments, prefixed with a tick (') in VB.NET or two for- ward slashes (//) in C#. You learn more about commenting your code later in this chapter. c05.indd 147c05.indd 147 10/8/2012 9:52:19 AM10/8/2012 9:52:19 AM
    • 148 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES After you have declared a variable, you can assign it a value. You can assign types like numbers and booleans directly to a variable. To assign a string to a variable you need to enclose it in double quotes: VB.NET Dim distanceInMiles As Integer distanceInMiles = 437 Dim firstName As String firstName = "Imar" C# int distanceInMiles; distanceInMiles = 437; string firstName; firstName = "Imar"; In addition to separate declarations and assignments, you can also declare a variable and assign it a value in one fell swoop: VB.NET Dim distanceInMiles As Integer = 437 Dim firstName As String = "Imar" C# int distanceInMiles = 437; string firstName = "Imar"; Although a variable name can be nearly anything you like, it’s advised that you give each variable a meaningful name that describes its purpose. For example, a string to hold a first name could be called firstName and a variable that holds someone’s age could simply be called age. In .NET it’s common to write local variables in what’s called camel case, which means each word starts with a capital letter except for the first. To help you find the type of the variable later in the code, VS shows a useful tooltip when you hover over a variable in the code editor, making it super easy to find a vari- able’s type. Figure 5-1 shows that the distanceInMiles variable in the C# example is of type int. FIGURE 5-1 You’re advised not to prefix your variables with letters to indicate the type. For example, write firstName and not sFirstName for a String holding someone’s name. This type of notation, called Hungarian Notation, is considered outdated. IDEs like Visual Studio, with their smart IntelliSense and other programming tools, don’t really require this anymore. Without Hungarian Notation, your code becomes easier to read (age is more readable than iAge) and easier to maintain because you can change a variable’s type without renaming it everywhere it’s used. c05.indd 148c05.indd 148 10/8/2012 9:52:19 AM10/8/2012 9:52:19 AM
    • Data Types and Variables x 149 Microsoft .NET supports a large number of different programming languages, including VB.NET, C#, and others. All these languages are able to communicate with each other. For example, you can write some code in C#, use Visual Studio Express 2012 for Windows Desktop to compile it to a .dll file (a file with reusable code that can be consumed by other .NET applications), and then use it in a web application that uses VB.NET as the primary language. Because of this interoperability, it’s necessary to agree on some system that enables all .NET programming languages to understand each other. This system is called the Common Type System (CTS). It’s the CTS that defines the data types that are accessible to all CTS-compliant languages. Each language is then free to define a set of primitive types, which are essentially shortcuts or aliases for the more complex type descriptions in the .NET Framework. So, even if the CTS defines a type called System.Int32, a language like C# is free to alias this type as int and VB is free to alias this type as Integer to make it easier for a developer to work with it. The following table lists the most common CTS types in the .NET Framework and their C# and VB.NET aliases. The table also lists the ranges of the variables and what they are used for. .NET C# VB.NET DESCRIPTION System.Byte byte Byte Used to store small, positive whole numbers from 0 to 255. Defaults to 0 when no value is assigned explicitly. System.Int16 short Short Capable of storing whole numbers between –32,768 and 32,767. Defaults to 0. System.Int32 int Integer Capable of storing whole numbers between –2,147,483,648 and 2,147,483,647. Defaults to 0. System.Int64 long Long Holds whole large numbers between –9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. Defaults to 0. System.Single float Single Stores large numbers with decimals between –3.4028235E+38 and 3.4028235E+38. Defaults to 0.0. System.Double double Double Can hold large fractional numbers. It’s not as accurate as the Decimal when it comes to the fractional numbers but when extreme accuracy is not a requirement, you should prefer the Double over the Decimal, because the Double is a little faster. Defaults to 0.0. System.Decimal decimal Decimal Stores extremely large fractional numbers with a high accuracy. Defaults to 0. This data type is often used to store monetary values. continues c05.indd 149c05.indd 149 10/8/2012 9:52:19 AM10/8/2012 9:52:19 AM
    • 150 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES .NET C# VB.NET DESCRIPTION System.Boolean bool Boolean Used to hold a simple boolean value: True or False in VB, and true or false in C#. Defaults to False. System.DateTime n/a Date VB.NET has an alias for the System.DateTime data type to store date and time values. C# doesn’t define an alias for this type. Defaults to 1/1/0001: 12:00 am. System.Char char Char Holds a single character. Defaults to Nothing (null in C#). System.String string String Can hold text with a length of up to 2 billion characters. Defaults to Nothing (null in C#). System.SByte sbyte SByte Used to store small numbers from –128 to 127. Defaults to 0. System.UInt16 ushort UShort Similar to a System.Int16, but this data type can only store unsigned whole numbers, between 0 and 65,535. Defaults to 0. The other data types prefixed with a U are all unsigned as well. System.UInt32 uint UInteger Capable of storing whole numbers between 0 and 4,294,967,295. Defaults to 0. System.UInt64 ulong ULong Capable of storing whole numbers between 0 and 18,446,744,073,709,551,615. Defaults to 0. System.Object object Object The parent of all data types in .NET, including the CTS types and types you define yourself. Each data type is also an object, as you learn later in the book. Defaults to Nothing (null in C#). The standard .NET types are all prefixed with System followed by a period. This System part is the namespace for this data type. You learn what namespaces are and what they are used for later in this chapter. Sometimes you need to convert data from one type to another. For example, you may have an Int32 that you need to treat as a Double. You can do this in a number of different ways. Converting and Casting Data Types The most common way to convert a type is converting it into a String. Web applications use string types in many places. For example, the Text returned from a TextBox is a String, and so is the   (continued) c05.indd 150c05.indd 150 10/8/2012 9:52:19 AM10/8/2012 9:52:19 AM
    • Data Types and Variables x 151 SelectedValue of a DropDownList. To get a string representation of an Object, you can call its ToString() method. Every object in the .NET world supports this method, although the exact behavior may differ from object to object. For now, it’s important to understand that ToString is a method — or an operation — on an object, like a String or a Double and even the parent Object itself. You learn more about methods and objects later in this chapter when object-oriented pro- gramming is discussed. Using ToString() is easy, as the following example that outputs today’s date and time on a Label control demonstrates: VB.NET Label1.Text = System.DateTime.Now.ToString() C# Label1.Text = System.DateTime.Now.ToString(); Another way to convert data types is by using the Convert class. NOTE Classes are an important concept in .NET, so they are discussed in their own section later in this chapter. For now it’s important to understand that a class is like a blueprint for objects that are used in .NET. You can create your own classes, but you will also use many of the standard classes that are part of the .NET Framework. The Convert class contains functionality to convert a number of data types into another type. The following is a simple example of converting a String containing a value that looks like a boolean into a true Boolean type: VB.NET Dim myBoolean1 As Boolean = Convert.ToBoolean("True") ' Results in True Dim myBoolean2 As Boolean = Convert.ToBoolean("False") ' Results in False C# bool myBoolean1 = Convert.ToBoolean("True"); // Results in true bool myBoolean2 = Convert.ToBoolean("False"); // Results in false Besides the ToBoolean method, Convert offers you a host of other conversion methods, including ToInt32 (for integer types), ToDateTime (for dates), and ToString. Another way to convert one type into another is by using casting. With casting you actually force one type into another, which is different from converting, in which the underlying value of a data type is transformed into a new value. Casting only works for compatible types. You can’t, for example, cast a DateTime into an Integer. You can, however, cast similar types, like a Double to an Integer or a String to an Object. The reverse of the latter example isn’t always true. Earlier I said that every data type in the .NET Framework is based on the Object data type, meaning that, for example, a String is an Object. c05.indd 151c05.indd 151 10/8/2012 9:52:19 AM10/8/2012 9:52:19 AM
    • 152 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES However, not every Object is also a String. When you try to cast one type into another and get a compilation or runtime error, keep this in mind. Later chapters in this book show you more exam- ples of how to cast compatible types into each other. To cast one type into another using VB.NET, you have a few options. First, you can use CType and DirectCast. CType is a bit more flexible in that it allows you to cast between two objects that look similar. DirectCast, on the other hand, only allows you to cast between compatible types but per- forms slightly faster. The following VB.NET example shows how this works: Dim o1 As Object = 1 Dim i1 As Integer = DirectCast(o1, Integer) ' Works, because o1 is an Integer Dim i2 As Integer = CType(o1, Integer) ' Works, because o1 is an Integer Dim o2 As Double = 1 Dim i3 As Integer = DirectCast(o2, Integer) ' Does not compile, because o2 is ' not an Integer Dim i4 As Integer = CType(o2, Integer) ' Works, because o2 looks like an ' Integer In the first part of the example, an object called o1 is declared and assigned the Integer value of 1. Although o1 exposes itself to the outside world as an Object, its underlying value is still an Integer. When DirectCast is called, the cast succeeds because o1 is, under the hood, an Integer. In the second example, o2 is declared as a Double, a numeric type that looks somewhat like an Integer, but isn’t really one. Therefore, the call to DirectCast fails because a Double cannot be cast to an Integer. CType, on the other hand, works fine, because the underlying value of the vari- able o2 looks like an Integer and can therefore be cast to one. It’s important to realize that if the Double type has a decimal part, that part gets lost when casting it to an Integer. The third option to cast in VB.NET is using the keyword TryCast, which is somewhat similar to the other two options. When an object cannot be cast correctly, TryCast returns Nothing, whereas DirectCast and CType result in a crash of the code. In C# you have two options to cast objects. The most common way is to put the data type in paren- theses in front of the expression you want to cast. This works similar to CType in VB. object o1 = 1; int i1 = (int)o1; // Works double o2 = 1; int i2 = (int)o2; // Works Alternatively, you can use the as keyword, which works similarly to TryCast in VB.NET in that the code doesn’t crash if the cast doesn’t succeed. The following sample code shows that you cannot cast an Integer to an ArrayList (which you meet later in this chapter). Instead of crashing, the variable myList simply contains null to indicate that the cast operation didn’t succeed. object o1 = 1; ArrayList myList = o1 as ArrayList; // Doesn't cast, but doesn't crash either. You see more about casting and converting in the remaining chapters in this book. c05.indd 152c05.indd 152 10/8/2012 9:52:20 AM10/8/2012 9:52:20 AM
    • Data Types and Variables x 153 Using Arrays and Collections So far the data types you have seen are relatively straightforward and singular objects. For exam- ple, you store a value of True or False in a Boolean type, and you store a number like 123 in an Integer. But what if you have the need to store lots of integers? You may have the need to do so if you want to store the points of a complex shape like a polygon. Or you may have the need to store all the roles that your application supports in a single variable so you can show them on a web page in the Management section, for example. Here’s where arrays and collections come to the rescue. Defining and Working with Arrays You can see an array as a big bag or list of the same type of things. You define the data type of the things in the array when you declare it. Each item in the array is identified by a sequential number (its so-called index) starting at 0, making arrays zero-based. When declaring and accessing an array in VB.NET you use parentheses, whereas in C# you use square brackets. After you have defined the array and populated its elements, you can access the elements by their zero-based element index (0, 1, 2, and so on). The following code snippet defines an array called roles that can hold up to two roles at the same time: VB.NET Dim roles(1) As String C# string[] roles = new string[2]; See the difference between the VB.NET and C# examples? That’s not a typo. In VB.NET you define an array’s size by specifying the upper bound. The upper bound is the last element in the array that you can access. Because arrays are zero-based (that is, you address the first item in the array with an index of 0), it means that if you need room for two items, the upper bound is 1, giving you the items 0 and 1. In C#, on the other hand, you don’t define the upper bound but instead you define the size. So in C#, you simply specify 2 to get an array with two elements. Additionally, C# requires you to use the keyword new, which instantiates a new array for you. VB.NET does that for you automatically and raises an error if you add the New keyword as in the C# example. You see the new (New in VB.NET) keyword again later in this chapter. To enter the role names into the array you use the following syntax: VB.NET roles(0) = "Administrators" roles(1) = "ContentManagers" C# roles[0] = "Administrators"; roles[1] = "ContentManagers"; c05.indd 153c05.indd 153 10/8/2012 9:52:20 AM10/8/2012 9:52:20 AM
    • 154 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES Just as with the array’s declaration, you use parentheses in VB.NET and square brackets in C# to address the elements in the array. Note that (0) and [0] refer to the first element in the array and (0) and [1] refer to the second. By design, arrays have a fixed size. So, given the previous example that defines an array with room for two elements, the following code will throw an error: VB.NET roles(2) = "Members" ' Throws an error C# roles[2] = "Members"; // Throws an error This code tries to squeeze a third role into an array that has room for only two. Obviously, that doesn’t fit and you’ll get an error stating that the “Index was outside the bounds of the array.” But what if you need to create more room in the array at a later stage in your code at run time? In VB.NET this is pretty easy. You can use the ReDim statement: ReDim Preserve roles(2) roles(2) = "Members" ' Works fine now This line of code re-dimensions the array to its new size: an upper bound of two, thus creating room for a third element. The Preserve keyword is necessary to leave the current items in the array intact. Without it, the resized array will be empty. C# has no direct keyword to re-dimension an array. However, you can leverage the Array class of the .NET Framework to resize the array as follows: Array.Resize(ref roles, 3); // Resize the array so it can // hold three elements roles[2] = "Members"; // Works fine now Don’t worry about this odd-looking syntax right now; you probably won’t need it very often, because the .NET Framework offers alternatives to fixed-size arrays. Since Array .Resize is available to VB.NET as well, you have two options to choose from if you’re using that language. When you start working with arrays, you find that they are quick to use at run time, but lack some useful functionality. For example, it’s not so easy to add new elements or to remove existing items from the array. Fortunately, the .NET Framework offers a range of useful collections that do give you the feature set you need. Defining and Working with Collections Collections are similar to arrays in that they enable you to store more than one object in a single variable. The same bag analogy works for collections: You can simply drop a number of items in a bag, and it will hold them for you. What’s different with collections is how they enable you to work with the data in the bag. Instead of simply accessing each item by its index, most collections expose an Add method that enables you to add an item to the collection. Similarly, they have Remove and c05.indd 154c05.indd 154 10/8/2012 9:52:20 AM10/8/2012 9:52:20 AM
    • Data Types and Variables x 155 Clear methods to remove one or all items from the collection. Just like arrays, they enable you to iterate, or loop, over them to access the items in the collection. When collections were first introduced in the .NET Framework 1.0, the ArrayList and Hashtable became popular very quickly because they were so easy to use. The ArrayList enables you to add arbitrary objects that are then stored in the order in which you add them, whereas the Hashtable enables you to store objects referenced by a custom key. The main benefit of these collections over their array cousins is that they can grow on demand. Unlike the previous example, where you needed to resize the array to create room for the third role, the ArrayList grows dynamically when required. The following example shows you how this works: VB.NET Dim roles As New ArrayList() ' Create a new ArrayList. You don't need ' to set its size explicitly roles.Add("Administrators") ' Add the first role roles.Add("ContentManagers") ' Add the second role roles.Add("Members") ' Keep adding roles and the ArrayList ' grows as necessary C# ArrayList roles = new ArrayList(); // Create a new ArrayList. You don't need // to set its size explicitly roles.Add("Administrators"); // Add the first role roles.Add("ContentManagers"); // Add the second role roles.Add("Members"); // Keep adding roles and the ArrayList // grows as necessary Because this code now calls a method (Add) rather than assigning an item to a predefined index in an array, you need parentheses (()) in both VB.NET and C#. The usage of methods is discussed later in this chapter. Although collections solve some of the problems that arrays have, they introduce a few problems of their own. The biggest drawback of the ArrayList is that it isn’t strongly typed. What this means is that you can add any object to the list using the Add method. This means that the ArrayList could hold objects that are of different types at the same time. This may not seem to be a big deal at first, but as soon as you start working with an ArrayList that contains multiple types of objects, you’ll quickly see why this is problematic. Take the roles example again. With the array and the ArrayList versions, the code simply added a few strings containing role names. You can then use these three strings to, say, build up a drop-down list in a Web Form to enable a user to pick a role. So far, so good. But what if one of the items in the list is not a string? What if another developer accidentally wrote some code that adds a DropDownList control to the ArrayList? Because the ArrayList accepts all objects, it won’t complain. However, your code will crash if it expects a String, but gets a DropDownList control instead. With .NET 2.0, Microsoft introduced a concept called generics. Generics are still strongly present in version 4.5 of .NET, helping you overcome the problems that weakly typed collections like the ArrayList introduced. c05.indd 155c05.indd 155 10/8/2012 9:52:20 AM10/8/2012 9:52:20 AM
    • 156 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES An Introduction to Generics Since their introduction with .NET 2.0, generics pop up in many different locations in the .NET Framework. Although they are used often in situations where collections are used, the use of gener- ics is not limited to collections; you can also use them for singular types of objects. Generics are to code what Microsoft Word templates are to word processing. They enable you to write a code template that can be used in different scenarios with different types. With generics, you can define a generic code template that doesn’t explicitly specify a type. Only when that code is used do you define the type. The main benefit of this is that you can reuse the same template over and over again for multiple data types, without retyping and maintaining multiple versions of the code. In addition to using generics in your own code definitions, you find a host of generics-enabled objects and collections in the .NET Framework, ready to be used by your code. To understand how you can take advantage of generics, take a look at the following example. It’s essentially the same code you saw earlier where the ArrayList was used, but this time the type of the list is constrained so it accepts only strings: VB.NET Dim roles As New List(Of String) roles.Add("Administrators") roles.Add("ContentManagers") roles.Add("Members") C# List<string> roles = new List<string>(); roles.Add("Administrators"); roles.Add("ContentManagers"); roles.Add("Members"); Not much code has changed to make the roles list type safe. However, with the definition of List (Of String) in VB.NET and List<string> in C# the new list is now set up to allow only strings to be added through its Add method. This compiles fine: roles.Add("Administrators"); The following will not compile because 33 is not a String: roles.Add(33); Similar to a generics list of strings, you can also create lists to hold other types. For example: VB.NET Dim intList As New List(Of Integer) ' Can hold Integers only Dim boolList As New List(Of Boolean) ' Can hold Booleans only Dim buttonList As New List (Of Button) ' Can hold Button controls only C# List<int> intList = new List<int>(); // Can hold ints only List<bool> boolList = new List<bool>(); // Can hold bools only List<Button> buttonList = new List<Button>(); // Can hold Button controls only c05.indd 156c05.indd 156 10/8/2012 9:52:20 AM10/8/2012 9:52:20 AM
    • Statements x 157 NOTE Because there’s a lot more to generics than what is shown here, they deserve an entire book of their own. Wrox has released such a book: Professional .NET 2.0 Generics by Tod Golding (ISBN: 978-0-7645-5988-4). Although it was originally written for .NET 2.0, you’ll find that all the concepts and examples introduced in that book still apply. Though the Add method is useful to add items to a collection, it can sometimes be a bit tedious if you need to add multiple items to a collection at once. To make this easier, .NET supports collec- tion initializers. With a collection initializer, you declare the collection and add some items in one step. You do this by adding the items in a pair of curly braces (prefixed with the keyword From in VB.NET) as shown in the following example: VB.NET Dim myList As New List(Of Integer) From {1, 2, 3, 4, 5} C# List<int> myList = new List<int>() { 1, 2, 3, 4, 5 }; Right after this line, the list is populated with the five integers. Collection initializers are not limited to the List class or integers. You can use them with other col- lection types and data types as well. The generics examples you have seen barely scratch the surface of what is possible with generics. However, when building ASP.NET websites, you often don’t need all the advanced stuff that gener- ics offer you. The List collection is so useful it had to be discussed here. Without a doubt, you’ll use that collection in your own code one way or another. STATEMENTS To make a program or a website do something useful, you need to provide it with code statements that it can execute. Statements cover a wide range of actions, such as show this button, send this e-mail, execute this and that code when a user clicks that button, and so on. However, simply executing these actions is not enough. You often need to execute some code only when a certain condition is true. For example, if a visitor to an e-commerce website is buying more than $100 worth of merchandise at one time, she might get a discount of 10 percent. Otherwise, she’ll pay the full price. Conditions or decisions are therefore very important statements in a programming lan- guage. Another important set of statements is the loops. Loops enable you to repeat a certain piece of code a number of times. For example, you can have a loop that goes from 1 to 10, performing some action on each iteration. Or you can loop through the products in a shopping cart, summing up their total price, for example. The final important set of statements is the operators. Operators enable you to do something with your values; or, to be more exact, they enable you to operate on them. For example, you use opera- tors to add or subtract values, concatenate (combine) them, or compare them to each other. The following three sections dig deeper into operators, decision making, and loops. c05.indd 157c05.indd 157 10/8/2012 9:52:20 AM10/8/2012 9:52:20 AM
    • 158 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES Operators The most important operators can be grouped logically into five different types; these types are cov- ered in this section. Of these five types, the assignment operators are probably the easiest to under- stand and use. Assignment Operators The assignment operators are used to assign a value to a variable. This value can come from many sources: a constant value, like the number 6, the value of another variable, or the result of an expression or a function, which are discussed later. In its simplest form, an assignment looks like this, where the number 40 is assigned to the age variable: VB.NET Dim age As Integer = 40 C# int age = 40; What if the person this age variable is referring to just had his birthday? You’d need to add 1 to the age value. That’s where arithmetic operators come into play. Arithmetic Operators Arithmetic operators enable you to perform most of the familiar calculations on variables and val- ues, like adding, subtracting, and dividing. The following table lists the common arithmetic opera- tors for both VB.NET and C#. VB.NET C# USAGE + + Adds two values to each other − − Subtracts one value from another * * Multiplies two values / / Divides two values n/a Divides two values but always returns a rounded integer ^ n/a Raises one value to the power of another Mod % Divides two whole numbers and returns the remainder The first four operators probably look familiar, and their usage is pretty straightforward. The fol- lowing code snippet shows the basic operations you can perform with these operators: VB.NET Dim firstNumber As Integer = 100 Dim secondNumber As Single = 23.5 Dim result As Double = 0 c05.indd 158c05.indd 158 10/8/2012 9:52:20 AM10/8/2012 9:52:20 AM
    • Statements x 159 result = firstNumber + secondNumber ' Results in 123.5 result = firstNumber - secondNumber ' Results in 76.5 result = firstNumber * secondNumber ' Results in 2350 result = firstNumber / secondNumber ' Results in 4.25531914893617 C# int firstNumber = 100; float secondNumber = 23.5F; double result = 0; result = firstNumber + secondNumber; // Results in 123.5 result = firstNumber - secondNumber; // Results in 76.5 result = firstNumber * secondNumber; // Results in 2350 result = firstNumber / secondNumber; // Results in 4.25531914893617 Note that in the C# example you need to add the letter F to the value of 23.5. This tells the compiler you really want it to be a float rather than a double. VB.NET also supports the operator, which basically performs the division and then drops the remainder from the value, effectively rounding the return value down to the nearest integer. VB.NET result = firstNumber secondNumber ' Results in 4 C# doesn’t have a special operator for this. However, when you try to divide two integers, the result is always an integer as well. This means that 7 (stored as an int) divided by 2 (stored as an int) will be 3. It’s important to realize that this rounding occurs, or you may end up with unexpected results. The final two operators need a bit more explanation. First, the ^ operator — for raising one number to the power of another — is available only in the VB.NET language: VB.NET Dim result As Double result = 2 ^ 3 ' Results in 8 (2 * 2 * 2) result = 3 ^ 2 ' Results in 9 (3 * 3) C# doesn’t support this operator, but you can easily replicate its behavior using Math.Pow, which is made available by the .NET Framework. The following code snippet is functionally equivalent to the preceding one: C# result = Math.Pow(2, 3); // Results in 8 (2 * 2 * 2) result = Math.Pow(3, 2); // Results in 9 (3 * 3) Of course Math.Pow is available to VB.NET as well, so if you’re using that language, you have two options to choose from. The final operator is called the modulus operator. It returns the remainder of the division of two numbers, like this: VB.NET Dim firstNumber As Integer = 17 Dim secondNumber As Integer = 3 c05.indd 159c05.indd 159 10/8/2012 9:52:21 AM10/8/2012 9:52:21 AM
    • 160 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES Dim result As Integer = firstNumber Mod secondNumber ' Results in 2 C# int firstNumber = 17; int secondNumber = 3; int result = firstNumber % secondNumber; // Results in 2 Simply put, the modulus operator tries to subtract the second number from the first as many times as possible and then returns the remainder. In the preceding example this will succeed five times, subtracting a total of 15, leaving a remainder of 2, which is then returned and stored in the result. The modulus operator is often used to determine if a number is odd or even. When working with operators, it’s important to keep their precedence in mind. To see why this is important, consider the following calculation: 2 + 10 * 4 What is the outcome of this? You may think the answer is 48 if you first add 2 and 10 together, and then multiply the result by 4. However, the right answer is 42; first the multiplication operator is applied on 10 and 4, resulting in 40. Then 2 is added, which leads to 42 as the final result. The fol- lowing table shows the operator precedence for both VB.NET and C#. VB.NET C# ^ Exponentiation *, /, % Multiplication, division, and modulus *, / Multiplication and division +, − Addition and subtraction Integer division Mod Modulus arithmetic +, − Addition and subtraction and string concatenation using the plus (+) symbol & String concatenation To force a different operator order, you can use parentheses around expressions. The contents of the expressions are evaluated first, resulting in a different order. For example: (2 + 10) * 4 This does result in 48 now, because the addition operator is applied before the multiplication operator. Both languages also enable you to combine the arithmetic and assignment operators, enabling you to take the value of a variable, perform some arithmetic operation on it, and assign the result back to the variable. The following examples show how this works: VB.NET Dim someNumber1 As Integer = 3 Dim someNumber2 As Integer = 3 Dim someNumber3 As Integer = 3 c05.indd 160c05.indd 160 10/8/2012 9:52:21 AM10/8/2012 9:52:21 AM DownloadfromWow!eBook<www.wowebook.com>
    • Statements x 161 Dim someNumber4 As Integer = 3 someNumber1 += 3 ' Results in someNumber1 having the value 6 someNumber2 -= 3 ' Results in someNumber2 having the value 0 someNumber3 *= 3 ' Results in someNumber3 having the value 9 someNumber4 /= 3 ' Results in someNumber4 having the value 1 C# int someNumber1 = 3; int someNumber2 = 3; int someNumber3 = 3; int someNumber4 = 3; someNumber1 += 3; // Results in someNumber1 having the value 6 someNumber2 -= 3; // Results in someNumber2 having the value 0 someNumber3 *= 3; // Results in someNumber3 having the value 9 someNumber4 /= 3; // Results in someNumber4 having the value 1 C# also enables you to increase a variable’s value by 1 using the ++ operator, like this: C# int someNumber = 3; someNumber++; // Results in someNumber having the value 4 This construct is used often in loops, as you’ll see later in the chapter. Both languages also use arithmetic assignment operators to concatenate string values, as you’ll see shortly. Another common set of operators is the comparison operators, which enable you to compare values. Comparison Operators Just as with the arithmetic operators, VB.NET and C# each have their own set of comparison operators to compare one value to another. A comparison operator always compares two values or expressions and then returns a boolean value as the result. The following table lists the most com- mon comparison operators. VB.NET C# Usage = == Checks if two values are equal to each other <> != Checks if two values are not equal < < Checks if the first value is less than the second > > Checks if the first value is greater than the second <= <= Checks if the first value is less than or equal to the second >= >= Checks if the first value is greater than or equal to the second Is is In VB.NET: Compares two objects. In C#: Checks if a variable is of a certain type c05.indd 161c05.indd 161 10/8/2012 9:52:21 AM10/8/2012 9:52:21 AM
    • 162 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES The first thing you’ll notice is that C# uses a double equals symbol (==) for the standard comparison operator. This clearly makes it different from the assignment operator. It’s a common mistake in C# to use only a single equals symbol if you intend to compare two values. Consider the following example: if (result = 4) { // Do something here with result } The intention here is to see if result equals 4. However, because the assignment operator is used instead of a proper comparison operator, you’ll get the compile error that is displayed in Figure 5-2. FIGURE 5-2 At first the error message may look a little strange. But if you look at the code a little closer, it starts to make more sense. First, result gets assigned a value of 4. This value is then used for the if state- ment. However, the if statement needs a boolean value to determine whether it should run the code inside the if block. Because you can’t convert an integer value to a boolean like this, you get a com- pile error. The fix is easy, though; just use the proper comparison operator instead: if (result == 4) { // Do something here with result } Similar to the simple comparison operator, you can use the other operators to compare values: VB.NET 4 > 5 ' 4 is not greater than 5; evaluates to False 4 <> 5 ' 4 is not equal to 5; evaluates to True 5 >= 4 ' 5 is greater than or equal to 4; evaluates to True C# 4 > 5 // 4 is not greater than 5; evaluates to false 4 != 5 // 4 is not equal to 5; evaluates to true 5 >= 4 // 5 is greater than or equal to 4; evaluates to true The Is keyword in VB.NET and is in C# do something completely different. In VB.NET, Is com- pares two instances of objects, something you learn more about in the second half of this chapter. In C#, you use is to find out if a certain variable is compatible with a certain type. You can accomplish that in VB.NET using the TypeOf operator. The following two examples are functionally equivalent: VB.NET Dim myTextBox As TextBox = New TextBox() If TypeOf myTextBox Is TextBox Then c05.indd 162c05.indd 162 10/8/2012 9:52:21 AM10/8/2012 9:52:21 AM
    • Statements x 163 ' Run some code when myTextBox is a TextBox End If C# TextBox myTextBox = new TextBox(); if (myTextBox is TextBox) { // Run some code when myTextBox is a TextBox } One of the arithmetic operators enables you to add two values to each other. That is, you use the plus (+) symbol to add two values together. But what if you want to combine two values, rather than add them up? That’s where the concatenation operators are used. Concatenation Operators To concatenate two strings, you use the + in C# and the & character in VB.NET. Additionally, you can use += and &= to combine the concatenation and assignment operators. Consider this example: VB.NET Dim firstString As String = "Hello " Dim secondString As String = "World" Dim result As String ' The following three blocks are all functionally equivalent ' and result in the value "Hello World" result = firstString & secondString result = firstString result = result & secondString result = firstString result &= secondString C# string firstString = "Hello "; string secondString = "World"; string result; // The following three blocks are all functionally equivalent // and result in the value "Hello World" result = firstString + secondString; result = firstString; result = result + secondString; result = firstString; result += secondString; c05.indd 163c05.indd 163 10/8/2012 9:52:21 AM10/8/2012 9:52:21 AM
    • 164 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES In addition to the & and &= concatenation operators in VB.NET, you could use + and += as well. However, depending on the data types of the expressions you’re trying to concatenate, you may not get the result you’d expect. Take a look at this code snippet: Dim firstNumber As String = "4" Dim secondNumber As Integer = 5 Dim result As String = firstNumber + secondNumber Because firstNumber is a String, you may expect the final result to be 45, a concatenation of 4 and 5. However, by default, the VB.NET compiler will silently convert the string "4" into the number 4, after which addition and not concatenation takes place, giving result a value of "9", the string representation of the addition. To avoid this ambiguity, always use the & and &= operators to concatenate values. Additionally, you can tell VB.NET to stop converting these values for you automatically by adding the following line to the top of your code files: Option Strict On This forces the compiler to generate errors when an implicit conversion is about to occur, as in the previous example. The final group of operators worth looking into is the logical operators, which are discussed in the next section. Logical Operators The logical operators are used to combine the results of multiple individual expressions, and to make sure that multiple conditions are true or false, for example. The following table lists the most common logical operators. VB.NET C# Usage And & Returns True when both expressions result in a True value. Or | Returns True if at least one expression results in a True value. Not ! Reverses the outcome of an expression. AndAlso && Enables you to short-circuit your logical And condition checks. OrElse || Enables you to short-circuit your logical Or condition checks. The And, Or, and Not operators (&, |, and ! in C#) are pretty straightforward in their usage, as dem- onstrated in the following code snippets: VB.NET Dim num1 As Integer = 3 Dim num2 As Integer = 7 c05.indd 164c05.indd 164 10/8/2012 9:52:21 AM10/8/2012 9:52:21 AM
    • Statements x 165 If num1 = 3 And num2 = 7 Then ' Evaluates to True because both ' expressions are True If num1 = 2 And num2 = 7 Then ' Evaluates to False because num1 is not 2 If num1 = 3 Or num2 = 11 Then ' Evaluates to True because num1 is 3 If Not num1 = 5 Then ' Evaluates to True because num1 is not 5 C# int num1 = 3; int num2 = 7; if (num1 == 3 & num2 == 7) // Evaluates to true because both // expressions are true if (num1 == 2 & num2 == 7) // Evaluates to false because num1 is not 2 if (num1 == 3 | num2 == 11) // Evaluates to true because num1 is 3 if (!(num1 == 5)) // Evaluates to true because num1 is not 5 The AndAlso and OrElse operators in VB.NET and the && and || operators in C# work very simi- lar to their And and Or counterparts (& and |) in C#. The difference is that with these operators the second expression is never evaluated when the first one already determines the outcome of the entire expression. So with a simple And operator: If num1 = 2 And num2 = 7 Then both expressions are checked. This means that both num1 and num2 are asked for their values to see if they equal 2 and 7, respectively. However, because num1 does not equal 2, there really isn’t a point in asking num2 for its value anymore because the result of that expression will never change the final outcome of the combined expressions. This is where the AndAlso (&& in C#) operator enables you to short-circuit your logic: VB.NET If num1 = 2 AndAlso num2 = 7 Then C# if (num1 == 2 && num2 == 7) With this code, the expression num2 = 7 (num2 == 7 in C#) is never evaluated because num1 already didn’t meet the required criteria. This may not seem like a big deal with these simple expressions, but it can be a real performance booster if one of the expressions is actually a slow and long-running operation. Consider this ficti- tious code: VB.NET If userName = "Administrator" And GetNumberOfRecordsFromDatabase() > 0 Then C# if (userName == "Administrator" & GetNumberOfRecordsFromDatabase() > 0) c05.indd 165c05.indd 165 10/8/2012 9:52:22 AM10/8/2012 9:52:22 AM
    • 166 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES The code for this If block executes only when the current user is called Administrator and the fictitious call to the database returns at least one record. Now, imagine that GetNumberOfRecordsFromDatabase() is a long-running operation. It would be a waste of time to execute it if the current user weren’t Administrator. AndAlso (&& in C#) can fix this problem: VB.NET If userName = "Administrator" AndAlso GetNumberOfRecordsFromDatabase() > 0 Then C# if (userName == "Administrator" && GetNumberOfRecordsFromDatabase() > 0) Now, GetNumberOfRecordsFromDatabase() will only be executed when the current user is Administrator. The code will be ignored for all other users, resulting in increased performance for them. Most of the previous examples used an If statement to demonstrate the logical operators. The If statement itself is a very important language construct as well. The If statement and other ways to make decisions in your code are discussed next. Making Decisions Making decisions in an application is one of the most common things you do as a developer. For example, you need to hide a button on a Web Form when a user is not an administrator. Or you need to display the even rows in a table with a light gray background and the odd rows with a white background. You can make all these decisions with a few different logic constructs, explained in the following sections. If, If Else, and ElseIf Constructs The If statement (if in C#) is the simplest of all decision-making statements. The If statement con- tains two relevant parts: the condition being tested and the code that is executed when the condition evaluates to True (true in C#.) For example, to make a button visible only to administrators you can use code like this: VB.NET If User.IsInRole("Administrators") = True Then DeleteButton.Visible = True End If C# if (User.IsInRole("Administrators") == true) { DeleteButton.Visible = true; } Note that VB.NET uses the If and End If keywords, whereas C# uses if together with a pair of curly braces to indicate the code block that is being executed. Also, with C#, the parentheses around the condition being tested are required, whereas VB.NET requires you to use the keyword Then after the condition. c05.indd 166c05.indd 166 10/8/2012 9:52:22 AM10/8/2012 9:52:22 AM
    • Statements x 167 This code explicitly checks for the value True / true. However, this is not required and it’s quite common to leave it out. The following example is equivalent: If User.IsInRole("Administrators") Then DeleteButton.Visible = True End If C# if (User.IsInRole("Administrators")) { DeleteButton.Visible = true; } I’ll use this succinct version in the remainder of the examples in this chapter. Often you want to per- form a different action if the condition is not True. Using the negation operator Not or ! you could simply write another statement: VB.NET If User.IsInRole("Administrators") Then DeleteButton.Visible = True End If If Not User.IsInRole("Administrators") Then DeleteButton.Visible = False End If C# if (User.IsInRole("Administrators")) { DeleteButton.Visible = true; } if (!User.IsInRole("Administrators")) { DeleteButton.Visible = false; } Clearly, this leads to messy code, because you need to repeat each expression evaluation twice: once for the True case and once for the False case. Fortunately, there is an easier solution: the Else block (else in C#): VB.NET If User.IsInRole("Administrators") Then DeleteButton.Visible = True Else DeleteButton.Visible = False End If C# if (User.IsInRole("Administrators")) { DeleteButton.Visible = true; } else c05.indd 167c05.indd 167 10/8/2012 9:52:22 AM10/8/2012 9:52:22 AM
    • 168 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES { DeleteButton.Visible = false; } For simple conditions this works fine. But consider a scenario in which you have more than two options. In those scenarios you can use ElseIf in VB.NET or the else if ladder in C#. Imagine that your site uses three different roles: administrators, content managers, and standard members. Administrators can create and delete content; content managers can only create new con- tent, whereas members can’t do either of the two. To show or hide the relevant buttons, you can use the following code: VB.NET If User.IsInRole("Administrators") Then CreateNewArticleButton.Visible = True DeleteArticleButton.Visible = True ElseIf User.IsInRole("ContentManagers") Then CreateNewArticleButton.Visible = True DeleteArticleButton.Visible = False ElseIf User.IsInRole("Members") Then CreateNewArticleButton.Visible = False DeleteArticleButton.Visible = False End If C# if (User.IsInRole("Administrators")) { CreateNewArticleButton.Visible = true; DeleteArticleButton.Visible = true; } else if (User.IsInRole("ContentManagers")) { CreateNewArticleButton.Visible = true; DeleteArticleButton.Visible = false; } else if (User.IsInRole("Members")) { CreateNewArticleButton.Visible = false; DeleteArticleButton.Visible = false; } Although this makes your code a bit more readable, you can still end up with difficult code when you have many expressions to test. If that’s the case, you can use the Select Case (VB.NET) or switch (C#) statement. Select Case/switch Constructs Imagine you’re building a website for a concert hall that has shows on Saturday. During the week, visitors can buy tickets online for Saturday’s gig. To encourage visitors to buy tickets as early as possible, you decide to give them an early-bird discount. The earlier in the week they buy their tick- ets, the cheaper they are. Your code to calculate the discount percentage can look like this, using a Select Case/switch statement: c05.indd 168c05.indd 168 10/8/2012 9:52:22 AM10/8/2012 9:52:22 AM
    • Statements x 169 VB.NET Dim today As DateTime = DateTime.Now Dim discountPercentage As Double = 0 Select Case today.DayOfWeek Case DayOfWeek.Monday discountPercentage = 40 Case DayOfWeek.Tuesday discountPercentage = 30 Case DayOfWeek.Wednesday discountPercentage = 20 Case DayOfWeek.Thursday discountPercentage = 10 Case Else discountPercentage = 0 End Select C# DateTime today = DateTime.Now; double discountPercentage = 0; switch (today.DayOfWeek) { case DayOfWeek.Monday: discountPercentage = 40; break; case DayOfWeek.Tuesday: discountPercentage = 30; break; case DayOfWeek.Wednesday: discountPercentage = 20; break; case DayOfWeek.Thursday: discountPercentage = 10; break; default: discountPercentage = 0; break; } For each day where the discount is applicable (Monday through Thursday) there is a Case block. The differences between VB.NET and C# syntax are quite small: C# uses a lowercase c for case and requires a colon after each case label. Additionally, you need to exit each block with a break statement. At run time, the condition (today.DayOfWeek) is evaluated and the correct block is exe- cuted. It’s important to understand that only the relevant block is executed, and nothing else. When no valid block is found (the code is executed on a day between Friday and Sunday), the code in the Case Else or default block fires. You’re not required to write a Case Else or default block, although it’s recommended to do so because it makes your code more explicit and easier to read. The preceding examples could have left it out, because discountPercentage already gets a default value of 0 at the top of the code block. To get a feel for the statements you have seen so far, the following Try It Out exercise shows you how to use them in a small demo application. c05.indd 169c05.indd 169 10/8/2012 9:52:22 AM10/8/2012 9:52:22 AM
    • 170 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES TRY IT OUT Creating a Simple Web-Based Calculator In this exercise you create a simple calculator that is able to add, subtract, multiply, and divide values. You see how to use some of the logical and assignment operators and learn to use the If and Select Case/switch constructs. 1. Start by creating a new Web Form called CalculatorDemo.aspx in the Demos folder. Make sure you don’t name the page Calculator or you’ll run into trouble later in this chapter when you create a class by that name. Once again, make sure you’re using the Code Behind model and select the correct programming language. 2. Switch the page to Design View, and click in the dashed rectangle to put the focus on it. Choose Table Í Insert Table from the main menu and add a table with three rows and three columns. 3. Merge all three cells of the first row by selecting them with the mouse (either by dragging the mouse or by clicking each cell while holding down the Ctrl key), right-clicking the selection, and choosing Modify Í Merge Cells from the menu that appears. 4. Add the following controls to the page, set their ID and other properties as in the following table, and arrange the controls as shown in Figure 5-3. CONTROL TYPE CONTROL ID PROPERTY SETTINGS Label ResultLabel Clear its Text property. To do this, right-click the property name in the Properties Grid and choose Reset. TextBox ValueBox1 DropDownList OperatorList Add four list items for the following arithmetic operators using the DropDownList’s Smart Tasks panel. + - * / TextBox ValueBox2 Button CalculateButton Set the Text property of the button to Calculate. When you’re done, your page should look like Figure 5-3 in Design View. FIGURE 5-3 c05.indd 170c05.indd 170 10/8/2012 9:52:22 AM10/8/2012 9:52:22 AM
    • Statements x 171 5. Double-click the Calculate button and add the following bolded code in the code placeholder that VS added for you: VB.NET Protected Sub CalculateButton_Click(sender As Object, e As EventArgs) Handles CalculateButton.Click If ValueBox1.Text.Length > 0 AndAlso ValueBox2.Text.Length > 0 Then Dim result As Double = 0 Dim value1 As Double = Convert.ToDouble(ValueBox1.Text) Dim value2 As Double = Convert.ToDouble(ValueBox2.Text) Select Case OperatorList.SelectedValue Case "+" result = value1 + value2 Case "-" result = value1 - value2 Case "*" result = value1 * value2 Case "/" result = value1 / value2 End Select ResultLabel.Text = result.ToString() Else ResultLabel.Text = String.Empty End If End Sub C# protected void CalculateButton_Click(object sender, EventArgs e) { if (ValueBox1.Text.Length > 0 && ValueBox2.Text.Length > 0) { double result = 0; double value1 = Convert.ToDouble(ValueBox1.Text); double value2 = Convert.ToDouble(ValueBox2.Text); switch (OperatorList.SelectedValue) { case "+": result = value1 + value2; break; case "-": result = value1 - value2; break; case "*": result = value1 * value2; break; case "/": result = value1 / value2; break; } ResultLabel.Text = result.ToString(); } c05.indd 171c05.indd 171 10/8/2012 9:52:22 AM10/8/2012 9:52:22 AM
    • 172 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES else { ResultLabel.Text = string.Empty; } } 6. Save all changes and press Ctrl+F5 to open the page in the browser. If you get an error instead of seeing the page, make sure you typed the code exactly as shown here, and that you named all con- trols according to the table you saw earlier. 7. Enter a number in the first and second text boxes, choose an operator from the drop-down list, and click the Calculate button. The code in the Code Behind fires and then — based on the item you selected in the drop-down list — the correct calculation is performed and the label is updated with the result. 8. Go ahead and try some other numbers and operators; you’ll see that the calculator carries out the right operation every time you click the Calculate button. How It Works When you enter two values and click the Calculate button, the following code in the Code Behind fires: VB.NET If ValueBox1.Text.Length > 0 AndAlso ValueBox2.Text.Length > 0 Then C# if (ValueBox1.Text.Length > 0 && ValueBox2.Text.Length > 0) This code is necessary to ensure that both text boxes contain a value. The code uses a simple If statement to ensure that both fields have a value. It also uses AndAlso or && to avoid checking the Text property of the second TextBox when the first is empty. In Chapter 9 you see a much cleaner way to perform this validation. In that chapter you’ll also see how to make sure users enter valid numbers, as currently the code crashes when you enter anything that cannot be converted to a Double. The code then declares a Double to hold the result of the calculation and then gets the values from the two text box controls, converts the values to a Double using the ToDouble method of the Convert class, and then sets up a Select Case (switch in C#) block to handle the type of opera- tor you have chosen in the drop-down list: VB.NET Select Case OperatorList.SelectedValue Case "+" result = value1 + value2 C# switch (OperatorList.SelectedValue) { case "+": result = value1 + value2; break; c05.indd 172c05.indd 172 10/8/2012 9:52:22 AM10/8/2012 9:52:22 AM
    • Statements x 173 For each item in the drop-down list, there is a Case statement. When you have chosen the + operator from the list, the code in the first case block fires, and result is assigned the sum of the numbers you entered in the two text boxes. Likewise, when you choose the subtrac- tion operator, for example, the two values are subtracted from each other. At the end, the result is converted to a String and then displayed on the label called ResultLabel. The Select Case/switch statements close off the discussion about making decisions in your code. There’s one more group of statements left: loops that enable you to loop over code or over objects in a collection. Loops Loops are extremely useful in many applications, because they enable you to execute code repeti- tively, without the need to write that code more than once. For example, if you have a website that needs to send a newsletter by e-mail to its 20,000 subscribers, you write the code to send the newsletter once, and then use a loop that sends the newsletter to each subscriber the code finds in a database. Loops come as a few different types, each with their own usage and advantages. The For Loop The For loop simply repeats its code a predefined number of times. You define the exact number of iterations when you set up the loop. The For loop takes the following format: VB.NET For counter [ As datatype ] = start To end [ Step stepSize ] ' Code that must be executed for each iteration Next [ counter ] C# for (startCondition; endCondition; step definition) { // Code that must be executed for each iteration } This looks a little odd, but a concrete example makes this a lot easier to understand: VB.NET For loopCount As Integer = 1 To 10 Label1.Text &= loopCount.ToString() & "<br />" Next C# for (int loopCount = 1; loopCount <= 10; loopCount++) { Label1.Text += loopCount.ToString() + "<br />"; } c05.indd 173c05.indd 173 10/8/2012 9:52:23 AM10/8/2012 9:52:23 AM
    • 174 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES Although the syntax used in both languages is quite different, both code examples perform the same action: They write out numbers from 1 to 10 on a Label control. That is, the loop is started by the assignment of 1 to the variable loopCount. Next, the value is converted to a String and assigned to the Label control. Then loopCount is increased by 1, and the loop continues. This goes on until loopCount is 10, and then the loop ends. In this example, hard-coded numbers are used. However, you can replace the start and end conditions with dynamic values from variables or other objects. For example, if you’re working with the roles array you saw earlier, you can write out each role in the array like this: VB.NET For loopCount As Integer = 0 To roles.Length - 1 Label1.Text &= roles(loopCount) & "<br />" Next C# for (int loopCount = 0; loopCount < roles.Length; loopCount++) { Label1.Text += roles[loopCount] + "<br />"; } Because arrays are zero-based, you need to address the first item with roles(0) in VB.NET and roles[0] in C#. This also means that the loop needs to start at 0. The Length property of an array returns the total number of items that the array contains. So when three roles are in the array, Length returns 3. Therefore, in VB.NET the code subtracts one from the Length and uses that value as the end condition of the loop, causing the loop to run from 0 to 2, accessing all three elements. The C# example doesn’t subtract 1 from the Length, though. Instead it uses the expression: loopCount < roles.Length; So, as long as loopCount is less than the length of the array, the loop continues. Again, this causes the loop to access all three items, from 0 to 2. The previous examples loop by adding 1 to the loopCount variable on each iteration. To use a greater step increase, you use the keyword Step in VB.NET, whereas C# enables you to define the step size directly in the step definition: VB.NET For loopCount As Integer = 0 To 10 Step 2 Label1.Text &= loopCount.ToString() & "<br />" Next C# for (int loopCount = 0; loopCount <= 10; loopCount = loopCount + 2) { Label1.Text += loopCount.ToString() + "<br />"; } This loop assigns the even numbers between 0 and 10 to the Label control. If you are looping over an array or a collection of data, there’s another loop at your disposal that’s a bit easier to read and work with: the For Each or foreach loop. c05.indd 174c05.indd 174 10/8/2012 9:52:23 AM10/8/2012 9:52:23 AM
    • Statements x 175 The For Each/foreach Loop The For Each loop in VB.NET and the foreach loop in C# simply iterate over all the items in a collection. Taking the roles array as an example, you can execute the following code to print each role name on the Label control: VB.NET For Each role As String In roles Label1.Text &= role & "<br />" Next C# foreach (string role in roles) { Label1.Text += role + "<br />"; } Because the roles variable is an array of strings, you need to set up the loop with a String as well, as is done with the role variable. You would change this variable’s type if the collection contained items of a different type. In addition to the For and the For Each loops, there is one more loop that you need to look at: the While loop. The While Loop As its name implies, the While loop is able to loop while a certain condition is true. Unlike the other two loops, which usually end by themselves, the While loop could loop forever if you’re not careful. It could also not execute at all if its condition is never met. The following example shows how to use the While loop: VB.NET Dim success As Boolean = False While Not success success = SendEmailMessage() End While C# bool success = false; while (!success) { success = SendEmailMessage(); } This code tries to send an e-mail message using the fictitious SendEmailMessage method and will do so until it succeeds — that is, as long as the variable success has the value False (false in C#). Note that Not and ! are used to reverse the value of success. The SendEmailMessage method is supposed to return True when it succeeds and False when it doesn’t. If everything works out as planned, the code enters the loop and calls SendEmailMessage. If it returns True, the loop condi- tion is no longer met, and the loop ends. However, when SendEmailMessage returns False, for example because the mail server is down, the loop continues and SendEmailMessage is called again. c05.indd 175c05.indd 175 10/8/2012 9:52:23 AM10/8/2012 9:52:23 AM
    • 176 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES To avoid endless loops with the While loop, it’s often a good idea to add a condition that terminates the loop after a certain number of tries. For example, the following code helps to avoid an infinite loop if the mail server is down: VB.NET Dim success As Boolean = False Dim loopCount As Integer = 0 While Not success AndAlso loopCount < 3 success = SendEmailMessage() loopCount = loopCount + 1 End While C# bool success = false; int loopCount = 0; while (!success && loopCount < 3) { success = SendEmailMessage(); loopCount = loopCount + 1; } With this code, the variable loopCount is responsible for exiting the loop after three attempts to call SendEmailMessage. Instead of using loopCount = loopCount + 1, you can also use the combined concatenation and assignment operators, like this: VB.NET loopCount += 1 C# loopCount += 1; // Alternatively C# enables you to do this: loopCount++; All examples have the same result: the loopCount value is increased by one, after which the new total is assigned to loopCount again. Besides the While loop, you have a few other alternatives, such as the Do While loop (do while in C#), which ensures that the code to be executed is always executed at least once, and the Do Until loop (not available in C#), which goes on until a certain condition is true, as opposed to looping while a certain condition is true, as is the case with the While loop. Exiting Loops Prematurely It’s common to have the need to exit a loop before it has completely finished. You can do this with Exit For in VB.NET and break in C#, like this: VB.NET For loopCount As Integer = 1 To 10 If loopCount = 5 Then c05.indd 176c05.indd 176 10/8/2012 9:52:23 AM10/8/2012 9:52:23 AM
    • Organizing Code x 177 Exit For End If Label1.Text &= loopCount.ToString() & "<br />" Next C# for (int loopCount = 1; loopCount <= 10; loopCount++) { if (loopCount == 5) { break; } Label1.Text += loopCount.ToString() + "<br />"; } With this code, the label will only show the numbers 1 to 4, as the loop is exited as soon as loop- Count has reached the value of 5. Note: This example doesn’t have a lot of real-world usage as you would rewrite the code to loop four times only, but it shows the concept quite nicely. You can use Continue For in VB and continue in C# to stop processing the current iteration and move on with the next, if available. So far, the code you’ve seen has been comprised of short and simple examples that can be placed directly in the Code Behind of a web page; for example, in Page_Load or in a Button’s Click han- dler that you have seen before. However, in real-world websites, you probably want to structure and organize your code a lot more. In the next section, you see different ways to accomplish this. ORGANIZING CODE When you start adding more than just a few pages to your website, you’re almost certain to end up with some code that you can reuse in multiple pages. For example, you may have some code that reads settings from the Web.config file that you need in multiple files. Or you want to send an e-mail with user details from different pages. So you need to find a way to centralize your code. To accomplish this in an ASP.NET website, you can use functions and subroutines, which are discussed next. To make these functions and subroutines available to all the pages in your site, you need to create them in a special location, which is discussed afterward. Methods: Functions and Subroutines Functions and subroutines (subs) are very similar; both enable you to create a reusable block of code that you can call from other locations in your application. The difference between a function and a subroutine is that a function can return data, whereas a sub can’t. Together, functions and subrou- tines are referred to as methods. You’ll see that term again in the final part of this chapter that deals with object orientation. To make functions and subs more useful, they can be parameterized. That is, you can pass in addi- tional information that can be used inside the function or subs. Functions and subs generally take the following format: c05.indd 177c05.indd 177 10/8/2012 9:52:23 AM10/8/2012 9:52:23 AM
    • 178 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES VB.NET ' Define a function Public Function FunctionName ([parameterList]) As DataType End Function ' Define a subroutine Public Sub SubName ([parameterList]) End Sub C# // Define a function public DataType FunctionName([parameterList]) { } // Define a subroutine public void SubName([parameterList]) { } The complete first line, starting with Public, is referred to as the method signature because it defines the look of the function, including its name and its parameters. The Public keyword (pub- lic in C#) is called an access modifier and defines to what extent other web pages or code files can see this method. This is discussed in detail later in the chapter. For now, you should realize that Public has the greatest visibility, so the method is visible to any calling code. The name of the function is followed by parentheses, which in turn can contain an optional param- eter list. The italic parts in these code examples will be replaced with real values in your code. The parts between the square brackets ([]) are optional. To make it a little more concrete, here are some examples of functions and subs: VB.NET Public Function Add(a As Integer, b As Integer) As Integer Return a + b End Function Public Sub SendEmailMessage(emailAddress As String) ' Code to send an e-mail goes here End Sub C# public int Add(int a, int b) { return a + b; } public void SendEmailMessage(string emailAddress) { c05.indd 178c05.indd 178 10/8/2012 9:52:23 AM10/8/2012 9:52:23 AM
    • Organizing Code x 179 // Code to send an e-mail goes here } In these code examples it’s clear that functions return a value, and subs don’t. The Add method uses the Return keyword (return in all lowercase in C#) to return the sum of a and b. The Sub in VB.NET and the void method in C# don’t require the Return keyword, although you can use it to exit the method prematurely. Finally, both the function and subroutine have a parameter list that enables you to define the name and data type of variables that are passed to the method. Inside the method you can access these variables as you would access normal variables. In the case of the Add method, you have two param- eters: one for the left side of the addition and one for the right side. The SendEmailMessage method has only a single parameter: a String holding the user’s e-mail address. In earlier versions of VB.NET you would see the keyword ByVal in front of each parameter in the parameter list. This is the default type for all parameters, so VS no longer adds it for you. The oppo- site of ByVal is ByRef. These keywords determine the way a value is sent to the function or subrou- tine. When you specify ByVal, a copy of the variable is made. Any changes made to that copy inside the method are lost as soon as the method finishes. In contrast, when you specify ByRef, a reference to the variable is sent to the method. Any changes made to the incoming variable reflect on the origi- nal variable as well. The following short example demonstrates how this works: Public Sub ByValDemo(someValue As Integer) ' No ByVal needed as it's the default someValue = someValue + 20 End Sub Public Sub ByRefDemo(ByRef someValue As Integer) someValue = someValue + 20 End Sub Dim x As Integer = 0 ByValDemo(x) Label1.Text = x.ToString() ' Prints out 0; A copy of x is sent to ByValDemo, ' leaving the original value of x unmodified. Dim y As Integer = 0 ByRefDemo(y) Label1.Text = y.ToString() ' Prints out 20; A reference to y is sent ' to ByRefDemo so when that method modified ' someValue, it also changed the variable y. C# has a similar construct using the ref keyword. The biggest difference from VB.NET is that you need to specify the ref keyword in the call to the method as well: public void ByRefDemo(ref int someValue) { someValue = someValue + 20; } int y = 0; ByRefDemo(ref y); // Just as in the VB example, y contains 20 // after the call to ByRefDemo c05.indd 179c05.indd 179 10/8/2012 9:52:23 AM10/8/2012 9:52:23 AM
    • 180 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES Be careful when using reference parameters like this; before you know it the method may change important variables in the calling code. This can lead to bugs that are hard to track down. To make your sitewide methods accessible to pages in your website, you should place them in a cen- tralized location. The App_Code folder of your website is a perfect location for your code. The App_Code Folder The App_Code folder is a special ASP.NET folder. It’s designed specifically to hold code files, like classes that you’ll use throughout the site. Code that applies only to one page (like the handler of a Button control’s Click event) should remain in the page’s Code Behind, as you have seen so far. NOTE The App_Code folder is specific to Web Site Projects, the project type used for the Planet Wrox sample website. Web Application Projects, on the other hand, don’t use or support an App_Code folder. However, that project type enables you to create code files in pretty much any other location. When you build sites using the Web Application Project model, you’re advised to create a central code folder (called Code or CodeFiles, for example) to store all your code files. To follow along with the samples in this and later chapters, it’s impor- tant that you’re using a Web Site Project as explained in Chapter 2. To add the App_Code folder to your site, right-click the site’s name in the Solution Explorer and choose Add Í Add ASP.NET Folder Í App_Code. The folder is added to the site and gets a special icon, shown in Figure 5-4. FIGURE 5-4 With the App_Code folder in place, you can start adding class files to it. Class files have an exten- sion that matches the programming language you have chosen for the site: .cs for C# files and .vb for files containing VB.NET code. Inside these class files you can create classes that in turn contain methods (functions and subroutines) that can carry out common tasks. Classes are discussed in more detail in the final section of this chapter; for now, focus on the methods in the code file and how they are called, rather than on why you need to add the code to a class first. The next exercise shows you how to use the App_Code folder to optimize the calculator you created in an earlier Try It Out. c05.indd 180c05.indd 180 10/8/2012 9:52:24 AM10/8/2012 9:52:24 AM
    • Organizing Code x 181 TRY IT OUT Optimizing the Calculator In this exercise, you create a class called Calculator that exposes four methods: Add, Subtract, Multiply, and Divide. When the class is set up and is capable of performing the necessary computing actions, you modify the CalculatorDemo.aspx file so it uses your new Calculator class. Although this is a trivial example when it comes to the amount of code you need to write and the added flexibility you gain by moving your code from the ASPX page to the App_Code folder so it can be reused by other applications, it’s comprehensive enough to show you the concept, yet short enough to enable you to understand the code. For now, just focus on how the calculator works and how to call its methods. In the section on object orientation later in this chapter, you see exactly what a class is. 1. If you haven’t already done so, start by adding an App_Code folder to your site by right-clicking the site and choosing Add Í Add ASP.NET Folder Í App_Code. 2. Right-click this newly created folder and choose Add Í Add New Item. 3. In the dialog box that follows, select the appropriate programming language, and click Class. 4. Type Calculator as the name of the file and click Add. This creates a class file that in turn con- tains a class called Calculator. Note that it’s common practice to name classes using what’s called Pascal casing, where each word starts with a capital letter. 5. Right after the line of code that defines the Calculator class, add the following four methods, replacing any code that was already present in the class: VB.NET Public Class Calculator Public Function Add(a As Double, b As Double) As Double Return a + b End Function Public Function Subtract(a As Double, b As Double) As Double Return a - b End Function Public Function Multiply(a As Double, b As Double) As Double Return a * b End Function Public Function Divide(a As Double, b As Double) As Double Return a / b End Function End Class C# public class Calculator { public double Add(double a, double b) { return a + b; } public double Subtract(double a, double b) c05.indd 181c05.indd 181 10/8/2012 9:52:24 AM10/8/2012 9:52:24 AM DownloadfromWow!eBook<www.wowebook.com>
    • 182 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES { return a − b; } public double Multiply(double a, double b) { return a * b; } public double Divide(double a, double b) { return a / b; } } 6. Next, modify the Code Behind of the CalculatorDemo.aspx page so it uses the class you just cre- ated. You need to make two changes: First you need to add a line of code that creates an instance of the Calculator class, and then you need to modify each Case block to use the relevant calcula- tion methods in the calculator: VB.NET Dim myCalculator As New Calculator() Select Case OperatorList.SelectedValue Case "+" result = myCalculator.Add(value1, value2) Case "-" result = myCalculator.Subtract(value1, value2) Case "*" result = myCalculator.Multiply(value1, value2) Case "/" result = myCalculator.Divide(value1, value2) End Select C# Calculator myCalculator = new Calculator(); switch (OperatorList.SelectedValue) { case "+": result = myCalculator.Add(value1, value2); break; case "-": result = myCalculator.Subtract(value1, value2); break; case "*": result = myCalculator.Multiply(value1, value2); break; case "/": result = myCalculator.Divide(value1, value2); break; } 7. Save all your changes and open the page in the browser. The calculator still works as before; only this time the calculations are not carried out in the page’s Code Behind file, but by the Calculator class in the App_Code folder instead. c05.indd 182c05.indd 182 10/8/2012 9:52:24 AM10/8/2012 9:52:24 AM
    • Organizing Code x 183 How It Works The file you created in the App_Code folder contains a class called Calculator. You learn more about classes in the final section of this chapter, but for now it’s important to know that a class is like a defi- nition for an object that can expose methods you can call at run time. In this case, the definition for the Calculator class contains four methods to perform arithmetic operations. These methods accept parameters for the left-hand and right-hand sides of the calculations. Each method simply carries out the requested calculation (Add, Subtract, and so on) and returns the result to the calling code. The code in the Code Behind of the CalculatorDemo.aspx page first creates an instance of the Calculator class. That is, it creates an object in the computer’s memory based on the class definition. To do this, it uses the New (new in C#) keyword to create an instance of Calculator, which is then stored in the variable myCalculator. You learn more about the New keyword later in this chapter when objects are discussed. Note that the data type of this variable is Calculator, the name of the class. VB.NET Dim myCalculator As New Calculator() C# Calculator myCalculator = new Calculator(); Once the Calculator instance is created, you can call its methods. Just as you saw earlier with other methods, the methods of the Calculator class accept parameters that are passed in by the calling code: VB.NET Case "+" result = myCalculator.Add(value1, value2) C# case "+": result = myCalculator.Add(value1, value2); break; The Add method then adds the two values and returns the result as a Double, which is stored in the variable result. Just as in the first version of the calculator, at the end the result is displayed on the page with a Label control. Functions and subroutines are a great way to organize your web application. They enable you to create reusable blocks of code that you can easily call from other locations. Because code you need more than once is defined only once, it’s much easier to maintain or extend the code. If you find a bug in a function, simply fix it in its definition in the App_Code folder, and all pages using that func- tion automatically benefit from the change. In addition to the increased maintainability, functions and subs also make your code easier to read: Instead of wading through long lists of code in a page, you just call a single function and work with the return value (if any). This makes the code easier on your brain, minimizing the chance of bugs in your application. Functions and subs are not the only way to organize code in your .NET projects. Another common way to organize things is to use namespaces. c05.indd 183c05.indd 183 10/8/2012 9:52:24 AM10/8/2012 9:52:24 AM
    • 184 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES Organizing Code with Namespaces Namespaces seem to cause a lot of confusion with new developers. They think they’re scary, they think way too many of them exist, or they don’t see the need to use them. None of this is true, and with a short explanation of them, you’ll understand and maybe even like namespaces. Namespaces are intended to solve two major problems: to organize the enormous amount of func- tionality in the .NET Framework and in your own code, and to avoid name collisions, where two different types share the same name. One common misconception about namespaces is that there is a direct relation with .NET assemblies (files with a .dll extension that are loaded and used by the .NET Framework), but that’s not the case. Although you typically find namespaces like System .Web.UI in a DLL called System.Web.dll, it’s possible (and common) to have multiple namespaces defined in a single DLL or to have a namespace be spread out over multiple assemblies. Keep that in mind when adding references to assemblies, as explained later. To see what a namespace looks like, open one of the Code Behind files of the ASPX pages you’ve created so far. You’ll see something similar to this: VB.NET Partial Class Demos_CalculatorDemo Inherits System.Web.UI.Page C# public partial class Demos_CalculatorDemo : System.Web.UI.Page { Note that the definition of the class name is followed by the Inherits keyword in VB and a colon in C#, which in turn are followed by System.Web.UI.Page. You see later what this Inherits keyword is used for. In this code, Page is the name of a class (a data type), which is defined in the System .Web.UI namespace. By placing the Page class in the System.Web.UI namespace, developers (and compilers) can see this class is about a web page. By contrast, imagine the following (fictitious) class name: Microsoft.Word.Document.Page This code also refers to a Page class. However, because it’s placed in the Microsoft.Word .Document namespace, it’s easy to see that it’s referring to a page of a Word document, not a web page. This way there is no ambiguity between a web page and a Word document page. This in turn helps the compiler understand which class you are referring to. Another benefit of namespaces is that they help you find the right data type. Instead of displaying thousands and thousands of items in the IntelliSense list, you get a few top-level namespaces. When you choose an item from that list and press the dot key (.), you get another relatively short list with types and other namespaces that live inside the chosen namespace. Namespaces are nothing more than simple containers that you can refer to by name using the dot notation. They are used to prefix each data type that is available in your application. For example, the Double data type lives in the System namespace, thus its fully qualified name is System .Double. Likewise, the Button control you’ve added to your web pages lives in the System.Web .UI.WebControls namespace, thus its full name is System.Web.UI.WebControls.Button. c05.indd 184c05.indd 184 10/8/2012 9:52:24 AM10/8/2012 9:52:24 AM
    • Organizing Code x 185 It’s also easy to create your own namespaces. As long as they don’t collide with an existing name, you can pretty much make up your own namespaces as you see fit. For example, you could wrap the Calculator class in the following namespace (in Calculator.vb or Calculator.cs in App_Code): VB.NET Namespace Wrox.Samples Public Class Calculator ... End Class End Namespace C# namespace Wrox.Samples { public class Calculator { ... } } With the calculator wrapped in this namespace, you could create a new instance of it like this: VB.NET Dim myCalculator As New Wrox.Samples.Calculator() C# Wrox.Samples.Calculator myCalculator = new Wrox.Samples.Calculator(); Although you get some help from IntelliSense to find the Calculator class, typing these long names becomes boring after a while. Fortunately, there’s a fix for that as well. After you have created your own namespaces, or if you want to use existing ones, you need to make them available in your code. You do this with the keyword Imports (in VB.NET) or using (in C#). For example, to make your Calculator class available in the Calculator demo page without specify- ing its full name, you can add the following namespace to your code: VB.NET Imports Wrox.Samples Partial Class Demos_CalculatorDemo Inherits System.Web.UI.Page C# using Wrox.Samples; public partial class Demos_CalculatorDemo : System.Web.UI.Page { With this Imports/using statement in place, you can now simply use Calculator again instead of Wrox.Samples.Calculator. c05.indd 185c05.indd 185 10/8/2012 9:52:24 AM10/8/2012 9:52:24 AM
    • 186 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES If you are using C#, you’ll see a number of using statements by default in the Code Behind of an ASPX page for namespaces like System and System.Web.UI.WebControls. If you’re using VB.NET, you won’t see these references. Instead, with a VB.NET website, the default namespaces are included in the machine’s global Web.config file under the <namespaces> element. Quite often, you know the name of the class, but you don’t know the namespace it lives in. VS makes it very easy to find the namespace and add the required Imports or using statement for you. Simply type the name of the class you want to use and then place the cursor in the class name and press Ctrl+. (Ctrl+Dot). You see a menu appear that lets you select the right namespace, as shown in Figure 5-5. FIGURE 5-5 If the dialog box doesn’t offer to add an Imports or using statement, the assembly that contains the class you’re looking for may not be referenced by the project. If that’s the case, right-click the website in the Solution Explorer and choose Add Reference. In the dialog box that follows you can choose from the many built-in .NET assemblies on the .NET tab or browse to a third-party assem- bly using the Browse button. Once the reference is added you should be able to add an Imports or using statement for the class you’re looking for by pressing Ctrl+. again on the class name. Once you start writing lots of code, you may quickly forget where you declared what, or what a variable or method is used for. It’s therefore wholeheartedly recommended to put comments in your code. Writing Comments No matter how clean a coder you are, it’s likely that someday you will run into code that makes you raise your eyebrows and think, “What on earth is this code supposed to do?” Over the years, the way you program will change; you’ll learn new stuff, optimize your coding standards, and find ways to code more efficiently. To make it easier for you to recognize and understand your code now and two years from now, it’s a good idea to comment your code. You have two main ways to add com- ments in your code files: inline and as XML comments. Commenting Code Inline Inline comments are written directly in between your code statements. You can use them to com- ment on existing variables, difficult loops, and so on. In VB.NET, you can comment out only one line at a time using the tick (') character, which you place in front of the text that you want to use as a comment. To comment a single line in C#, you use two slashes (//). Additionally, you can use /* and */ to comment out an entire block of code in C#. The following examples show some different uses of comments: c05.indd 186c05.indd 186 10/8/2012 9:52:24 AM10/8/2012 9:52:24 AM
    • Organizing Code x 187 VB.NET ' Usage: explains the purpose of variables, statements and so on. ' Used to store the number of miles the user has traveled last year. Dim distanceInMiles As Integer ' Usage: comment out code that's not used (anymore). ' In this example, SomeUnfinishedMethod is commented out ' to prevent it from being executed. ' SomeUnfinishedMethod() ' Usage: End of line comments. If User.IsInRole("Administrators") Then ' Only allow admins in this area End If C# // Usage: explains the purpose of variables, statements and so on. // Used to store the number of miles the user has traveled last year. int distanceInMiles; // Usage: comment out code that's not used (anymore). // In this example, SomeUnfinishedMethod is commented out // to prevent it from being executed. // SomeUnfinishedMethod(); // Usage: End of line comments. if (User.IsInRole("Administrators")) // Only allow admins in this area { } /* * This is a block of comments that is often used to add additional * information to your code, for example to explain a difficult loop. You can * also use this to (temporarily) comment a whole block of code. */ To comment out the code, simply type the code character (' or //) at the location where you want the comment to start. To comment out a block of code, select it in the text editor and press Ctrl+K followed by Ctrl+C. Similarly, press Ctrl+K followed by Ctrl+U to uncomment a selected block of code. Alternatively, you can choose Edit Í Advanced Í Comment Selection or Uncomment Selection from the main menu. Inline comments are usually good for documenting small details of your code. However, it’s also a good idea to provide a high-level overview of what your code does. For example, for a method called SendEmailMessage it would be good to have a short description that explains what the method does and what the parameters are used for. This is exactly what XML comments are used for. Writing XML Comments XML comments are comments that you add as XML elements (using angle brackets: < >) in your code to describe its purpose, parameters, return value, and more. The VS IDE helps you by writing these comments. All you need to do is position your cursor on the line just before a class or method c05.indd 187c05.indd 187 10/8/2012 9:52:25 AM10/8/2012 9:52:25 AM
    • 188 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES and type ''' (three tick characters) for VB or /// (three forward slashes) for C#. As soon as you do that, the IDE inserts XML tags for the summary and, optionally, the parameters and return type of a method. Once again, consider a SendEmailMessage method. It could have two parameters of type String: one for the e-mail address to send the message to, and one for the mail body. With the XML comments applied, the method could look like this: VB.NET ''' <summary> ''' Sends out an e-mail to the address specified by emailAddress. ''' </summary> ''' <param name="emailAddress">The e-mail address of the recipient.</param> ''' <param name="mailBody">The body of the mail message.</param> ''' <returns>This method returns True when the message was sent successfully; ''' and False otherwise.</returns> ''' <remarks>Attention: this method assumes a valid mail server is ''' available.</remarks> Public Function SendEmailMessage(emailAddress As String, mailBody As String) As Boolean ' Implementation goes here End Function C# /// <summary> /// Sends out an e-mail to the address specified by emailAddress. /// </summary> /// <param name="emailAddress">The e-mail address of the recipient.</param> /// <param name="mailBody">The body of the mail message.</param> /// <returns>This method returns true when the message was sent successfully; /// and false otherwise.</returns> /// <remarks>Attention: this method assumes a valid mail server is /// available.</remarks> public bool SendEmailMessage(string emailAddress, string mailBody) { // Implementation goes here } The cool thing about this type of commenting is that the comments you type here show up in IntelliSense in the code editor when you try to call the method (see Figure 5-6). FIGURE 5-6 This makes it much easier for you and other developers to understand the purpose of the method and its parameters. In addition to aiding development in the code editor, you can also use the XML comments to create good-looking, MSDN-like documentation. A number of third-party tools are available that help you with this, including Microsoft’s own Sandcastle (http://msdn.microsoft.com/en-us/vstudio/ bb608422.aspx) and Document! X from Innovasys (www.innovasys.com/). c05.indd 188c05.indd 188 10/8/2012 9:52:25 AM10/8/2012 9:52:25 AM
    • Object Orientation Basics x 189 OBJECT ORIENTATION BASICS A chapter about writing code in ASP.NET wouldn’t be complete without a section on object ori- entation (OO). Object orientation, or object-oriented programming, is a highly popular style of programming where the software is modeled as a set of objects interacting with each other. Object orientation is at the heart of the .NET Framework. Literally everything inside the framework is an object, from simple things like integers to complex things like a DropDownList control, a connection to the database, or a data-driven control. Because object orientation is such an important aspect of .NET, it’s important to be familiar with the general concepts of object-oriented programming. At the same time, you don’t have to be an expert on OO to be able to build websites with ASP.NET. This section gives you a 10,000-foot over- view of the most important terms and concepts. This helps you get started with object orientation, so you can start building useful applications in the next chapter instead of keeping your nose in the books for the next three weeks. Important OO Terminology In object orientation, everything revolves around the concept of objects. In OO everything is, in fact, an object. But what exactly is an object? And what do classes have to do with them? Objects Objects are the basic building blocks of object-oriented programming languages. Just like in the real world, an object in OO-land is a thing, but stored in the computer’s memory. It can be an integer holding someone’s age or an open database connection to a SQL Server located on the other side of the world, but it can also be something more conceptual, like a web page. In your applications, you create a new object with the New (new in C#) keyword, as you saw with the calculator example. This process of creat- ing new objects is called instantiating and the objects you create are called instances. You can instantiate complex or custom types like Calculator, as well as simple types like Integers and Strings: VB.NET Dim myCalculator As Calculator = New Calculator() Dim age As Integer = New Integer() C# Calculator myCalculator = new Calculator(); int age = new int(); Because it’s so common to create variables of simple types like Integer (int in C#) and String (string in C#), the compiler allows you to leave out the new keyword and the assignment. Therefore, the following code is functionally equivalent to the preceding age declaration: VB.NET Dim age As Integer C# int age; c05.indd 189c05.indd 189 10/8/2012 9:52:25 AM10/8/2012 9:52:25 AM
    • 190 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES All data types listed at the beginning of this chapter except System.Object can be created without the New keyword. Once you have created an instance of an object, such as the myCalculator object, it’s ready to be used. For example, you can access its methods and properties to do something useful with the object. But before you look at methods and properties, you need to understand classes. Classes Classes are the blueprints of objects. Just as you can use a single blueprint to build a bunch of simi- lar houses, you can use a single class to create multiple instances of that class. So the class acts as the definition of the objects that you use in your application. At its most basic form, a class looks like this: VB.NET Public Class ClassName End Class C# public class ClassName { } Because this code simply defines an empty class, it cannot do anything useful. To give the class some behavior, you can give it fields, properties, methods, and constructors. In addition, you can let the class inherit from an existing class to give it a head start in terms of functionality and behavior. You’ll come to understand these terms in the next couple of sections. Fields Fields are simple variables declared at the class level that can contain data. They are often used as backing variables for properties (as you’ll see in the next section), but that doesn’t have to be the case. Here’s a quick example of a field in a Person class: VB.NET Public Class Person Private _firstName As String End Class C# public class Person { private string _firstName; } Fields are often marked as Private (private in C#), which makes them visible only in the class that defines them. If you have the need to expose fields to other classes as well, you should use proper- ties, which are discussed next. Later in the chapter you learn more about the Private keyword and other access modifiers. c05.indd 190c05.indd 190 10/8/2012 9:52:25 AM10/8/2012 9:52:25 AM
    • Object Orientation Basics x 191 Properties Properties of an object are the characteristics the object has. Consider a Person object. What kind of properties does a Person have? It’s easy to come up with many different characteristics, but the most common are: ‰ First name ‰ Last name ‰ Date of birth You define a property in a class with the Property keyword (in VB.NET) or with a property header similar to a method in C#. In both languages, you use a Get block (get in C#) and a Set block (set in C#) to define the so-called getters and setters of the property. The getter is accessed when an object is asked for the value of a specific property, and the setter is used to assign a value to the property. Properties only provide access to underlying data stored in the object; they don’t contain the actual data. To store the data, you need what is called a backing variable. This is often a simple field defined in the class that is able to store the value for the external property. In the following example, the variable _firstName is the backing variable for the FirstName property: VB.NET Public Class Person Private _firstName As String Public Property FirstName() As String Get Return _firstName End Get Set(value As String) _firstName = value End Set End Property End Class C# public class Person { private string _firstName; public string FirstName { get { return _firstName; } set { _firstName = value; } } } It is common to prefix the private backing variables with an underscore, followed by the first word in all lowercase, optionally followed by more words that start with a capital again. So the FirstName property has a backing variable called _firstName, LastName has one called _lastName, and so on. This way, all variables that apply to the entire class are nicely packed together in the IntelliSense list. Simply type an underscore in your code and you’ll get the full list of private variables. Note that the underscore is typically not used when defining variables inside a function or a subroutine. c05.indd 191c05.indd 191 10/8/2012 9:52:25 AM10/8/2012 9:52:25 AM
    • 192 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES Just like the Public keyword you saw earlier, Private is also an access modifier. You learn more about access modifiers later in this chapter. The main reason for a property in a class is to encapsulate data. The idea is that a property enables you to control the data that is being assigned to it. This way, you can perform validation or manipu- lation of the data before it’s stored in the underlying backing variable. Imagine that one of the busi- ness rules of your application states that all first names must be written with the first letter as a capital. In non–object-oriented languages, the developer setting the name would have to keep this rule in mind every time a variable was filled with a first name. In an OO approach, you can make the FirstName property responsible for this rule so others don’t have to worry about it anymore. You can do this type of data manipulation in the setter of the property: VB.NET Set(value As String) If Not String.IsNullOrEmpty(value) Then _firstName = value.Substring(0, 1).ToUpper() & value.Substring(1) Else _firstName = String.Empty End If End Set C# set { if (!string.IsNullOrEmpty(value)) { _firstName = value.Substring(0, 1).ToUpper() + value.Substring(1); } else { _firstName = string.Empty; } } This code demonstrates that in both VB.NET and C#, the value parameter is accessible, just as a parameter is accessible to a method. The value parameter contains the value that is being assigned to the property. In VB.NET, the value parameter is defined explicitly in the property’s setter. In C# it’s not specified explicitly, but you can access it nonetheless. The code first checks if the value that is being passed is not Nothing (null in C#) and that it doesn’t contain an empty string, using the handy String.IsNullOrEmpty method. The code in the If block then takes the first letter of value, using the Substring method of the String class, to which it passes the values 0 and 1. The 0 indicates the start of the substring and the 1 indicates the length of the string that must be returned. String indexing is zero-based as well, so a start of 0 and a length of 1 effectively returns the first character of the value parameter. This character is then changed to uppercase using ToUpper(). Finally, the code takes the remainder of the value param- eter using Substring again and assigns the combined name back to the backing variable. In this call to Substring, only the start index is passed, which returns the string from that position to the end. You can now use code that sets the name with arbitrary casing. But when you try to access the name again, the first name will always begin with a proper first character: c05.indd 192c05.indd 192 10/8/2012 9:52:25 AM10/8/2012 9:52:25 AM
    • Object Orientation Basics x 193 VB.NET Dim myPerson As Person = New Person() ' Create a new instance of Person myPerson.FirstName = "imar" ' Accessing setter to change the value Label1.Text = myPerson.FirstName ' Accessing getter that now returns Imar C# Person myPerson = new Person(); // Create a new instance of Person myPerson.FirstName = "imar"; // Accessing setter to change the value Label1.Text = myPerson.FirstName; // Accessing getter that now returns Imar For simple properties that don’t need any data manipulation or validation, you can use so-called automatic properties. With these properties, you can use a much more condensed syntax without the need for a private backing variable. When the code is compiled, the compiler creates a hidden backing variable for you, and you’ll need to refer to the public property. Here’s the DateOfBirth property of the Person class, written as an automatic property: VB.NET Public Property DateOfBirth As DateTime C# public DateTime DateOfBirth { get; set; } The Visual Basic implementation of automatic properties has one advantage over the C# ver- sion: You can declare the property and give it a value in one shot. The following snippet defines a CreateDate property and assigns it with the current date and time: VB.NET Public Property CreateDate As DateTime = DateTime.Now To assign a default value to an automatic property in C#, you need to set its value using construc- tors, which are discussed later. If you later decide you need to write code in the getter or the setter of the property, it’s easy to extend the relevant code blocks without breaking your existing applications. Until that time, you have nice, clean property definitions that don’t clutter up your class. Creating Read-Only and Write-Only Properties At times, read-only or write-only properties make a lot of sense. For example, the ID of an object could be read-only if it is assigned by the database automatically. When the object is constructed from the database, the ID is assigned to the private backing variable. The public Id property is then made read-only to stop calling code from accidentally changing it. Likewise, you can have a write- only property for security reasons. For example, you could have a Password property on a Person object that you can only assign to if you know it, but no longer read it afterward. Internally, code within the class can still access the backing variables to work with the password value. Another good candidate for a read-only property is one that returns a combination of data. Consider a FullName property of a Person class that returns a combination of the FirstName and LastName properties. You use the setter of each individual property to assign data, but you can have a read- only property that returns the concatenated values. c05.indd 193c05.indd 193 10/8/2012 9:52:26 AM10/8/2012 9:52:26 AM
    • 194 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES Read-only or write-only properties in C# are simple: Just leave out the setter (for a read-only prop- erty) or the getter (for a write-only property). VB.NET is a bit more verbose and wants you to spec- ify the keyword ReadOnly or WriteOnly explicitly. The following code snippet shows a read-only FullName property in both VB.NET and C#: VB.NET Public ReadOnly Property FullName() As String Get Return _firstName & " " & _lastName End Get End Property C# public string FullName { get { return _firstName + " " + _lastName; } } When you try to assign a value to a read-only property, you’ll get a compilation error in VS. Similar to properties, objects can also have methods. Methods If properties are the things that a class has (its characteristics), then methods are the things a class can do or the operations it can perform. A Car class, for example, has properties such as Brand, Model, and Color. Its methods could be Drive(), Brake(), and OpenDoors(). Methods give objects the behavior that enables them to do something. You have already seen methods at work earlier, when this chapter discussed some ways to write organized code using subs and functions. You simply add methods to a class by writing a function or a sub between the start and end elements of the class. For example, imagine the Person class has a Save method that enables the object to persist itself in the database. The method’s signature could look like this: VB.NET Public Class Person Public Sub Save() ' Implementation goes here End Sub End Class C# public class Person { public void Save() { // Implementation goes here } } If you want to call the Save method to have the Person object save itself to the database, you create an instance of it, set the relevant properties such as FirstName, and then call Save: c05.indd 194c05.indd 194 10/8/2012 9:52:26 AM10/8/2012 9:52:26 AM
    • Object Orientation Basics x 195 VB.NET Dim myPerson As Person = New Person() myPerson.FirstName = "Jim" myPerson.Save() C# Person myPerson = new Person(); myPerson.FirstName = "Jim"; myPerson.Save(); The Save method would then know how to save the Person in the database. Methods can also have parameters, as you saw earlier in the section on XML comments. The SendEmailMessage method accepts two parameters — one for the e-mail address and one for the message body — whose values are then accessible from within the method. Note that a new instance of the Person class is created with the New (new in C#) keyword followed by the class name. When this code fires, it calls the object’s constructor, which is used to create instances of objects. Constructors Constructors are special methods in a class that help you create an instance of your object. They run as soon as you try to create an instance of a class, so they are a great place to initialize your objects to some default state. Earlier you learned that you create a new instance of an object using the New (new in C#) keyword: VB.NET Dim myCalculator As Calculator = New Calculator() C# Calculator myCalculator = new Calculator(); The New keyword is followed by the object’s constructor: the name of the class. By default, when you create a new class file in VS, you get a default constructor for C# but not for VB.NET. That’s not really a problem, though, because the compiler generates a default constructor for you if no other constructor exists. A default constructor has no arguments and takes the name of the class in C# and the reserved keyword New in VB.NET: VB.NET Public Class Person Public Sub New() End Sub End Class C# public class Person { public Person() { } } c05.indd 195c05.indd 195 10/8/2012 9:52:26 AM10/8/2012 9:52:26 AM
    • 196 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES Although this default constructor is nice for creating standard instances of your classes, sometimes it is really useful to be able to send some information into the class up front, so it’s readily available as soon as it is constructed. For example, with the Person class, it could be useful to pass in the first and last names and the date of birth to the constructor so that data is available immediately afterward. To enable this scenario, you can create a specialized constructor. To have the constructor accept the names and the date of birth, you need the following code: VB.NET Public Sub New(firstName As String, lastName As String, dateOfBirth As DateTime) _firstName = firstName _lastName = lastName _dateOfBirth = dateOfBirth End Sub C# public Person(string firstName, string lastName, DateTime dateOfBirth) { _firstName = firstName; _lastName = lastName; _dateOfBirth = dateOfBirth; } With this code, you can create a new Person object: VB.NET Dim myPerson As Person = New Person("Imar", "Spaanjaars", New DateTime(1971, 8, 9)) C# Person myPerson = new Person("Imar", "Spaanjaars", new DateTime(1971, 8, 9)); The constructor accepts the values passed to it and assigns them to the private backing variables, so right after this line of code, the myPerson object is fully initialized. You can have multiple constructors for the same class, as long as each one has a different method signature. Visual Basic supports a slightly different syntax to declare and initialize an object in one fell swoop using the Dim myVariable As New ClassName syntax. The following code is equivalent to the pre- vious instantiation of a Person instance: Dim myPerson As New Person("Imar", "Spaanjaars", New DateTime(1971, 8, 9)) In addition to constructors, .NET offers another quick way to create an object and initialize a few properties: object initializers. With an object initializer, you provide the initial values for some of the properties at the same time you declare an instance of your objects. The following code creates a Person object and assigns it a value for the FirstName and LastName properties: VB.NET Dim myPerson As New Person() With {.FirstName = "Imar", .LastName = "Spaanjaars"} c05.indd 196c05.indd 196 10/8/2012 9:52:26 AM10/8/2012 9:52:26 AM
    • Object Orientation Basics x 197 C# Person myPerson = new Person() { FirstName = "Imar", LastName = "Spaanjaars" }; In VB.NET, you need the With keyword in front of the properties list. In addition, you need to pre- fix each property name with a dot (.). Other than that, the syntax is the same for both languages. Object initializers are great if you need to set a bunch of properties on an object quickly without being forced to write specialized versions of the constructors. Although it’s useful to have this Person class in your application, at times you may need specialized versions of a Person. For example, your application may require classes like Employee and Student. What should you do in this case? Create two copies of the Person class and name them Employee and Student, respectively? Although this approach certainly works, it has a few large drawbacks. The biggest problem is the duplication of code. If you decide to add a SocialSecurityNumber property, you now need to add it in multiple locations: in the general Person class and in the Employee and Student classes. Object inheritance, a major pillar of object orientation, is designed to solve problems of this kind. Inheritance Earlier you learned that System.Object is the parent of all other data types in .NET, including all the built-in types and types that you define yourself, meaning that each type in .NET (except Object itself) inherits from Object. One of the benefits of inheritance is that you can define a behavior at a high level (for example in the Object class) that is available to inheriting classes auto- matically without the need to duplicate that code. In the .NET Framework, the Object class defines a few members that all other objects inherit, including the ToString() method. To let one class inherit another, you need to use the Inherits keyword in VB.NET and the colon (:) in C#, as shown in the following example that defines a Student class that inherits Person: VB.NET Public Class Student Inherits Person C# public class Student : Person { } To see how inheritance works, think again about the Person class shown in earlier examples. That class had a few properties, such as FirstName and LastName, and a Save method. But if it is inheriting from Object, does it also have a ToString() method? You bet it does. Figure 5-7 shows the rela- tionship between the Object class and the Person class that inherits from Object. FIGURE 5-7 c05.indd 197c05.indd 197 10/8/2012 9:52:26 AM10/8/2012 9:52:26 AM
    • 198 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES Figure 5-7 shows that Person inherits from Object (indicated by the arrow pointing in the direction of the class that is being inherited from), which in turn means that a Person instance can do what- ever an Object can do. So, for example, you can call ToString() on your Person object: Label1.Text = myPerson.ToString() ' Writes out Person The default behavior of the ToString() method defined in Object is to say its own class name. In the preceding example, it means that the Person class inherits this behavior and thus says Person as its name. Usually, this default behavior is not enough, and it would be much more useful if the Person could return the full name of the person it is representing, for example. You can easily do this by overriding the ToString() method. Overriding a method or property redefines the behav- ior the class inherits from its parent class. To override a method you use the keyword Overrides in VB.NET and override in C#. The following snippet redefines the behavior of ToString in the Person class: VB.NET Public Overrides Function ToString() As String Return FullName & ", born at " & _dateOfBirth.ToShortDateString() End Function C# public override string ToString() { return FullName + ", born at " + _dateOfBirth.ToShortDateString(); } With this definition of ToString in the Person class, it no longer returns the word Person, but now returns the full name of the person it is representing: Label1.Text = myPerson.ToString() ' Imar Spaanjaars, born at 8/9/1971 Notice how the code uses the read-only FullName property to avoid coding the logic of concatenat- ing the two names again. You can’t just override any method member you want to. For a method to be overridable, the parent class needs to mark the member with the keyword virtual (in C#) or Overridable (in VB.NET). Object inheritance in .NET enables you to create a hierarchy of objects that enhance, or add func- tionality to, other objects. This enables you to start out with a generic base class (Object). Other classes can then inherit from this class, adding specialized behavior. If you need even more special- ized classes, you can inherit again from the class that inherits from Object, thus creating a hierar- chy of classes that keep getting more specialized. This principle works for many classes in the .NET Framework, including the Page class. You may not realize it, but every ASPX page you create in VS is actually a class that inherits from the class System.Web.UI.Page. This Page class in turn inher- its from TemplateControl, which inherits from Control, which inherits from Object. The entire hierarchy is shown in Figure 5-8. At the bottom you see the class MyWebPage, which could be a Code Behind class of a page such as MyWebPage.aspx. c05.indd 198c05.indd 198 10/8/2012 9:52:26 AM10/8/2012 9:52:26 AM
    • Object Orientation Basics x 199 FIGURE 5-8 In Figure 5-8 you can see that TemplateControl is an abstract class — a class that cannot be instantiated; that is, you cannot use New (new in C#) to create a new instance of it. It serves solely as a common base class for others (like Page) that can inherit from it. The exact classes between Page and Object are not really relevant at this stage, but what’s important is that your page inherits all the behavior that the Page class has. The fact that all your ASPX pages inherit from Page is more useful than you may think at first. Because it inherits from Page, you get loads of properties and methods defined in this class for free. For example, the Page class exposes a Title property that, when set, ends up as a <title> element in the page. Your page can simply set this property, and the parent Page class handles the rest for you: VB.NET Title = "Beginning ASP.NET 4.5 in C# and VB from Wrox" C# Title = "Beginning ASP.NET 4.5 in C# and VB from Wrox"; You use inheritance in the next chapter when you create a BasePage class that serves as the parent class for most of the pages you create in the Planet Wrox website. In earlier examples, including the override for the ToString() method, you have seen the keyword Public. Additionally, when creating backing variables, you saw the keyword Private. These key- words are called access modifiers and determine the visibility of your code. c05.indd 199c05.indd 199 10/8/2012 9:52:26 AM10/8/2012 9:52:26 AM
    • 200 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES Access Modifiers Earlier in this chapter I mentioned that a core concept of OO is encapsulation. By creating members such as functions and properties, you make an object responsible for the implementation. Other objects interacting with this object consider those methods and properties as black boxes. That is, they pass some data in and optionally expect some result back. How the method performs its work is of no interest to them; it should just work as advertised. To enable an object to shield some of its inner operations, you need a way to control access to types and members. You do this by specify- ing an access modifier in front of the class, property, or method name. The following table lists the available access modifiers for C# and VB.NET and explains their purpose. C# VB.NET Description public Public The class or member can be accessed from everywhere, including code outside the current application. protected Protected Code with a protected access modifier is available only within the type that defines it or within types that inherit from it. For example, a protected member defined in the Page class is accessible to your ASPX page because it inherits from Page. internal Friend Limits the accessibility of your code to other code within the same assem- bly. An assembly is a set of one or more compiled code files (either an .exe or a .dll file) containing reusable .NET code. private Private A class or member that is accessible only within the type that defines it. For example, with the Person class, the _firstName variable is accessible only from within the Person class. Other code, like an ASPX page, cannot access this field directly, and needs to access the public FirstName property to get or set the first name of a person. Of these four access modifiers, only protected and internal (Protected and Friend in VB) can be combined. The other two must be used separately. By combining protected and internal, you can create members that are accessible by the current class and any class that inherits from it in the current assembly only. Using access modifiers, you can now create properties that are read-only for external code but that can still be set from within the class by marking the getter as private. As with some of the other OO concepts, you won’t be spending half your day specifying access modifiers in your code. However, it’s good to know that they exist and what they do. That way, you may have a clue as to why sometimes your classes don’t show up in the IntelliSense list. There’s a fair chance you forgot to specify the public access modifier (Public in VB.NET) on the class in that case. The default is internal (Friend in VB.NET), which makes the class visible to other classes in the same assembly but hides it from code outside the assembly. Adding the keyword pub- lic or Public in front of the class definition should fix the problem. c05.indd 200c05.indd 200 10/8/2012 9:52:27 AM10/8/2012 9:52:27 AM
    • Object Orientation Basics x 201 Events The final important topic that needs to be discussed in this chapter is events. ASP.NET is an event- driven environment, which means that code can execute based on certain events that occur in your application. Events are raised by certain objects in the application and then handled by others. Many objects in the .NET Framework are capable of raising an event, and you can even add your own events to classes that you write. To be able to handle an event raised by an object, you need to write an event handler, which is basi- cally a normal method with a special signature. You can wire up this event handler to the event using event wiring syntax, although VS takes care of writing that code most of the time for you. When an object, such as a control in a web page, raises an event, it may have the need to pass addi- tional information to the event handler, to inform it about relevant data that caused or influenced the event. You can send out this information using an event arguments class, which is the class System.EventArgs or any class that inherits it. To see how all these terms fit together, consider what happens when you click a button in a web page. When you click it, the client-side button in the browser causes a postback. At the server, the Button control sees it was clicked in the browser and then raises its Click event. It’s as if the but- ton says: “Oh, look, everyone. I just got clicked. In case anyone is interested, here are some details.” Usually, the code that is interested in the button’s Click event is your own page, which needs to have an event handler to handle the click. You can create an event handler for the Button by dou- ble-clicking it in the designer, or you can wire it up using Markup View as you saw in Chapter 4. Alternatively, you can double-click the relevant event on the Events tab of the Properties Grid. You open this tab by clicking the button with the lightning bolt on the toolbar of the Properties Grid (see Figure 5-9.) FIGURE 5-9 If you double-click the control in Design View or the event name in the Properties Grid, VS writes the code for the event handler for you. The following snippet shows the handler for a Button con- trol’s Click event in VB.NET and C#: VB.NET Protected Sub Button1_Click(sender As Object, e As EventArgs) _ Handles Button1.Click End Sub c05.indd 201c05.indd 201 10/8/2012 9:52:27 AM10/8/2012 9:52:27 AM
    • 202 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES C# protected void Button1_Click(object sender, EventArgs e) { } In the VB.NET example, you see a standard method with some arguments, followed by Handles Button1.Click. This is the event wiring code that hooks up the Button control’s Click event to the Button1_Click method. Now, whenever the button is clicked, the code inside Button1_Click is executed. The C# version doesn’t have this Handles keyword. Instead, with C# you’ll find that VS has added the following bold code to the Button control in the markup of the page: <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> With this piece of markup, the compiler generates the necessary code to link up the Button1_Click method to the Click event of the button. At run time you’ll see the exact same behavior: When you click the button, the code in Button1_Click is executed. Note that if you wire up an event in Markup View in VB.NET, you get the same behavior as in C#; in that case the Handles keyword is omitted from the Code Behind because there’s already an On handler in Markup View. You can also see that this Button1_Click event handler has two parameters: an Object called sender and an EventArgs class called e. This is a standard .NET naming scheme and is followed by all objects that generate events. The sender parameter contains a reference to the object that triggered the event, Button1 in this example. This enables you to find out who triggered an event in case you wired up multiple events to the same event handler. The second parameter is an instance of the EventArgs class and supplies additional arguments to the event. With a button’s click, there is no additional relevant data to submit, so the plain and empty EventArgs class is used. However, in later chapters (for example, Chapter 9, which deals with data-driven Web Forms), you see some examples of classes that fire events with richer information. With the concepts of events, you have come to the end of the section on object orientation. This sec- tion should have familiarized you with the most important terms used in object-oriented program- ming. You see practical examples of these concepts in the remainder of this book. PRACTICAL TIPS ON PROGRAMMING The following list presents some practical tips on programming: ‰ Always give your variables meaningful names. For simple loop counters you can use i, although loopCount probably describes the purpose of the variable much better. Don’t pre- fix variables with the word var. All variables are variables, so adding var only adds noise to your code. Consider useful names such as _firstName and _categoryId as opposed to strFName, varFirstName, or catI for private fields, and names like FirstName and Person for public properties and classes, respectively. c05.indd 202c05.indd 202 10/8/2012 9:52:27 AM10/8/2012 9:52:27 AM
    • Summary x 203 ‰ Experiment and experiment. Even more so than with working with controls and ASPX pages, the best way to learn how to program is by actually doing it. Just type in some code and hit Ctrl+F5 to see how the code behaves. The compiler will bark at you when something is wrong, providing you with useful hints on how to fix it. Don’t be afraid to mess anything up; just keep trying variations until the code does what you want it to do. If you can’t make your code work, check out Chapter 18, which deals with debugging. You’ll find useful tips to locate and fix many of the errors that may occur in your code. ‰ When writing functions or subroutines, try to minimize the number of lines of code. Usually, methods with more than 40 or 50 lines of code are a sign of bad design. When you see such code, consider the option to move certain parts to their own routine. This makes your code much easier to understand, leading to better code with fewer bugs. Even if a method is used only once, keeping a chunk of code in a separate method can significantly increase the read- ability and organization of your code. ‰ When writing comments in your code, try to describe the general purpose of the code instead of explaining obvious statements. For example, this comment (seen many times in real code) is completely useless and only adds noise: Dim loopCount As Integer = 0 ' Declare loopCount and initialize it to zero Anyone with just a little bit of coding experience can see what this code does. SUMMARY Although programming can get really complex, the bare basics that you need to understand are relatively easy to grasp. The fun thing about programming is that you don’t have to be an expert to make useful programs. You can start with a simple Hello World example and work from there, each time expanding your view on code a little. This chapter covered two main topics. First, you got an introduction to programming in .NET using either C# or VB.NET. You saw what data types and variables are and learned about operators, decision making, and loops. You also saw how to write organized code using functions, subs, and namespaces and how to add comments to your code. The final section of this chapter dealt with object orientation. Though object orientation in itself is a very large subject, the basics are easy to pick up. In this chapter you learned about the basic ele- ments of OO programming: classes, methods, properties, and constructors. You also learned a bit about inheritance, the driving force behind object-oriented design. In the next chapter, which deals with creating consistent-looking web pages, you see inheritance again when you create a BasePage class that serves as the parent for most of the Code Behind classes in the Planet Wrox project. c05.indd 203c05.indd 203 10/8/2012 9:52:27 AM10/8/2012 9:52:27 AM
    • 204 x CHAPTER 5 PROGRAMMING YOUR ASP.NET WEB PAGES EXERCISES 1. Considering the fact that the oldest person in the world lived to be 122, what’s the best numeric data type to store a person’s age? Bonus points if you come up with an even better alternative to store someone’s age. 2. What does the following code do? VB.NET DeleteButton.Visible = Not DeleteButton.Visible C# DeleteButton.Visible = !DeleteButton.Visible; 3. Given the following class Person, what would the code look like for a new class Student that con- tains a string property called StudentId? Make use of inheritance to create this new class. VB.NET Public Class Person Public Property Name As String End Class C# public class Person { public string Name { get; set; } } You can find answers to these exercises in Appendix A. c05.indd 204c05.indd 204 10/8/2012 9:52:28 AM10/8/2012 9:52:28 AM
    • Summary x 205 WHAT YOU LEARNED IN THIS CHAPTER Class A blueprint for objects in a programming language Collection A special data type that is capable of holding multiple objects at the same time Encapsulation Hiding the inner workings and data of a class from the outside world in order to better manage and protect that data Instantiating The process of creating a new object in memory based on a type’s definition Method An operation on an object, like Brake() for a Car class Namespace A way to structure classes and other types in a hierarchi- cal manner Object Orientation A popular style of programming where the software is modeled as a set of objects interacting with each other Overriding Redefining the behavior in a child class of a member defined in a parent class Property A characteristic of an object, like the first name of a person c05.indd 205c05.indd 205 10/8/2012 9:52:28 AM10/8/2012 9:52:28 AM
    • c05.indd 206c05.indd 206 10/8/2012 9:52:28 AM10/8/2012 9:52:28 AM
    • Creating Consistent Looking Websites WHAT YOU WILL LEARN IN THIS CHAPTER: ‰ How to use master and content pages that enable you to define the global look and feel of a web page ‰ How to work with a centralized base page that enables you to define common behavior for all pages in your site ‰ How to create themes to define the look and feel of your site with an option for the user to choose a theme at run time ‰ How to create skins to make site-wide changes to control layout ‰ What the ASP.NET page life cycle is and why it’s important WROX.COM CODE DOWNLOADS FOR THIS CHAPTER You can find the wrox.com code downloads for this chapter on the Download Code tab at www.wrox.com/remtitle.cgi?isbn=1118311809. The code is in the Chapter 6 download. When you’re building a website you should strive to make the layout and behavior as consis- tent as possible. Consistency gives your site a professional appearance and it helps your visi- tors to find their way around the site. Fortunately, ASP.NET 4.5 and Visual Studio 2012 offer a number of great features and tools to implement a consistent design, helping you to create great-looking pages in no time. In previous chapters you learned how to work with VS, HTML5, CSS, and server controls to create your web pages visually. Chapter 5 introduced you to programming in ASP.NET. This chapter is the first that combines these concepts, by showing you—among many other things—how to use programming code to change the appearance of the site. 6 c06.indd 207c06.indd 207 10/8/2012 9:54:17 AM10/8/2012 9:54:17 AM
    • 208 x CHAPTER 6 CREATING CONSISTENT LOOKING WEBSITES The first section shows you how to create a master page that defines the general look and feel of a page. The ASPX pages in your site can then use this master page without the need to repeat the gen- eral layout. The remaining sections of this chapter build on top of this master page. CONSISTENT PAGE LAYOUT WITH MASTER PAGES With most websites, only part of the page changes when you go from one page to another. The parts that don’t change usually include common regions like the header, a menu, and the footer. To cre- ate web pages with a consistent layout, you need a way to define these relatively static regions in a single template file. Versions of ASP.NET prior to 2.0 did not have a template solution, so you were forced to duplicate your page layout on every single page in the website, or resort to weird program- ming tricks. Fortunately, this is no longer the case due to master pages. The biggest benefit of master pages is that they enable you to define the look and feel of all the pages in your site in a single loca- tion. This means that if you want to change the layout of your site—for instance, if you want to move the menu from the left to the right—you need to modify only the master page, and the pages based on this master pick up the changes automatically. When master pages were introduced in ASP.NET 2.0, they were quickly embraced by the developer community as the template solution for ASP.NET pages because they are very easy to use. Even bet- ter, VS has great design-time support, because it enables you to create and view your pages at design time during development, rather than only in the browser at run time. To some extent, a master page looks like a normal ASPX page. It contains static HTML such as the <html>, <head>, and <body> elements, and it can also contain other HTML and ASP.NET Server Controls. Inside the master page, you set up the markup that you want to repeat on every page, like the general structure of the page and the menu. However, a master page is not a true ASPX page and cannot be requested in the browser directly; it only serves as the template on which real web pages—called content pages—are based. Instead of the @ Page directive that you saw in Chapter 4, a master page uses an @ Master directive that identifies the file as a master page: VB.NET <%@ Master Language="VB" %> C# <%@ Master Language="C#" %> Just like a normal ASPX page, a master page can have a Code Behind file, identified by its CodeFile and Inherits attributes: c06.indd 208c06.indd 208 10/8/2012 9:54:23 AM10/8/2012 9:54:23 AM
    • Consistent Page Layout with Master Pages x 209 VB.NET <%@ Master Language="VB" CodeFile="Frontend.master.vb" Inherits="MasterPages_Frontend" %> C# <%@ Master Language="C#" AutoEventWireup="true" CodeFile="Frontend.master.cs" Inherits="MasterPages_Frontend" %> To create regions that content pages can fill in, you define ContentPlaceHolder controls in your page like this: <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> You can create as many placeholders as you like, although you usually need only a few to create a flexible page layout. The content pages, which are essentially normal ASPX files, without the code that they’re going to take from the master page, are connected to a master page using the MasterPageFile attribute of the Page directive: VB.NET <%@ Page Title="" Language="VB" MasterPageFile="~/MasterPages/Frontend.master" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default"> C# <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPages/Frontend.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"> The page-specific content is then put inside a Content control that points to the relevant ContentPlaceHolder: <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"> </asp:Content> Note that the ContentPlaceHolderID attribute of the Content control points to the ContentPlaceHolder that is defined in the master page. Right now it points to the default name of ContentPlaceHolder1, but in a later exercise you see how to change this. At run time, when the page is requested, the markup from the master page and the content page are merged, processed, and sent to the browser. Figure 6-1 shows a diagram of the master page with just one ContentPlaceHolder and the content page that results in the final page that is sent to the browser. c06.indd 209c06.indd 209 10/8/2012 9:54:23 AM10/8/2012 9:54:23 AM DownloadfromWow!eBook<www.wowebook.com>
    • 210 x CHAPTER 6 CREATING CONSISTENT LOOKING WEBSITES Master Page Header Menu ContentPlaceHolder Header Final Page Menu Content Page FIGURE 6-1 To see this process in action, the following sections guide you through creating master and content pages. Creating Master Pages You can add master pages to the site using the Add New Item dialog box. You can place them in any custom folder in the site, including the root folder, but from an organizational point of view, it’s often easier to store them in a separate folder. Just like normal ASPX pages, they support the inline code model as well as the Code Behind model. The master pages used in the Planet Wrox project use the Code Behind model exclusively. In the following exercise, you learn how to create a simple mas- ter page and add some HTML to it to define the general structure of the pages in your website. TRY IT OUT Creating a Master Page 1. Open the Planet Wrox project in Visual Studio if it is not open already. 2. In Chapter 2 you created a folder called MasterPages to hold your master pages and then added a single master page to that folder. If you didn’t carry out that exercise, add the master page now. To do this, create the MasterPages folder in the root of the site, right-click the new folder, choose Add Í Add New Item, and select the Master Page item. Make sure that the master page uses Code Behind and that it is using your preferred programming language. Name the master page Frontend.master. Finally, click Add. c06.indd 210c06.indd 210 10/8/2012 9:54:23 AM10/8/2012 9:54:23 AM
    • Consistent Page Layout with Master Pages x 211 3. Add the following highlighted code between the <form> tags of the master page, replacing the <div> tags and the ContentPlaceHolder that VS added for you when you created the master page. Note that this is almost the same code you added to Default.aspx in Chapter 3, except for the <asp:ContentPlaceHolder> element and the <a> element within the Header <div>. The <a> element takes the user back to the homepage, and will be styled later. <form id="form1" runat="server"> <div id="PageWrapper"> <header><a href="/">Header Goes Here</a></header> <nav>Menu Goes Here</nav> <section id="MainContent"> <asp:ContentPlaceHolder ID="cpMainContent" runat="server"> </asp:ContentPlaceHolder> </section> <aside id="Sidebar">Sidebar Goes Here</aside> <footer>Footer Goes Here</footer> </div> </form> Make sure that you have the ContentPlaceHolder within the MainContent <section> tags. You can drag one from the Toolbox onto the page or enter the code directly, using IntelliSense’s help- ful hints. In both cases you should give the control an ID of cpMainContent. 4. Next, switch the master page into Design View and then drag Styles.css from the Styles folder in the Solution Explorer onto the master page. As soon as you drop the file, VS updates the Design View and shows the layout for the site that you created in Chapter 3. If the design doesn’t change, switch to Markup View and ensure there’s a <link> tag in the head of the page pointing to your CSS file: <asp:ContentPlaceHolder ID="head" runat="server"> </asp:ContentPlaceHolder> <link href="../Styles/Styles.css" rel="stylesheet" type="text/css" /> </head> The page should now look like Figure 6-2 in Design View. FIGURE 6-2 c06.indd 211c06.indd 211 10/8/2012 9:54:23 AM10/8/2012 9:54:23 AM
    • 212 x CHAPTER 6 CREATING CONSISTENT LOOKING WEBSITES Note the area with the purple border around it between the menu and the footer region in your Design View. This is the ContentPlaceHolder control that is used by the content pages. You see how to use it in the next exercise. 5. Drag the file modernizr-2.6.2.js from the Scripts folder into the <head> section of the Master Page below the CSS file. Then manually replace the two leading periods with a slash, like this: <script src="/Scripts/modernizr-2.6.2.js"></script> 6. You can save and close the master page because you’re done with it for now. How It Works Within VS, master pages behave like normal pages. You can add HTML and server controls to them, and you can manage the page both in Markup and Design View. The big difference is, of course, that a master page isn’t a true page itself; it only serves as a template for other pages in your site. In the next section you see how to use this master page as the template for a content page. Creating Content Pages A master page is useless without a content page that uses it. Generally, you’ll have only a few master pages, whereas you can have many content pages in your site. To base a content page on a master page, check the Select Master Page option at the bottom right of the Add New Item dialog box when you add a new Web Form to your site. Alternatively, you can set the MasterPageFile attribute on the page directly in the Markup View of the page. You saw this @ Page directive earlier in this chapter when master and content pages were introduced. Content pages can only directly contain Content controls that each map to a ContentPlaceHolder control in the master page. These content controls in turn can contain standard markup like HTML and server control declarations. Because the entire markup in a content page needs to be wrapped by <asp:Content> tags, it’s not easy to turn an existing ASPX page into a content page. Usually the easiest thing to do is copy the content you want to keep to the clipboard, delete the old page, and then add a new page based on the master page to the website. Once the page is added, you can paste the markup within the <asp:Content> tags. You see how this works in the following exercise. TRY IT OUT Adding a Content Page In this Try It Out you see how to add a content page to the site that is based on the master page you cre- ated earlier. Once the page is added, you add content to the <asp:Content> regions. 1. In previous exercises you added standard ASPX pages to your project, which should now be “upgraded” to make use of the new master page. If you want to keep the welcome text you added to Default.aspx earlier, copy all the HTML between the MainContent <section> tags to the clipboard (that is, the <h1> and the two <p> elements that you created earlier) and then delete the Default.aspx page from the Solution Explorer. Next, right-click the website in the Solution Explorer and choose Add Í Add New Item. Select the correct programming language, click Web c06.indd 212c06.indd 212 10/8/2012 9:54:23 AM10/8/2012 9:54:23 AM
    • Consistent Page Layout with Master Pages x 213 Form, name the page Default.aspx, and then, at the bottom of the dialog box, select the check boxes for Place Code in Separate File and Select Master Page, as shown in Figure 6-3. FIGURE 6-3 Finally, click the Add button. 2. In the Select a Master Page dialog box (see Figure 6-4), click the MasterPages folder in the left- hand pane, and then in the area at the right, click Frontend.master. FIGURE 6-4 Click OK to add the page to your website. c06.indd 213c06.indd 213 10/8/2012 9:54:24 AM10/8/2012 9:54:24 AM
    • 214 x CHAPTER 6 CREATING CONSISTENT LOOKING WEBSITES Instead of getting a full page with HTML as you got with standard ASPX pages, you now only get two <asp:Content> placeholders as shown in this VB.NET example: <%@ Page Title="" Language="VB" MasterPageFile="~/MasterPages/Frontend.master" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="cpMainContent" runat="Server"> </asp:Content> 3. Switch to Design View and note that everything is grayed out and read-only, except for the <asp:Content> region for cpMainContent. Figure 6-5 shows you how the page should look. FIGURE 6-5 Also note that VS conveniently lists the master page that this page is based on in the top-right cor- ner of Design View, visible in Figure 6-5. Clicking the name opens the master page in the editor. 4. If you still have the old markup from the Default.aspx on the clipboard, click once inside the cpMainContent placeholder and press Ctrl+V. (Note: you can do this both in Design View and in Markup View). This adds the markup to the page, right between the <asp:Content> tags. 5. Save your changes by pressing Ctrl+S and press Ctrl+F5 to open the page in your browser. The browser should display the page very closely to what you saw in Design View (see Figure 6-5). 6. Now take a look at the HTML for the page in the browser. You can do this by right-clicking the page and choosing View Source or View Page Source. Note that the source of the final page in the browser is a combination of the source of the master page and the content page: <div id="PageWrapper"> <header><a href="/">Header Goes Here</a></header> <nav>Menu Goes Here</nav> <section id="MainContent"> <h1>Hi there visitor and welcome to Planet Wrox</h1> <p class="Introduction"> We&#39;re glad you&#39;re paying a visit to <a href="http://www.PlanetWrox.com"> www.PlanetWrox.com</a>, the coolest music community site on the Internet. </p> ... The first four lines come from the master page and the bolded lines of HTML code come from the content page. c06.indd 214c06.indd 214 10/8/2012 9:54:24 AM10/8/2012 9:54:24 AM
    • Consistent Page Layout with Master Pages x 215 7. Switch back to VS and create a new page called Login.aspx in the root of the site based on the master page. Notice how VS remembered your last settings with regard to the master page and Code Behind (make sure both are checked in case you unchecked them earlier). Switch to Markup View and create an <h1> element inside the cpMainContent placeholder with the text Log in to Planet Wrox. There’s no need to add any other controls to this page just yet, but it serves as the basis for the login functionality you create in Chapter 16. Without any content in the MainContent element, the Sidebar will be moved to the left of the page. 8. Go back to Default.aspx and switch to Design View. Beneath the welcome text with the header and two <p> elements, create a new paragraph (press Enter in Design View) and type some text (for example, You can log in here). Notice how this new paragraph has a class attribute called Introduction because VS applies the previous class to new paragraphs automatically. Remove this class using the Clear Styles option of the Apply Styles window, or manually remove it from the code in Markup View. 9. Highlight the words “log in” in Design View and choose Format Í Convert to Hyperlink from the main menu. In the dialog box that follows, click the Browse button and select the Login.aspx page that you just created. Click OK twice. 10. Save all changes and press Ctrl+F5 again to view Default.aspx in the browser. Then click the link you created in the preceding step. You should now be taken to Login.aspx. Note that the general layout, like the header and the sidebar, is maintained. The only thing that changes when you go from page to page is the content in the main content area. How It Works When a page based on a master page is requested in the browser, the server reads in both the con- tent page and the master page, merges the two, processes them, and then sends the final result to the browser. In step 6 of this exercise you saw that the HTML in the browser for the requested page con- tained the markup from both files. Master pages will save you a lot of work when it comes to updating or radically changing the looks of your site. Because the entire design and layout of your site is defined in the master page, you only need to touch that single file when you want to make any changes. All content pages will pick up the changes automatically. A Closer Look at Master Pages So far you’ve seen a master page with a content placeholder for the main content. But if you look at the master page in Markup View, you’ll find another content placeholder in the head section of the page: <head runat="server"> <title></title> <asp:ContentPlaceHolder id="head" runat="server"> </asp:ContentPlaceHolder> ... </head> This placeholder is added for you automatically to each new master page you create. You can use it in content pages to add page-specific content that belongs between the <head> tags of a page, such c06.indd 215c06.indd 215 10/8/2012 9:54:24 AM10/8/2012 9:54:24 AM
    • 216 x CHAPTER 6 CREATING CONSISTENT LOOKING WEBSITES as CSS (both embedded and external style sheets) and JavaScript. You learn more about JavaScript in Chapters 10 and 11. You need to add content to this placeholder in Markup View, because it’s not visible in Design View. The ContentPlaceHolder called cpMainContent in the master page currently does not contain any markup itself. However, it doesn’t have to be like this. You can easily add your own content there that will serve as the default in your content pages as long as it’s not overridden by the content page. For example, you can have the following ContentPlaceHolder in a master page: <asp:ContentPlaceHolder ID="cpMainContent" runat="server"> This is default text that shows up in content pages that don't explicitly override it. </asp:ContentPlaceHolder> When you base a new page on this master page, you won’t see this default at first in Markup View. However, you can open the Content control’s Smart Tasks panel, shown in Figure 6-6, and choose Default to Master’s Content. FIGURE 6-6 When you click Yes when asked if you want to default to the master page content, VS removes the entire Content control from the Markup View of the page. However, when you request the page in the browser you will still see the default content from the master page. In Design View, the con- tent is still visible, now presented as a read-only area on the design surface. A master page with default content can be useful if you add a new ContentPlaceHolder to the master page at a later stage. Existing pages can simply display the default content, without the need for you to touch all these pages. New pages can define their own content. If you don’t have default content in the ContentPlaceHolder control in the master page and the content page doesn’t have a Content con- trol for the ContentPlaceHolder, no output is sent to the browser. Once you have defaulted to the master page’s content, you can create custom content again by open- ing the Smart Tasks panel and choosing Create Custom Content. This copies the default contents into a new Content control that you can then modify. Nesting Master Pages It is also possible to nest master pages. A nested master page is a master that is based on another master page. Content pages can then be based on the nested master page. This is useful if you have a website that targets different areas that still need to share a common look and feel. For example, you can have a corporate website that is separated by departments. The outer master page defines the global look and feel of the site, including corporate logo and other branding elements. You can c06.indd 216c06.indd 216 10/8/2012 9:54:24 AM10/8/2012 9:54:24 AM
    • Consistent Page Layout with Master Pages x 217 then have different nested master pages for different departments. For example, the sales depart- ment’s section could be based on a different master than the marketing department’s, enabling each to add their own identity to their section of the site. VS 2012 has excellent Design View support for nested master pages, giving you a good look at how the final page will end up. Creating a nested master page is easy: check the Select Master Page check box when you add a master page just as you do when you add a normal content page to the site. Then add markup and ContentPlaceHolder controls to the Content controls at locations that you want to override in the content pages. Finally, you choose your nested master page as the master for new content pages you create. Inside the content page, you only see the ContentPlaceHolder controls from the nested mas- ter page, not from its parent. Master Page Caveats Although master pages are great and can save you a lot of work, you need to be aware of some caveats. For starters, the ASP.NET run time changes the client ID of your controls in the page. This is the id attribute that is used in client script to access controls from JavaScript in the browser and with CSS ID selectors. With normal ASPX pages, the server-side ID of a control is usually inserted one-on-one in the final HTML. For example, a Button control with a server-side ID of Button1 in a normal ASPX page defined with this code, <asp:Button ID="Button1" runat="server" Text="Click Me" /> ends up with a client-side ID like this in the final HTML: <input type="submit" name="Button1" value="Click Me" id="Button1" /> However, the same button inside an <asp:Content> control ends up like this: <input type="submit" name="ctl00$cpMainContent$Button1" value="Click Me" id="cpMainContent_Button1" /> The name attribute has been prefixed with the auto-generated ID of the master page (ctl00) and both the name and the id attributes contain the ID of the ContentPlaceHolder control (cpMainContent). This means that any client-side code that previously referred to Button1 should now refer to cpMainContent_Button1. Note that this is not just a master page problem. You’ll also run into this behavior in other situa- tions; for example, when working with user controls (discussed in Chapter 8) and data-bound con- trols (discussed in Chapter 13 and onward). The second caveat is related to the first. Because the name and id of the HTML elements are changed, they add considerably to the size of the page. This may not be problematic for a single con- trol, but once you have pages with lots of controls, this could impact the performance of your site. The problem gets worse with nested master pages, where both content controls are appended to the ID. The same button inside a nested master page can end up like this: <input type="submit" name="ctl00$ctl00$cpMainContent$ContentPlaceHolder1$Button1" value="Click Me" id="cpMainContent_ContentPlaceHolder1_Button1" /> c06.indd 217c06.indd 217 10/8/2012 9:54:24 AM10/8/2012 9:54:24 AM
    • 218 x CHAPTER 6 CREATING CONSISTENT LOOKING WEBSITES To mitigate the problem, you should keep the IDs of your ContentPlaceHolder and Content con- trols as short as possible. To improve readability, this book uses longer names, like cpMainContent. However, in your own sites, you could reduce this to MC or cpMC to save some bandwidth on every request. NOTE ASP.NET 4 introduced a new feature called ClientIDMode that helps minimize the problems typically associated with changing client-side IDs. You learn more about this feature in Chapter 8. Master pages enable you to define the general look and feel of your site in a single location, thus improving the consistency and maintainability of your site. However, there is another way to improve consistency: centralize the behavior of the pages in your website. You can do this with a so- called base page, which is discussed next. USING A CENTRALIZED BASE PAGE In Chapter 5 you learned that, by default, all ASPX pages derive from a class called System.Web .UI.Page. This means all of your pages have at least the behavior defined in this class. However, in some circumstances this behavior is not enough and you need to add your own stuff to the mix. For example, you may have the need to add some behav- ior that applies to all the pages in your site. Instead of adding this behavior to each and every individual page, you can create a common base page. All the pages in your site can then inherit from this intermediate page instead of from the standard Page class. The left half of Figure 6-7 shows how an ASPX page called MyWebPage inherits from the Page class directly. The right half shows a situ- ation where the ASPX page inherits from a class called BasePage, which in turn inherits from Page. To have your pages inherit from this base page, you need to do two things: ‰ Create a class that inherits from System.Web.UI.Page in the App_Code folder of your website. ‰ Make the web pages in your site inherit from this base page instead of the standard Page class. In an upcoming exercise you create a new base page class inside the App_Code folder. For now, the sole purpose of this class is to check the Title of the page at run time to stop pages with an FIGURE 6-7 c06.indd 218c06.indd 218 10/8/2012 9:54:24 AM10/8/2012 9:54:24 AM
    • Using a Centralized Base Page x 219 empty title or a meaningless title like “Untitled Page” making it to the browser. Giving your pages a unique and helpful title helps the major search engines to index them, so it’s recommended to always include a title in your web pages. Checking the title programmatically is relatively easy to do, which enables you to focus on the concept of inheritance rather than on the actual code. In the section that discusses themes later in this chapter, you modify the base page once more, this time to retrieve the user’s preference for a theme. NOTE Older versions of VS used “Untitled Page” as the default title for new Web Forms. However, starting with the Service Pack 1 release of Visual Studio 2008, the default title is an empty string. I decided to leave the check for “Untitled Page” in the base page so you can see how you can check for unwanted titles. Before you can implement the base class, you need to know more about the ASP.NET page life cycle, an important concept that describes the process a web page goes through when requested by a browser. An Introduction to the ASP.NET Page Life Cycle When you think about how a page is served by a web server to the browser and think of this process as the life cycle of a page, you can probably come up with a few important moments in the page’s life. For example, the initial request by the browser is the starting point for the page’s “life.” Similarly, when the page has sent its entire HTML to the browser, its life may seem to end. However, more interesting events are going on in the page’s life cycle. The following table describes eight broad phases the page goes through. Within each phase, at least one event is raised that enables a page developer to hook into the page’s life cycle and perform actions at the right moment. You see an example of this in the next exercise. PHASE DESCRIPTION Page request A request to an ASPX page starts the life cycle of that page. When the web server is able and allowed to return a cached copy of the page, the entire life cycle is not executed. In all other situations, the page enters the start phase. Start In this phase, the page gets access to properties like Request and Response that are used to interact with the page’s environment. In addition, during this phase the PreInit event is raised to signal that the page is about to go into the initialization phase. You use this event later to set the theme of a page. Page initialization During this phase, the controls you have set up in your page or added program- matically become available. Additionally, the Page class fires three events: Init, InitComplete, and PreLoad. continues c06.indd 219c06.indd 219 10/8/2012 9:54:25 AM10/8/2012 9:54:25 AM
    • 220 x CHAPTER 6 CREATING CONSISTENT LOOKING WEBSITES PHASE DESCRIPTION Load During this phase, the control properties are loaded from View State and Control State during a postback. For example, when you change the selected item in a DropDownList and then cause a postback, this is the moment where the correct item gets preselected in the drop-down list again, which you can then work with in your server-side code. Also, during this phase the page raises the Load event. Validation In the validation phase, the Validation controls used to validate user input are processed. You learn about validators in Chapter 9. Postback event handling During this phase, the controls in your page may raise their own events. For example, the DropDownList may raise a SelectedIndexChanged event when the user has chosen a different option in the list. Similarly, a TextBox may raise the TextChanged event when the user has changed the text before she posted back to the server. When all event processing is done, the page raises the LoadComplete event. Also during this phase the PreRender event is raised to signal that the page is about to render to the browser. Shortly after that, SaveStateComplete is raised to indicate that the page is done storing all the relevant data for the controls in View State. Rendering Rendering is the phase where the controls (and the page itself) output their HTML to the browser. Unload The unload phase is really a clean-up phase. This is the moment where the page and controls can release resources they were holding on to. During this phase, the Unload event is raised so you can handle any cleanup you may need to do. One thing that’s important to realize is that all these events fire at the server, not at the client. So, even if you change, say, the text of a text box at the client, the TextChanged event of the TextBox control will fire at the server after you have posted back the page. Now you may wonder why you need to know all of this. The biggest reason to have some under- standing of the page life cycle is that certain actions can be performed only at specific stages in the page life cycle. For example, dynamically changing the theme has to take place in PreInit, as you’ll see later. To really understand the ASP.NET page life cycle, you need to know a little more about controls, state, events, and so on. Therefore, you’ll revisit the page life cycle again in Chapter 15 where you get a good look at all the different events that fire, and in what order. In the next exercise, you use the PreRender event of the Page class to check the title. Because a developer could set the page’s title programmatically during many events, checking for a correct title should be done as late as possible in the page’s life cycle, which is why PreRender is the best event for this. (continued) c06.indd 220c06.indd 220 10/8/2012 9:54:25 AM10/8/2012 9:54:25 AM
    • Using a Centralized Base Page x 221 Implementing the Base Page Implementing a base page is pretty easy: all you need to do is add a class file to your App_Code folder, add some code to it, and you’re done. What’s often a bit more difficult is to make sure each page in your site inherits from this new base page instead of from the standard System.Web.UI .Page class. Unfortunately, there is no way to configure the application to do this for you automati- cally when using Code Behind, so you need to modify each page manually. Visual Studio makes it a little easier for you by enabling you to export a page template that already contains this code. In the next exercise you add a base page to the site and in a later exercise you see how to export a web form to a template so you can add files that use the base page in no time. TRY IT OUT Creating a Base Page 1. Right-click the App_Code folder in the Solution Explorer and choose Add Í Add New Item. Select Class in the Templates list and name the file BasePage. You could choose another name if you like but BasePage clearly describes the purpose of the class, making it easier to understand what it does. 2. Clear the contents of the file, and then add the following code: VB.NET Public Class BasePage Inherits System.Web.UI.Page Private Sub Page_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender If String.IsNullOrEmpty(Me.Title) OrElse Me.Title.Equals("Untitled Page", StringComparison.CurrentCultureIgnoreCase) Then Throw New Exception( "Page title cannot be ""Untitled Page"" or an empty string.") End If End Sub End Class C# using System; public class BasePage : System.Web.UI.Page { private void Page_PreRender(object sender, EventArgs e) { if (string.IsNullOrEmpty(this.Title) || this.Title.Equals("Untitled Page", StringComparison.CurrentCultureIgnoreCase)) { throw new Exception( "Page title cannot be "Untitled Page" or an empty string."); } c06.indd 221c06.indd 221 10/8/2012 9:54:25 AM10/8/2012 9:54:25 AM
    • 222 x CHAPTER 6 CREATING CONSISTENT LOOKING WEBSITES } public BasePage() { this.PreRender += Page_PreRender; } } 3. Save the file and close it, and then open the Login.aspx page that you created earlier. Open its Code Behind file and change the Inherits code (the colon [:] in C#) so the login page inherits from the BasePage class you created earlier: VB.NET Partial Class Login Inherits BasePage ... End Class C# public partial class Login : BasePage { ... } 4. Save the page and then request it in the browser by pressing Ctrl+F5. If you haven’t changed the title of the page earlier, you should be greeted by the error shown in Figure 6-8 in your browser. FIGURE 6-8 Instead of this error, you may see an error that displays the source for the BasePage class where the title is checked. 5. Go back to VS and open the login page in Markup View. Locate the Title attribute in the @ Page directive (or add one if it isn’t there) and set its value to Log in to Planet Wrox. The following snippet shows the VB.NET version of the @ Page directive but the C# version is almost identical: <%@ Page Title="Log in to Planet Wrox" Language="VB" MasterPageFile="~/MasterPages/Frontend.master" AutoEventWireup="false" CodeFile="Login.aspx.vb" Inherits="Login" %> c06.indd 222c06.indd 222 10/8/2012 9:54:25 AM10/8/2012 9:54:25 AM
    • Using a Centralized Base Page x 223 6. Repeat steps 3 and 5 for all the pages in your site. To make this a bit quicker, you can use Find and Replace to quickly replace all the occurrences of System.Web.UI.Page with BasePage. Make sure you don’t accidentally replace it in the BasePage file in the App_Code folder itself. To prevent this from happening, make sure you search only in Code Behind files, like this: ‰ Open the Replace in Files dialog box (press Ctrl+Shift+H or select Edit Í Find and Replace Í Replace in Files). ‰ In the Find What box, enter System.Web.UI.Page. In the Replace With text box, enter BasePage. ‰ Expand the Find Options section and in the Look at These File Types text box, enter *.aspx.vb or *.aspx.cs depending on the language you use. This leaves the BasePage file, which has a single extension of .vb or .cs, alone. ‰ Click Replace All and then click Yes to confirm the Replace operation. 7. Save the changes you made to any open page and then browse to Login.aspx again. If everything worked out as planned, the error should be gone and you now see the login page. Remember, though, that all other pages in your site now throw an error when you try to access them. The fix is easy; just give them all a valid Title. For pages without a Title attribute in their page directive, you need to do this manually. For other pages, with an empty Title="" attribute, you can quickly do this by searching the site for Title="" and replacing it with something like Title="Planet Wrox". (Don’t forget to reset Look at These File Types back to *.*). For pages other than the demo pages you’ve created so far, you’re better off giving each page a unique title, clearly describing the content it contains. How It Works By default, all pages in your website inherit from the Page class defined in the System.Web.UI namespace. This gives them the behavior required to make them act as web pages that can be requested by the browser and processed by the server. Because the inheritance model in .NET enables you to create a chain of classes that inherit from each other, you can easily insert your own base page class between a web page and the standard Page class. You do this by changing the Inherits statement (in VB) and the colon (in C#) to your new BasePage: VB.NET Partial Class Login Inherits BasePage C# public partial class Login : BasePage Inside this new BasePage class you add an event handler that is called when the class fires its PreRender event. As you learned earlier, this event is raised quite late in the page’s life cycle, when the entire page has been set up and is ready to be rendered to the client: VB.NET Private Sub Page_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender ' Implementation here c06.indd 223c06.indd 223 10/8/2012 9:54:25 AM10/8/2012 9:54:25 AM
    • 224 x CHAPTER 6 CREATING CONSISTENT LOOKING WEBSITES End Sub C# private void Page_PreRender(object sender, EventArgs e) { // Implementation here } Note that Visual Basic uses the Handles keyword to tell the compiler that the Page_PreRender method will be used to handle the event. In C#, you need to hook up this handler manually. A good place to do this is in the class’s constructor: public BasePage() { this.PreRender += Page_PreRender; } This highlighted line of code serves the same purpose as the Handles keyword in VB.NET: it tells the compiler what method to run when the page raises its PreRender event. Inside the event handler, the code checks the current page title. If the page title is still an empty string (the default for any new page you add to your web project) or Untitled Page it throws an exception. VB.NET If String.IsNullOrEmpty(Me.Title) OrElse Me.Title.Equals("Untitled Page", StringComparison.CurrentCultureIgnoreCase) Then Throw New Exception( "Page title cannot be ""Untitled Page"" or an empty string.") End If C# if (string.IsNullOrEmpty(this.Title) || this.Title.Equals("Untitled Page", StringComparison.CurrentCultureIgnoreCase)) { throw new Exception( "Page title cannot be "Untitled Page" or an empty string."); } This code uses the handy IsNullOrEmpty method of the String class to check if a value is null (Nothing in VB) or an empty string. It also uses the Equals method to check if the page title is equal to Untitled Page. It uses StringComparison.CurrentCultureIgnoreCase to do a case-insensitive com- parison, so untitled page or Untitled Page would both match. Notice how the keywords Me (in VB.NET) and this (in C#) are used. These keywords are context- sensitive and always refer to the instance of the class where they are used. In this example, Me and this refer to the current instance of the BasePage class. This BasePage instance has a Title property (which it inherits from Page) that can be checked for unwanted values. If it still contains the default title (an empty string) or the text “Untitled Page,” the code raises (or throws) an exception. This imme- diately stops execution of the page so you as a page developer can fix the problem by providing a valid title before the page ends up in public. In Chapter 18 you learn more about exceptions and how to pre- vent and handle them. c06.indd 224c06.indd 224 10/8/2012 9:54:26 AM10/8/2012 9:54:26 AM
    • Using a Centralized Base Page x 225 To display a double quote (") in the error message, both languages use a different format. In Visual Basic, you need to double the quotes. In C#, you need to prefix the double quote with a backslash () to escape the double quote. In both cases, a double quote character ends up in the error message. Because every new page you add to the site should now inherit from this new base page, you should create a page template that already has the correct code in its Code Behind and markup, making it easy to add the correct page to the site right from the start. This is discussed next. Creating Reusable Page Templates Visual Studio comes with a great tool to export templates for a number of different file types includ- ing ASPX pages, class files, and even CSS files. By creating a custom template, you define the code or markup that you need in every file once and then create new files based on this template, giving you a jump start with the file and minimizing the code you need to type. The next exercise shows you how to create your own templates. TRY IT OUT Creating a Reusable Page Template In this exercise you see how to create a template file for all new ASPX pages you add to your site. To avoid conflicts with existing pages in your current site, you create a new temporary page and use that for the template. Afterward, you can delete the temporary file. 1. Add a new Web Form to the root of the site and call it Temporary.aspx. Make sure it uses Code Behind, uses your programming language, and is based on the master page in the MasterPages folder. 2. Open the Code Behind of this new page (by pressing F7) and change the Inherits line (the colon in C#) so the page inherits from BasePage instead of from System.Web.UI.Page. Also rename the class from Temporary to $relurlnamespace$_$safeitemname$: VB.NET Partial Class $relurlnamespace$_$safeitemname$ Inherits BasePage ... End Class C# public partial class $relurlnamespace$_$safeitemname$ : BasePage { ... } Make sure you don’t remove any of the existing code, like the using statements or the Page_Load method in the C# version. Don’t worry about any compile errors you may get about unexpected characters like $. Once you start adding pages based on this template, $relurlnamespace$_$safeitemname$ will be replaced by the name of the page you’re adding. c06.indd 225c06.indd 225 10/8/2012 9:54:26 AM10/8/2012 9:54:26 AM
    • 226 x CHAPTER 6 CREATING CONSISTENT LOOKING WEBSITES 3. Switch to Markup View, and change the Inherits attribute from Temporary to $relurlnamespa ce$_$safeitemname$ as shown in this C# example: <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPages/Frontend.master" AutoEventWireup="true" CodeFile="Temporary.aspx.cs" Inherits="$relurlnamespace$_$safeitemname$" %> You must leave the CodeFile attribute alone; VS will change it to the right Code Behind file auto- matically whenever you add a new page to the site. 4. Optionally, add other code you want to add to your pages by default, like a comment block with a copyright notice. 5. Save all changes and then choose File Í Export Template. In the dialog box that follows, select Item Template and choose your programming language from the drop-down list at the bottom of the screen, shown in Figure 6-9. FIGURE 6-9 6. Click Next and place a check mark in front of Temporary.aspx, which you find near the bottom of the list. Click Next again to go to the Select Item References dialog box. 7. There is no need to set anything in the Select Item References dialog box now. If you had a web page referencing specific assemblies (.dll files) you could pick them here, so VS adds the references for you automatically next time you add a file based on this template. Click Next again to go to the Select Template Options screen. Type MyBasePage as the new template name, and optionally c06.indd 226c06.indd 226 10/8/2012 9:54:26 AM10/8/2012 9:54:26 AM
    • Using a Centralized Base Page x 227 type a short note describing the purpose of the template. Make sure the Automatically Import the Template into Visual Studio option is checked. Figure 6-10 shows the final dialog box. FIGURE 6-10 8. Click Finish to create the template. VS opens a File Explorer (Windows Explorer in Windows 7) showing a copy of the new template as a zip file. You can close that window, because you don’t need it. If you want to carry out this exercise for both VB.NET and C#, be sure to rename the resulting zip file first before you make an export for the second language; otherwise the zip file gets over- written. To rename the file, open File Explorer, go to your Documents folder and then browse to Visual Studio 2012TemplatesItemTemplates. You’ll find a file called MyBasePage.zip, which you can rename to something like MyBasePageCS.zip. Note that the file’s location is differ- ent from the one you see in Figure 6-10; the output location contains just a copy of the exported template that you can use as a backup. 9. Back in VS, delete the temporary file Temporary.aspx you created. Then right-click the website in the Solution Explorer and choose Add Í Add New Item. Note that your custom template now shows up in the list of templates, shown in Figure 6-11. If you click it, VS shows you the descrip- tion you gave it earlier. Note: you may have to restart VS and reopen your website for the template to appear. 10. Type a new name for the page, such as TestPage.aspx, and click Add to add it to your site. Look at the markup and the Code Behind of the file and verify that $relurlnamespace$_$safeitemn c06.indd 227c06.indd 227 10/8/2012 9:54:26 AM10/8/2012 9:54:26 AM
    • 228 x CHAPTER 6 CREATING CONSISTENT LOOKING WEBSITES ame$ has been renamed to _TestPage to reflect the new name of the page. If everything looks OK, you can delete TestPage.aspx because it’s not used in the Planet Wrox website. FIGURE 6-11 How It Works When you export the template, Visual Studio creates a zip file with the necessary files—an ASPX file and a Code Behind file in this exercise. This zip file is then stored in the ItemTemplates subfolder of the Visual Studio 2012 folder under your Documents folder. Some of the files in the zip file con- tain the placeholders $relurlnamespace$ and $safeitemname$. When you add a new file to the site that is based on your template using the Add New Item dialog box, VS replaces $relurlnamespace$ with the name of the folder (nothing, in the case of a file added to the root of the site) and $safeitem- name$ with the actual name of the page. In this exercise, you typed TestPage.aspx as the new name for the page, so you ended up with a class in the Code Behind called _TestPage, which in turn inherits from the global BasePage. The underscore (_) is hard-coded between the two placeholders and is really only needed when adding a Web Form based on this template to a subfolder. However, it’s a valid start of a class identifier so you can safely leave it in for pages at the root of your website. If you add a file to a subfolder, such as the Demos folder, the class name is prefixed with the name of the folder so you end up with a class called Demos_TestPage. In addition to $relurlnamespace$ and $safeitemname$, you can use a few other placeholders. Search the MSDN site at http://msdn.microsoft.com for the term $safeitemname$ to find the other template parameters. If you need to make a change to the exported template, either redo the entire export process, or manu- ally edit the files in the zip file. c06.indd 228c06.indd 228 10/8/2012 9:54:26 AM10/8/2012 9:54:26 AM
    • Themes x 229 With this exported template you now have a very quick way to add pages to your site that inherit from the BasePage class. You don’t need to manually change the Code Behind of the class file or the markup of the page anymore. In addition to master pages and the central BasePage class, you have more options to create consis- tent-looking websites. One of them is themes. THEMES So far you’ve seen how to create a master page to define the global look and feel of the pages in your site. You also saw how to cen- tralize the behavior of your pages by using a central base page. However, you have more ways to influence the look and feel of your site: themes and skins. Skins are dealt with later in the chapter because they are an optional part of themes, which need to be dis- cussed first. A theme is a collection of files that defines the look of a page. A theme typically includes skin files, CSS files, and images. You define themes in the special App_Themes folder in the root of your website. Within this folder you create one or more subfolders that define the actual themes. Inside each subfolder, you can have a number of files that make up the theme. Figure 6-12 shows the Solution Explorer for a website that defines two themes: Monochrome and DarkGrey. A link to each CSS file in the theme folder is added to your page’s <head> section automatically whenever the theme is active. You see how this works later. The images in the theme folder can be referenced from the CSS files. You can use them to change c