1. Trang chủ
  2. » Công Nghệ Thông Tin

ASP.NET 4.0 in Practice phần 1 ppsx

51 1K 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề ASP.NET 4.0 in Practice
Tác giả Daniele Bochicchio, Stefano Mostarda, Marco De Sanctis
Trường học Manning Publications Co.
Chuyên ngành Computer Science/Software Development
Thể loại sách hướng dẫn thực hành
Năm xuất bản 2011
Thành phố Shelter Island
Định dạng
Số trang 51
Dung lượng 15,35 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

contentspreface xv acknowledgments xvii about this book xix about the authors xxiii about the cover illustration xxv TECHNIQUE 1 Handling PostBack 20 TECHNIQUE 2 Form validation 23 TECH

Trang 2

ASP.NET 4.0 in Practice

Trang 4

ASP.NET 4.0 in Practice

DANIELE BOCHICCHIO STEFANO MOSTARDA MARCO DE SANCTIS

M A N N I N GShelter Island

Trang 5

For online information and ordering of this and other Manning books, please visit

www.manning.com The publisher offers discounts on this book when ordered in quantity For more information, please contact

Special Sales Department

Manning Publications Co

20 Baldwin Road

PO Box 261

Shelter Island, NY 11964

Email: orders@manning.com

©2011 by Manning Publications Co All rights reserved

No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in the book, and Manning

Publications was aware of a trademark claim, the designations have been printed in initial caps

or all caps

Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine

Manning Publications Co Development editor: Cynthia Kane

20 Baldwin Road Copyeditor: Joan Celmer

Shelter Island, NY 11964 Cover designer: Marija Tudor

ISBN 9781935182467

Trang 6

brief contents

PART 1 ASP.NET FUNDAMENTALS 1

PART 2 ASP.NET WEB FORMS 75

Trang 7

BRIEF CONTENTS

vi

PART 5 ADVANCED TOPICS 317

Trang 8

contentspreface xv

acknowledgments xvii about this book xix about the authors xxiii about the cover illustration xxv

TECHNIQUE 1 Handling PostBack 20

TECHNIQUE 2 Form validation 23

TECHNIQUE 3 Page header, styling, and CSS 26

Trang 9

TECHNIQUE 4 Creating a model using Entity

Framework 38

TECHNIQUE 5 Generating POCO code 41

TECHNIQUE 6 Reading data using Entity Framework 43

TECHNIQUE 7 Writing data using Entity Framework 48

TECHNIQUE 8 First approach: one context per method 53

TECHNIQUE 9 A better approach: one context per ASP.NET

request 55

TECHNIQUE 10 Instantiating the context using modules 58

TECHNIQUE 11 Persisting entity modifications 60

TECHNIQUE 12 Persisting only selected properties 61

TECHNIQUE 13 Persisting an entity using ViewState 65

TECHNIQUE 14 Keep concurrency in mind 66

TECHNIQUE 15 Optimizing fetching 69

TECHNIQUE 16 Avoiding multiple query execution 70

TECHNIQUE 17 Optimizing queries that retrieve a single

element 71

TECHNIQUE 18 Disabling change tracking 73

TECHNIQUE 19 Better markup generation in ASP.NET 4.0 81

TECHNIQUE 20 Controlling ClientID generation 83

T 21 Using nested master pages 86

Trang 10

TECHNIQUE 23 URL routing with Web Forms 93

TECHNIQUE 24 Advanced URL routing scenarios 97

TECHNIQUE 25 Rewriting in practice: UrlRewriting.NET 101

TECHNIQUE 26 How to display data using Repeater 106

TECHNIQUE 27 ListView in ASP.NET 4.0 109

TECHNIQUE 28 Using data source controls 111

TECHNIQUE 29 EntityDataSource and Entity Framework 114

TECHNIQUE 30 What’s new in GridView, FormView, and

ListView 115

TECHNIQUE 31 The QueryExtender control 118

TECHNIQUE 32 The first application 123

TECHNIQUE 33 Working with metadata and templates 127

TECHNIQUE 34 Extending Dynamic Data 131

TECHNIQUE 35 Simple controls 136

TECHNIQUE 36 Composite controls 139

TECHNIQUE 37 Handling PostBack 144

TECHNIQUE 38 Container controls 147

TECHNIQUE 39 Templated controls 149

TECHNIQUE 40 Data binding in custom controls 153

TECHNIQUE 41 Control builders 156

TECHNIQUE 42 Add OptionGroups to DropDownList 164

TECHNIQUE 43 Build a table-less control adapter for the

DataList 170

Trang 11

TECHNIQUE 44 Building a custom browser capabilities

TECHNIQUE 46 The model 191

TECHNIQUE 47 The controller 194

TECHNIQUE 48 The view 197

TECHNIQUE 49 Partitioning using Areas 204

TECHNIQUE 50 Handling user input at the controller

level 207

TECHNIQUE 51 Validating posted data 212

TECHNIQUE 52 Building customized data templates 221

TECHNIQUE 53 Componentized markup through HTML

helpers 226

TECHNIQUE 54 Inject logic using action filters 229

TECHNIQUE 55 Custom model binders for domain

entities 236

TECHNIQUE 56 Building a new model binder from

scratch 243

TECHNIQUE 57 Routes with consistent URL termination 249

Trang 12

P ART 4 S ECURITY 257

TECHNIQUE 58 Handling improper parameter values 263

TECHNIQUE 59 Monitoring and blocking bad requests 264

TECHNIQUE 60 Handling SQL queries using parameters 267

TECHNIQUE 61 Dynamic queries with multiple values 269

TECHNIQUE 62 Handling and displaying user input 271

TECHNIQUE 63 Using Microsoft’s Anti-XSS Library 275

TECHNIQUE 64 Dynamically building a path 278

TECHNIQUE 65 Using FormsAuthentication and

TECHNIQUE 67 Implementing a role-enabled login using Roles

API 294

TECHNIQUE 68 Other providers 298

TECHNIQUE 69 Building custom Membership and Role

providers 300

TECHNIQUE 70 Integrating Windows Live ID with your

application 309

Trang 13

P ART 5 A DVANCED TOPICS 317

TECHNIQUE 71 Creating a classic page 323

TECHNIQUE 72 Ajaxize a page using the update

TECHNIQUE 75 Intercepting client-side pipeline 328

TECHNIQUE 76 Invoking REST web services with

TECHNIQUE 80 Per-request state 349

TECHNIQUE 81 Per-session state 351

TECHNIQUE 82 Using the Profile API 355

TECHNIQUE 83 A custom provider for the Profile API 359

Trang 14

TECHNIQUE 85 Deterministically removing items from

OutputCache 372

TECHNIQUE 86 OutputCache and partial views 378

TECHNIQUE 87 Implementing data caching in

ASP.NET 381

TECHNIQUE 88 Custom cache provider 388

TECHNIQUE 89 Custom OutputCache provider 393

TECHNIQUE 92 Intercepting, and handling errors with a custom

module 403

TECHNIQUE 93 Running your site from the database 407

TECHNIQUE 94 Building a request filter to minify HTML 417

TECHNIQUE 95 Building an HTTPHandler to minify CSS 422

TECHNIQUE 96 Building an HTTPHandler to minify

JavaScript 425

TECHNIQUE 97 Increasing performance with

multithreading 427

TECHNIQUE 98 Using ParallelFX 435

TECHNIQUE 99 Tips for your web.config 438

Trang 15

appendix A ASP.NET and IIS 7.x 441

TECHNIQUE 100 Modifying IIS behavior with managed

modules 443

TECHNIQUE 101 Configuring application warm-up in IIS 7.5 445

appendix B Data access fundamentals 448

TECHNIQUE 102 UsiQuerying the database using ADO.NET 449

TECHNIQUE 103 Using stored procedures to query the

Trang 16

preface

This has been a very long journey We found that writing this book was a challenging task, a much harder one than we had anticipated, but there were also moments of joy and discovery along the way! The idea for the book first came to us 18 months ago, and many days and nights have come and gone between the first sentence we wrote and the final book you hold today

This is not our first book—it is the ninth book for Daniele, the seventh for Stefano, and the fourth for Marco—but it is the most complex one we’ve attempted because of the Techniques format we implement in the book In addition, we were coauthoring

another book for Manning Publications, Entity Framework 4 in Action, at roughly the

same time

Our aim in writing this book was not to create a typical reference book: there are plenty of those around We felt that because ASP.NET has now reached a high level of maturity, the time was ripe for a book of best practices, and that is what we set out to

do Instead of focusing on how a class is implemented or what members offer, this book shows you how to get tasks done, the right way

If your days (and nights) are spent on implementing web applications, you know that the best way to learn is from experience This book contains all the tips we have learned in more than 10 years of working with ASP.NET Everything in this book comes from our own day-by-day experience working as consultants as well from ASP.NET com-munity members We learned a lot from other people’s problems, and we are happy to now share the solutions and best practices with you

Trang 17

In this book you will find everything you need to build your web applications using

a Problem/Solution/Discussion approach Each scenario is motivated, then resolved, and finally discussed and explained

This is a book that we felt was missing from the market We hope we have filled that need successfully and we invite you to send us your feedback and let us know if we have been successful in attaining our goal

We hope that our efforts will help you in your daily work Enjoy the read, get your hands dirty, and have some fun!

Trang 18

acknowledgments

We can’t mention by name all the individuals who made contributions to this book, adding to its value in ways both large and small All of them deserve our sincere thanks, but here we will mention only a few whose help was invaluable to us during the writing process

Cynthia Kane—Cynthia is our development editor at Manning She was there for

us from the the beginning, providing support and guidance, and has proved a master

at transforming a bunch of words and images into an appealing book Thank you Scott Guthrie—Scott, also known as ScottGu, is the man behind a number of prod-ucts in the Microsoft Developer Division, including ASP.NET Scott was always willing to let us solve some of the problems that we encountered with a beta Thank you

The Developer Division at Microsoft—thanks to everyone for their help and for building such a great product

All the folks at ASPItalia.com, our “mother ship”—if we managed to collect enough scenarios for your problem-solving enjoyment, part of the credit has to go to the mem-bers of our community

Many individuals at Manning worked hard on this book to bring it to our readers

A big thank-you to Michael Stephens and Marjan Bace for believing in us, and to the production team of Mary Piergies, Joan Celmer, Susan Harkins, Gordan Salinovic, and Janet Vail for their efforts

Our peer reviewers deserve special mention Their suggestions and feedback were invaluable and made this a much better book We thank Alex Thissen, Dave Corun, Anil Radhakrishna, Philippe Vialatte, Nikander Bruggeman, Margriet Bruggeman,

Trang 19

Jason Jung, David Barkol, Perga Massimo, Braj Panda, Alessandro Gallo, Gary Bushey, Eric Swanson, Amos Bannister, and Andrew Siemer We would also like to thank the technical proofreader, Matteo Casati, for his outstanding job of reviewing the final manuscript during production

Last but not least, thank you, dear reader, for your trust in this book Our hope is that

it will help you in your day-to-day work and make you more productive with ASP.NET!

In addition to the people mentioned above, there are others who are important in Daniele’s, Stefano’s, and Marco’s private lives Even if they didn’t directly work on the book, they contributed in other important ways to keep the authors on track

Danielewould like to thank his wife Noemi for her support and patience and for giving him his beautiful sons, Alessio and Matteo A big thank-you to my parents for letting

me play with computers when I was a kid, and to my family in general for supporting

me A special thank-you to my coauthors for helping me on this journey: you guys rock! And thanks to Alessio, Marco, Cristian, Matteo, and Riccardo at ASPItalia.com for all their help and support

Stefanowants to thank his wife Sara for being supportive and extremely patient, and his family (yes, the book is finally finished!) Special thanks to my closest friends (in alphabetical order), Federico, Gabriele, Gianni, and Riccardo Of course, I can’t help mentioning Filippo, who already bought a copy of the book Finally, a big thank-you to William and Annalisa for their friendship and their support My last words are for Marco and Daniele: thanks guys!

Marcothanks Stefano and Daniele because it’s always a privilege when you have the chance to work with such smart and funny guys I would also like to thank the whole ASPItalia.com team: I’m so proud to be a part of it Special thanks to my family, and to Barbara, for their support and for the patience they’ve shown me You have all my love

Trang 20

about this book

ASP.NET is a Microsoft technology for building web applications that leverages all the fantastic technologies you can find in NET Framework

The book will move you from apprentice to master of ASP.NET by giving you cific techniques to solve problems you are likely to encounter Each technique has a problem, solution, and discussion section You might think of this book as a guided tour through ASP.NET best practices; we’ll introduce each scenario, solve the problem, and then discuss the results Once you’ve read this book, you’ll have a better under-standing of the most important aspects of designing, building, and maintaining ASP.NET-based applications

You’re going to find many devices in this book that will help you in the learning process:

■ Figures—Pictures that show a workflow or summarize concepts

■ Listings and snippets—Pieces of code that show the solution to a problem

■ Tables—Visuals that summarize a list of features or options

We hope these devices will help make concepts clearer and the learning process faster

Who should read this book?

This book targets developers who are working on everything from the smallest home application to the largest enterprise application ASP.NET can be useful in simple sce-narios, where you can apply most of the RAD features provided by Visual Studio 2010,

Trang 21

ABOUT THIS BOOK

Part 1: ASP.NET fundamentals

In part 1, we introduce ASP.NET fundamentals For those of you who are already what familiar with ASP.NET, this part serves as a refresher before moving forward Chapter 1 provides an introduction to ASP.NET, with a focus on the Web Form’s model

Chapters 2 and 3 cover data access strategies in web applications You’ll learn the best practices for data access and how to leverage them in your application

Part 2: ASP.NET Web Forms

Part 2 covers how to use ASP.NET Web Forms, the original model provided in ASP.NET

to build the user interface

Chapter 4 takes a tour into ASP.NET Web Forms, covering the most common narios You’ll also learn about the new features offered by version 4.0, how to use mas-ter pages to their fullest extent, and how to leverage URL routing

Chapter 5 deals with one of the most common activities for a developer: using data binding and how to fully integrate this feature into your applications

Chapter 6 covers an important extensibility point in ASP.NET Web Forms and shows how to build custom controls You’ll start with the basics and analyze complex scenarios Finally, chapter 7 explains how to control the markup generated by ASP.NET You’ll learn how to produce better markup and how adaptive rendering works

Chapter 8 contains an introduction to ASP.NETMVC and shows the potential that this new toolkit offers when you’re building the UI You’ll learn how to perform the basic actions that you’re already acquainted with in ASP.NET Web Forms

Chapter 9 covers how to customize and extend ASP.NETMVC in order to unlock the full potential that it offers

Trang 22

ABOUT THIS BOOK xxi

Part 5: Advanced topics

Finally, part 5 is dedicated to more advanced scenarios and combines many of the ics previously addressed in this book These chapters cover both ASP.NET Web Forms and MVC

Chapter 12 covers how to integrate an ASP.NET application into an Ajax-enabled application and RIAs (Rich Internet Applications) We’ll also take a look at how to leverage jQuery and ASP.NET Ajax

In chapter 13, you’ll learn how to handle state in ASP.NET—from cookies, to ViewState, to new features introduced in version 4, like the ability to compress the SessionState

Chapter 14 is dedicated to caching You’ll find plenty of tips on how to achieve ter scalability by implementing a good caching strategy You’ll also learn how to build custom cache providers and how Microsoft AppFabric caching works

Chapter 15 contains miscellaneous topics related to fully extending ASP.NET, from HttpRuntime, to logging, to building a virtual path provider

Last, chapter 16 offers some tips on how to build applications that perform better, with topics like content minifying, multithreading, and ParallelFX

Code conventions and downloads

All the code used in this book is in a monospace font like this The NET code is in both C# and Visual Basic so that you’re comfortable with the code, regardless of the language you are using The language is indicated immediately above the relevant code For longer lines of code, a wrapping character might be used so the code is technically correct while conforming to the limitations of a printed page Code anno-tations accompany many of the listings, highlighting important concepts In some cases, numbered bullets link to explanations that follow the listing

Source code for all working examples in this book is available for download from the publisher’s website at www.manning.com/ASP.NET4.0inPractice

Trang 23

ABOUT THIS BOOK

xxii

Author Online

The purchase of ASP NET 4.0 in Practice includes free access to a private forum run by

Manning Publications where you can make comments about the book, ask technical questions, and receive help from the authors and other users You can access and sub-scribe to the forum at www.manning.com/ASP.NET4.0inPractice This page provides information on how to get on the forum after you’re registered, what kind of help is available, and the rules of conduct in the forum

Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the authors can take place It isn’t a commitment to any specific amount of participation on the part of the authors, whose contributions to the book’s forum remain voluntary (and unpaid) We suggest you try asking the authors some challenging questions, lest their interest stray! The Author Online forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print

In addition to the Author Online forum available on Manning’s website, you can also contact us regarding this book, or anything else, through one of the following avenues:

■ Book website—http://www.aspnetinpractice.com/

■ Daniele’s blog—http://blogs.5dlabs.it/daniele/

■ Stefano’s blog—http://blogs.5dlabs.it/stefano/

■ Marco’s blog—http://blogs.5dlabs.it/marcodes/

All comments sent to these blogs are moderated We post nearly all comments; but if you include your email address or phone number, we won’t post the comment out of respect for your privacy

Trang 24

about the authors

DANIELE BOCHICCHIOis the cofounder of 5DLabs.it, a consulting agency specializing in ASP.NET, Silverlight, Windows Phone 7, and NET Framework He has worked on a lot

of cool projects with many different technologies Daniele is a well-known speaker and author, and you can find him at the main developer-focused events worldwide He has also written several books, in both Italian and English He’s the coauthor of Manning’s

Entity Framework 4 in Action Daniele is the network manager of ASPItalia.com, the est Italian NET Framework community He currently lives in southern Italy with his family You can reach him via his personal website at www.bochicchio.com/ Daniele shares his thoughts in 140 characters or less at http://twitter.com/dbochicchio/

larg-STEFANO MOSTARDAis a Microsoft MVP in the Data Platform category He’s a software architect focused on web applications and the cofounder of 5DLabs.it, a consulting agency specialized in ASP.NET, Silverlight, Windows Phone 7, and NET Framework Stefano is a professional speaker at many important Italian conferences and a well-known author He has written many books for the Italian market and is the lead

author of Manning’s Entity Framework 4 in Action He’s also one of the leaders of the

ASPItalia.com Network and a content manager of the LINQItalia.com website cated to LINQ and Entity Framework In addition to visiting his blog, you can read his technical deliriums at http://twitter.com/sm15455/

dedi-MARCO DE SANCTIS is a Microsoft MVP who has been designing and developing prise applications in distributed scenarios for the last seven years He started develop-ing with ASP.NET when it was first released; since then, he’s improved his skills to

Trang 25

enter-ABOUT THE AUTHORS

xxiv

become an application architect Over the years, he has specialized in building uted services and has widened his knowledge to encompass technologies like Work-flow Foundation, Windows Communication Foundation, LINQ, and ADO.NET Entity Framework Today Marco is one of the members of 5DLabs.it and works as a senior software engineer for one of the biggest Italian companies in the IT market In his spare time, he’s a content manager at ASPItalia.com He shares his tweets at http:// twitter.com/crad77

Ngày đăng: 12/08/2014, 15:23