Top Banner
Professional ASP.NET 2.0 Server Control and Component Development Dr. Shahram Khosravi
30

Dr. Shahram Khosravi€¦ · Shahram Khosravi. Shahram Khosravi started working as a software engineer while still in college. After completing his Ph.D., he continued working on

Sep 20, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • Professional ASP.NET 2.0 Server Control and

    Component Development

    Dr. Shahram Khosravi

    01_793507 ffirs.qxp 7/10/06 5:21 PM Page iii

    File AttachmentC1.jpg

  • 01_793507 ffirs.qxp 7/10/06 5:21 PM Page ii

  • Professional ASP.NET 2.0 Server Control and

    Component Development

    01_793507 ffirs.qxp 7/10/06 5:21 PM Page i

  • 01_793507 ffirs.qxp 7/10/06 5:21 PM Page ii

  • Professional ASP.NET 2.0 Server Control and

    Component Development

    Dr. Shahram Khosravi

    01_793507 ffirs.qxp 7/10/06 5:21 PM Page iii

  • Professional ASP.NET 2.0 Server Control and ComponentDevelopmentPublished byWiley Publishing, Inc.

    10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com

    Copyright © 2006 by Wiley Publishing, Inc., Indianapolis, Indiana

    Published simultaneously in Canada

    ISBN-13: 978-0-471-79350-2ISBN-10: 0-471-79350-7

    Manufactured in the United States of America

    10 9 8 7 6 5 4 3 2 1

    1MA/RZ/QX/QW/IN

    Library of Congress Cataloging-in-Publication Data is available from the Publisher.

    No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or byany means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted underSections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of thePublisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Cen-ter, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher forpermission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indi-anapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions.

    LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NOREPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OFTHE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDINGWITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTYMAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE ANDSTRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK ISSOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERINGLEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE ISREQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT.NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HERE-FROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITA-TION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THEAUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITEMAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARETHAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEAREDBETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.

    For general information on our other products and services please contact our Customer Care Departmentwithin the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

    Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related tradedress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the UnitedStates and other countries, and may not be used without written permission. All other trademarks are theproperty of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendormentioned in this book.

    Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may notbe available in electronic books.

    01_793507 ffirs.qxp 7/10/06 5:21 PM Page iv

    www.wiley.com

  • About the Author

    Shahram KhosraviShahram Khosravi started working as a software engineer while still in college. After completing hisPh.D., he continued working on cutting-edge software development projects. Shahram is a senior soft-ware engineer, consultant, author, and instructor specializing in ASP.NET, Web services, .NET technologies,XML technologies, ADO.NET, C#, 3D computer graphics, Human Interface (HI) usability, and design pat-terns. He has more than 10 years of experience in object-oriented analysis, design, and programming.Shahram has written articles on the .NET Framework, ADO.NET, ASP.NET, and XML technologies forindustry leading magazines such as Dr. Dobb’s Journal, asp.netPRO magazine, and Microsoft MSDNOnline. He is a great enthusiast for using, teaching, and writing about the latest Microsoft technologies,and provides consulting and training services to help others use them in their own software products.

    01_793507 ffirs.qxp 7/10/06 5:21 PM Page v

  • 01_793507 ffirs.qxp 7/10/06 5:21 PM Page vi

  • CreditsSenior Acquisitions EditorJim Minatel

    Development EditorBrian MacDonald

    Technical EditorScott Spradlin

    Production EditorFelicia Robinson

    Copy EditorKim Cofer

    Editorial ManagerMary Beth Wakefield

    Production ManagerTim Tate

    Vice President and Executive Group PublisherRichard Swadley

    Vice President and Executive PublisherJoseph B. Wikert

    Graphics and Production SpecialistsJennifer ClickBrooke GraczykDenny HagerBarbara MooreBarry OffringaLynsey OsbornAlicia B. SouthJulie Trippetti

    Quality Control TechniciansJohn GreenoughLeeann HarneyJessica KramerChristy PingletonRob SpringerBrian H. Walls

    Proofreading and IndexingTechbooks

    01_793507 ffirs.qxp 7/10/06 5:21 PM Page vii

  • Acknowledgments

    I would first like to thank Jim Minatel, the senior acquisitions editor on the book or giving me the oppor-tunity to write this exciting book. Huge thanks go to Brian MacDonald, the book’s development editor.Thanks for all your valuable input, comments, and suggestions. I’ve really enjoyed working with you onthis wonderful project. I’d also like to thank Scott Spradlin, the book’s technical editor, for his work.Thanks for your valuable input. Thanks also go to Felicia Robinson, the book’s production editor.Additional thanks go to (Kim Cofer, the copy editor and Techbooks, the proofreader). I would also liketo thank my friends for understanding my absence.

    01_793507 ffirs.qxp 7/10/06 5:21 PM Page viii

  • Contents

    Acknowledgments viiiIntroduction xxi

    Chapter 1: The ASP.NET 2.0 Framework 1

    Following the Request 1Why Develop Custom Components? 5

    Data Source Controls 6Role Manager Modules and Principals 6Role Providers 7Membership Providers 7Customizing XML Web Services and Their Clients 7Developing Ajax-Enabled Controls and Components 7Developing Web Parts Controls 8Developing Custom Data Control Fields 8Developing Custom HTTP Handlers and Modules 9Developing Custom Provider-Based Services 9

    Summary 9

    Chapter 2: Developing Simple Custom Controls and User Controls 11

    Information Hiding 12Deploying Your Custom Controls 16Using Custom Controls in a Web Page 17Adding Properties to Your Custom Controls 18Adding Design-Time Attributes to Your Custom Controls 20

    Property-Level Attributes 20Class-Level Attributes 21Assembly-Level Attributes 22

    Adding Your Custom Control to the Visual Studio Toolbox 23The HtmlTextWriter-Related Enumerations 23State Management 28User Controls 32

    Using a User Control 33Adding Properties to User Controls 34Adding Methods to User Controls 36Under the Hood 38

    Summary 39

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page ix

  • x

    Contents

    Chapter 3: Developing Custom-Styled Controls 41

    Style 41WebControl 43

    Overriding the Render Method 47TagKey 47RenderBeginTag 48AddAttributesToRender 48RenderContents 52RenderEndTag 52

    Deriving from the WebControl Class 53Developing a Custom Style Class 58Using Your Custom Style Class 62Summary 64

    Chapter 4: Developing Custom Controls That Raise Events 65

    About Events 65.NET Event Design Pattern 66

    Event Data and Event Delegate Class 66Enabling Your Custom Control to Raise the Event 69

    Event Optimization 70Postback 73

    C# Interface Implementation Pattern 75Postback Event 76Postback Data 77

    Page Life Cycle 86Summary 90

    Chapter 5: Developing Custom Composite Controls 91

    CreditCardForm6 Revisited 91Rendering HTML 92Postback Functionality 95

    Creating Composite Controls 97Deriving from CompositeControl 98Choosing the Child Controls 98Choosing the Layout 99Implementing a Custom Container Control 100Creating a Container Control 101Creating the Child Controls of a Container Control 102Applying Style to a Container Control 105Adding a Container Control to a Composite Control 105Rendering a Container Control 106

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page x

  • xi

    Contents

    CreateChildControls: One-Stop Shopping for All Your Child Controls 106TagKey 108CreateControlStyle 109Exposing Style Properties 109RenderContents 109Label Properties 112Event Bubbling 114What Your Custom Control Inherits from CompositeControl 117Overriding the Controls Collection 118INamingContainer Interface 118

    Summary 120

    Chapter 6: Developing Custom Templated Controls 121

    Customizing the Contents of a Container Control 121TemplatedCreditCardForm 124Using the Template in an ASP.NET Page 125Under the Hood of the Template 127Data Binding Expressions 130Under the Hood of Data Binding Expressions 135Default Template 137Summary 145

    Chapter 7: Developing Custom Controls with Complex Properties 147

    Container Control Style Properties 147Customizing the Appearance of a Container Control 148State Management 151Types That Implement IStateManager 152

    DefaultTemplateManager 154TemplatedCreditCardForm3 158

    Types That Don’t Implement IStateManager 164TypeConverter 164DefaultTemplateManager2 165DefaultTemplateManager2Converter 166Marking DefaultTemplateManager2 with Its Converter 168Using the Non-IStateManager Class 169Why You Need to Use TypeDescriptor 172

    State Management of Container Control Styles 172Property Declaration 173TrackViewState 174SaveViewState 175LoadViewState 176

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page xi

  • xii

    Contents

    Declarative Persistence 177Simple Properties 177Complex Properties (Hyphenated Declarative Persistence) 177Complex Properties (Inner-Property Declarative Persistence) 179

    Summary 181

    Chapter 8: ASP.NET Request Processing Architecture 183

    Following the Request 183HTTP Modules 187HTTP Handlers 188HTTP Handler Factories 189Control Builders 189Developing Custom HTTP Modules 196Registering Your Custom HTTP Module 198Developing Custom HTTP Handler Factories 199Developing Custom HTTP Handlers 200

    RSS 201RssHandler 202Registering Your Custom HTTP Handler 205

    Developing Custom Control Builders 207Developing the CompositeCreditCardForm2Builder Custom Control Builder 210Developing the CompositeCreditCardForm2 Custom Control 210

    Summary 216

    Chapter 9: Data Binding 217

    The CustomTable Control 217Specifying the Data Source 218Overriding CreateChildControls 220Overriding the DataBind Method 221Creating the Control Hierarchy 222

    DataControlField 225CreateFields 225CreateHeaderRow 227CreateBodyRow 228CachePrimaryKey 233CreatePagerRow 234

    Overriding CreateControlStyle 235Implementing the CustomTable Events 235Overriding OnBubbleEvent 237CustomTableRow 238

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page xii

  • xiii

    Contents

    CustomTableRowCollection 240Child Control Styles 240Overriding Render 241State Management 243

    TrackViewState 243SaveViewState 244LoadViewState 245

    Using CustomTable in a Page 246Shortcomings of the CustomTable Control 247Summary 248

    Chapter 10: XML Web Services 249

    Developing and Consuming an XML Web Service 250Under the Hood of the Add Reference Button 252WSDL Document 255

    The Names, Types, and Order of the Arguments 257The Types and Order of the Return Values 257Describing the Method 258Describing the Communication Protocol for Accessing the Method 259Specifying the Site for Method Access 260Specifying the Class of the Method 260

    The XmlWebServiceMethodInvoker Class 260Programmatically Downloading the WSDL Document 261De-serializing a .NET Object from the WSDL Document 262Generating the Code for the Proxy Class 263Under the Hood of the Import Method 263Compiling the Code for the Proxy Class 267Creating an Instance of the Proxy Class 268Invoking the Specified Method of the Proxy Class Instance 268Putting It All Together: The InvokeXmlWebServiceMethod Method 272

    How to Use XmlWebServiceMethodInvoker 272Caching the Compiled Proxy Class 275

    Cache-Related Properties 275CompileCodeForProxyClass 276InvokeXmlWebServiceMethod 277Using the Caching Feature 278

    Developing XML Web Service–Enabled Custom Controls 281XmlWebServiceResolver 283

    XMLResolver 283GetEntity 288

    Summary 291

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page xiii

  • xiv

    Contents

    Chapter 11: Implementing Schema Importer Extensions and ISerializable Interface 293

    Implementing IXmlSerializable 293Implementing the Server-Side Component 294Developing the Client-Side Component 299

    Developing Custom Schema Importer Extensions 301Write the Code in Your Favorite Language 303CodeDom Approach 304

    Registering Your Custom Schema Importer Extension 317Sending and Receiving Data in Chunks 318

    BookContent 319ForumBook 321Custom Schema Importer Extension 322

    Extensibility of the XmlWebServiceMethodInvoker 324Summary 324

    Chapter 12: Understanding the ASP.NET 2.0 Tabular Data Source Control Model 325

    Why You Need the ASP.NET 2.0 Data Source Control Model 325Retrieving Data 327Update Event 328

    The ASP.NET 2.0 Data Source Control Model 330ASP.NET 2.0 Tabular Data Source Control Model 331

    IDataSource 332Under the Hood of DataSourceControl 333Deriving from the DataSourceControl Base Class 335DataSourceView 336Delete 347Update 351Insert 355State Management 359

    Summary 360

    Chapter 13: The ASP.NET 2.0 Data Source Control Parameter Model 361

    Parameters 361The Parameter Class 365

    The OnParameterChanged Method 365SaveCurrentValue Method 366Evaluate Method 366CookieParameter 367ControlParameter 368

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page xiv

  • xv

    Contents

    ParameterCollection 370ParametersChanged Event 370OnInsert Method 371GetValues Method 371UpdateValues Method 372

    Automatic Invocation of GetValues and UpdateValues Methods 373Properties of Type ParameterCollection 373OnInit and Page_LoadComplete Methods 375ExecuteSelect 375ExecuteDelete 376ExecuteUpdate 378ExecuteInsert 379

    Putting It All Together 381Developing Custom Parameters 383

    XmlWebServiceParameter 383ObjectParameter 387ClientParameter 390

    Summary 394

    Chapter 14: Developing ASP.NET 2.0 Custom Tabular Data Source Controls 395

    The XmlWebServiceMethodInvoker Component 396DataSourceControl 398DataSourceView 399

    ExecuteSelect 399ExecuteUpdate 411ExecuteInsert 416ExecuteDelete 420

    RetrieveMethodArgumentNamesAndValues 423State Management 426Summary 428

    Chapter 15: Understanding the ASP.NET 2.0 Hierarchical Data Source Control Model 429

    IHierarchicalDataSource 430HierarchicalDataSourceControl 431HierarchicalDataSourceView 433IHierarchyData 436IHierarchicalEnumerable 437

    XmlHierarchyData 440XmlHierarchicalEnumerable 446XmlHierarchyDataPropertyDescriptor 447

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page xv

  • xvi

    Contents

    ICustomTypeDescriptor 450XmlHierarchicalDataSourceView 451

    Summary 452

    Chapter 16: Developing ASP.NET 2.0 Custom Hierarchical Data Source Controls 453

    CustomSqlDataSource 453SqlHierarchyDataPropertyDescriptor 459SqlHierarchyData 462

    Constructor 462Implementing HasChildren 463Implementing the Type Property 463

    SqlHierarchicalEnumerable 465SqlHierarchicalDataSourceView 467Summary 468

    Chapter 17: Understanding the ASP.NET 2.0 Tabular Data-Bound Control Model 469

    The Big Picture 470ASP.NET 1.x Data-Bound Control Model 471

    The RetrieveData Method 472Overriding the DataBind Method 472Handling the Third Data-Binding Task 472

    BaseDataBoundControl 473Automating the Invocation of the DataBind Method 473The First and Second Data-Binding Tasks 474The Third Data-Binding Task 475

    Developing Custom Data-Bound Controls That Derive from BaseDataBoundControl 476Handling the Load Event 477Overriding the PerformSelect Method 477Declarative Programming Without Writing Code 479Shortcomings of the CustomTable2 Control 480

    DataBoundControl 480The GetDataSource Method 482The GetData Method 482Overriding the Abstract Methods of the BaseDataBoundControl 483

    Developing Custom Data-Bound Controls That Derive from DataBoundControl 486Overriding the CreateDataSourceSelectArguments Method 486Overriding the PerformDataBinding Method 488The UpdateCallback Method 489

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page xvi

  • xvii

    Contents

    The DeleteCallback Method 490Codeless Data-Agnostic Declarative Programming 491

    CompositeDataBoundControl 492Overriding the PerformDataBinding Method 494Overriding the DataBind Method 494Overriding the CreateChildControls Method 495Overriding the Controls Collection 495

    Developing Controls That Derive from CompositeDataBoundControl 496MasterDetailForm 496AddDetailRow 501AddMasterCell 503AddMasterHeaderCell 504AddMasterSelectButton 504AddDetailCommandBar 505Delete Data Operation 507Update Data Operation 508Sort Data Operation 509Control State 510Appearance Properties 511Codeless Master/Detail Form 512

    Summary 513

    Chapter 18: The ASP.NET 2.0 Data Control Field Model 515

    Why You Need the ASP.NET 2.0 Data Control Field Model 515DataControlField 518

    The OnFieldChanged Method 519Initialize Method 520InitializeCell Method 520ExtractValuesFromCell Method 521

    BoundField 522InitializeCell 523InitializeDataCell 523OnDataBindField 524GetValue 525ExtractValuesFromCell 526

    DataControlFieldCollection 527FieldsChanged Event 528OnInsert Method 528

    Developing Custom Data Control Fields 529DropDownListField 529CalendarField 537

    Summary 542

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page xvii

  • xviii

    Contents

    Chapter 19: Developing ASP.NET 2.0 Custom Tabular Data-Bound Controls 543

    Deriving from the CompositeDataBoundControl 544Overriding the CreateChildControls Method 545

    Initializing the Parameters 546Describing the Primary Key Fields 547Creating the Child Table Control 548Creating the PagedDataSource Object 549Creating the Data Control Fields 551Creating the Top Pager Row 555Creating the Header Row 558Enumerating the Data Records 558Creating the Empty Data Row 560Creating and Populating the GridViewRowCollection 561The CreateRow Method 562The InitializeRow Method 562

    Overriding the CreateDataSourceSelectArguments Method 564Overriding the CreateControlStyle Method 565Overriding the OnBubbleEvent Method 565

    The EventHandler Method 566Overriding the Render Method 573State Management 576Overriding the OnInit Method 578Events 578GridViewRow 581GridViewRowCollection 585Summary 585

    Chapter 20: Why You Need the ASP.NET 2.0 Membership/Role Model 587

    ASP.NET 1.x Security Model 588Authorization Mechanisms 593Shortcomings of the ASP.NET 1.x Security Model 594The .NET 2.0 Provider Pattern 595Summary 597

    Chapter 21: Understanding the ASP.NET 2.0 Membership Model 599

    Membership 599Membership Provider Instantiation and Initialization 600Support for the Section 600Provider and Providers Properties 602

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page xviii

  • xix

    Contents

    Membership API 605Adding a New User to the Data Store 605Removing a User from the Data Store 607Updating Specified User Membership Information in the Data Store 607Validating User Credentials Against the Data Store 607Searching Users in the Data Store 608Retrieving User Membership Information from the Data Store 609Enforcing Application-Specific Password Validation Rules 610Accessing the User Online Time Window 612

    Developing Custom Security Controls 613Login 613Register 618Using the Login and Register Controls 619Registering the SqlMembershipProvider 621

    MembershipUser 622Accessing the Membership Provider 624Resetting and Retrieving Passwords 624Changing Passwords 625Changing Password Question and Answer 625Unlocking a User 626

    Summary 626

    Chapter 22: Developing Custom MembershipProvider and MembershipUserComponents 627

    MembershipProvider 628SqlMembershipProvider 629ProviderBase 629MembershipProvider 635

    ChangePassword 635ValidateUserInfo 637UpdateUserInfo 641Update 642ChangePasswordQuestionAndAnswer 642CreateUser 643DeleteUser 648FindUsersByEmail 648FindUsersByName 650GetAllUsers 651Select 653GetNumberOfUsersOnline 653GetPassword 653GetUser 656GetUserNameByEmail 658

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page xix

  • xx

    Contents

    ResetPassword 659UnlockUser 661UpdateUser 662ValidateUser 662

    Registering SqlMembershipProvider 662Using the Custom Membership Provider 663Extending the ASP.NET 2.0 Membership API 665

    CustomMembershipUser 666CustomMembershipProvider 667CustomSqlMembershipProvider 667Using CustomMembershipUser, CustomMembershipProvider, andCustomSqlMembershipProvider 673

    Summary 675

    Chapter 23: Understanding the ASP.NET Role Management Model 677

    Roles API 678Managing Roles 678Managing Users 679

    RolePrincipal 681Identity 681Role Membership 682IPrincipal 682

    RoleManagerModule 687PostAuthenticateRequestCallback 687GetRoles Event 689EndRequestCallback 690

    Summary 692

    Chapter 24: Developing Custom Role Providers, Modules, and Principals 693

    RoleProvider 693XmlRoleProvider 694ProviderBase 695XML APIs 696

    Streaming XML APIs 696Random-Access XML APIs 701

    Implementing RoleProvider’s Methods 703LoadData 704SaveData 704Role Management 705User Management 716

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page xx

  • xxi

    Contents

    Developing Custom Role Principals 727Constructors 728GetRoles 730Implementing the IPrincipal Interface 731

    Developing Custom Role Manager Modules 732PostAuthenticateRequestCallback 733GetRoles Event 735EndRequestCallback 736XmlRoleProvider and CacheDependency 738

    Using the XmlRoleProvider 739Summary 743

    Chapter 25: Developing Custom Provider-Based Services 745

    Recipe for Developing Custom Provider-Based Services 745Provider-Based RSS Service 746Custom Provider Base 747Custom Provider Collection 748Configuring the Web.config and Machine.config Files 748

    Custom Configuration Section 749Registering the Section 750

    Implementing the Service Class 750Using the RSS Service 753SqlRssProvider 753

    Initialize 754LoadRss 759GetDataReader 761Registering SqlRssProvider 761

    RssHelper 762XmlRssProvider 764

    Initialize 764LoadRss 767RetrieveData 769Registering XmlRssProvider 770

    Summary 771

    Chapter 26: Developing Ajax-Enabled Controls and Components: Client-Side Functionality 773

    Ajax-Enabled Controls and Components 774Recipe for Implementing Ajax-Enabled Controls’ Client-Side Functionality 776

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page xxi

  • xxii

    Contents

    Rendering Options 776Rendering Client Script as HTML Attribute Values 776Rendering Client Script as Script Blocks 779Client Script Library 786

    Deployment Issues 789Deploying Resource Files to a Shared Location 789Embedding Resource Files into an Assembly 790

    When to Render Your Control’s Client Script 798Disabling Your Control’s Client-Side Capabilities 798Discovering Ajax Capabilities of the Requesting Browser 798

    Where to Render Your Control’s Client Script 800Overriding OnPreRender 800Overriding AddAttributesToRender 800Overriding RenderContents 801Overriding Render 801

    Falling Back on Server-Side Code 801Developing Ajax-Enabled Controls 802

    CustomImage Ajax-Enabled Control 804ImageDialog Ajax-Enabled Composite Control 811

    Summary 825

    Chapter 27: Developing Ajax-Enabled Controls and Components: Asynchronous Client Callback 827

    Motivation for the AjaxDropDownList Control 828The Client Callback Mechanism 829Implementing the ASP.NET 2.0 Client Callback Mechanism 830

    Overriding the OnPreRender Method 831Overriding the Render Method 837Server Side 838

    The ASP.NET 2.0 Client Callback Mechanism 839Overriding the OnPreRender Method 840Overriding the Render Method 841Server Side 842

    Data Store-Agnostic Ajax-Enabled Controls 844Master/Detail Form 847Developing Ajax-Enabled Data Control Fields 848AjaxDetailsDialog 851

    AjaxDetailsDialog as a Composite Control 854AjaxDetailsDialog as an Ajax-Enabled Control 857

    AjaxField Data Control Field 864Overriding InitializeCell 865Overriding OnDataBindField 868

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page xxii

  • xxiii

    Contents

    Implementing CreateField Method 869Overriding ExtractValuesFromCell 869

    DropDownListField2 870Overriding InitializeCell 871Overriding CreateField 873Overriding ExtractValuesFromCell 873

    Ajax-Enabled Custom GridView Control 873Overriding CreateChildTable 873Overriding PrepareControlHierarchy 876

    Summary 881

    Chapter 28: Developing Ajax-Enabled Controls and Components: Ajax Patterns 883

    Patterns 883Google XML Web Service API 884Predictive Fetch 892

    Deriving from WebControl 894Implementing ICallbackEventHandler 911

    Summary 914

    Chapter 29: Developing Ajax-Enabled Controls and Components: More Ajax Patterns 915

    Periodic Refresh 915Deriving from WebControl 916Implementing ICallbackEventHandler 918

    Submission Throttling 925Overriding OnPreRender 926Overriding Render 928JavaScript Functions 936

    Explicit Submission 943Overriding OnPreRender 944Overriding Render 945Implementing ICallbackEventHandler 946JavaScript Functions 947Summary 949

    Chapter 30: Understanding the ASP.NET 2.0 Web Parts Framework 951

    What Is the ASP.NET Web Parts Framework? 951Developing WebPart Controls Declaratively 954Moving WebPart Controls 957

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page xxiii

  • xxiv

    Contents

    Personalizing WebPart Controls’ Properties 961Personalizing WebPart Controls’ Custom Properties 964Adding Declared WebPart Controls 966Adding Closed WebPart Controls 968Exporting WebPart Controls 970Adding Imported WebPart Controls 972Main Components of the Web Parts Framework 974Part 975Summary 977

    Chapter 31: Developing Custom WebPart, EditorPart,and CatalogPart Controls 979

    WebPart 979Developing Custom WebPart Controls 983

    CreateChildControls 984AddContainer 986AddItemToContainer 986Using the RssReaderWebPart Control 987

    Implementing IWebPart 988IWebActionable 988

    Developing Custom Web Parts Verbs 990Developing WebPart Controls That Support Custom Web Parts Verbs 991

    EditorPart 995Developing Custom EditorPart Controls 996

    RssReaderEditorPart as a Composite Control 998SyncChanges 1002ApplyChanges 1003OnLoad 1005RssReaderWebPart4 Control 1005

    CatalogPart 1014Developing Custom CatalogPart Controls 1018

    GetAvailableWebPartDescriptions 1020LoadWebPartInfoSet 1023GetWebPart 1024LoadWebPartDescriptionFile 1025Using the XmlWebServiceCatalogPart Control 1025

    Summary 1031

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page xxiv

  • xxv

    Contents

    Chapter 32: Developing Custom WebPartZoneBase Controls 1033

    WebZone 1033WebPartZoneBase 1036

    Deriving from WebZone 1037CreateWebPartChrome 1038CreateInitialWebParts 1039CreateVerbs Event 1039Implementing IPostBackEventHandler 1040

    WebPartZone 1042Developing Custom WebPartZone Controls 1044

    XmlWebServiceWebPartZone 1044ProviderBasedWebPartZone 1050SqlDescriptionDocumentProvider 1062

    WebPartChrome 1066RenderWebPart 1067PerformPreRender 1071

    Developing a Custom WebPartChrome 1072CustomWebPartZone 1074Using the CustomWebPartChrome Control 1075

    Summary 1076

    Chapter 33: WebPartManager, Web Parts Connections,and Data-Bound WebPart Controls 1077

    Developing Custom WebPartManager Controls 1077Connecting WebPart Controls 1081

    Implementing the Provider and Consumer WebPart Controls 1090Dynamic Connections 1096Programmatic Connections 1101

    Developing Data-Bound WebPart Controls 1108BaseDataBoundWebPart 1110DataBoundWebPart 1111CompositeDataBoundWebPart 1113GridViewWebPart 1114MasterDetailGridViewWebPart 1116

    Summary 1121

    02_793507 ftoc.qxp 6/29/06 7:20 PM Page xxv

  • 02_793507 ftoc.qxp 6/29/06 7:20 PM Page xxvi

  • Introduction

    Welcome to Professional ASP.NET 2.0 Server Control and Component Development. The ASP.NET 2.0Framework consists of two groups of components. The first group contains server controls, that is, thosecomponents that directly or indirectly derive from the ASP.NET Control base class. This group includessecurity controls, tabular and hierarchical data source controls such as SqlDataSource andXmlDataSource, Web Parts controls set, data-bound controls, and so on.

    The second group contains the rest of the ASP.NET 2.0 components including HTTP modules, HTTPhandlers, HTTP handler factories, security components such as RolePrincipal, RoleManagerModule,role providers, MembershipUser and membership providers, data control fields such as BoundField,data source control parameters such as ControlParameter, ISerializable, schema importer exten-sions, and so on.

    This book covers both groups of ASP.NET 2.0 components. In other words, this book shows you how todevelop not only server controls, which belong to the first group, but also components that belong to thesecond group.

    Who This Book Is ForThis book is aimed at the ASP.NET developer who wants to learn how to build custom server controlsand components for the first time. No knowledge of authoring custom server controls and componentsis assumed.

    What This Book CoversThis book provides you with detailed step-by-step recipes and real-world server controls and compo-nents developed using these recipes to help you gain the skills, knowledge, and experience that youneed to develop:

    ❑ Ajax-enabled controls and components: This book has four chapters dedicated to this topicwhere you’ll learn how to develop Ajax-enabled controls and components. These controls arecharacterized by the following characteristics and features, which enables them to break freefrom the traditional “click-and-wait” user unfriendly user interaction pattern:

    ❑ Their rich client-side functionality: This book shows you how to use client-side tech-nologies such as XHTML/HTML, CSS, DOM, XML, and JavaScript to implement Ajax-enabled controls and components with rich client-side functionality.

    ❑ Their asynchronous communication with the server: You’ll learn how to use theASP.NET 2.0 client-callback mechanism to implement complex Ajax-enabled controlsand components that make asynchronous client callbacks to the server without havingto perform full page postbacks.

    03_793507 flast.qxp 6/29/06 7:20 PM Page xxvii

  • xxviii

    Introduction

    ❑ Exchanging XML data with the server: You’ll see how to use client-side and server-sideXML technologies to develop Ajax-enabled controls and components that exchangedata with the server in XML format and use DHTML to dynamically generate HTMLfrom the XML data that they receive from the server to display the data.

    ❑ Ajax patterns: You’ll also discover how to use Ajax patterns such as Predictive Fetch,Periodic Refresh, Submission Throttling, and Explicit Submission to develop Ajax-enabled controls and components that contain the logic that determines the best time toexchange data with the server to enable end users to interact with the application with-out interruptions and irritating waiting periods.

    ❑ ASP.NET 2.0 Web Parts controls: Four chapters cover the Web Parts controls set, where you’lllearn how to implement the following:

    ❑ Custom WebPart, EditorPart, CatalogPart, WebPartZoneBase, WebPartChrome,WebPartVerb, and WebPartManager controls

    ❑ The IWebPart, IWebActionable, IWebEditable, and IPersonalizable interfaces

    ❑ Static, dynamic, and programmatic Web Parts connections

    ❑ Custom data-bound WebPart controls with minimal effort. This book implements a setof base data-bound controls named BaseDataBoundWebPart, DataBoundWebPart, andCompositeDataBoundWebPart that you can derive from to implement custom data-bound WebPart controls that can access any type of data store and can automate all ofits data operations such as delete, update, insert, sorting, and paging so the page devel-oper can use them declaratively without writing a single line of code.

    ❑ ASP.NET 2.0 security, role management, and membership components: You’ll find five chap-ters dedicated to these topics where you’ll learn how to develop role providers, membershipproviders, custom role manager modules, custom role principals, and customMembershipUser.

    ❑ ASP.NET 2.0 tabular and hierarchical data source controls: This book has five chapters thatteach you how to develop custom tabular and hierarchical data source controls to expose tabu-lar and hierarchical data from your own favorite data store, whether the data store itself is tabu-lar or hierarchical.

    ❑ ASP.NET 2.0 tabular data-bound controls: The four chapters that cover this topic show youhow to develop tabular data-bound controls as complex as GridView that can access any typeof data store and can automate all of their data operations such as delete, update, insert, sorting,and paging so the page developer can use them declaratively without writing any code.

    ❑ Custom schema importer extensions and ISerializable: You’ll discover how to implement cus-tom schema importer extensions and the ISerializable interface to customize the proxy classcode generation and to customize the serialization and deserialization of your custom compo-nents. This book also shows you how to use these techniques to improve the performance ofXML Web services that send huge amounts of data.

    ❑ Provider-Based Services: You’ll also learn how to enable the services that your Web applica-tions provide to their clients to access any type of data store without code changes. For example,RSS feeds are one of the services that most Web applications provide to their clients. You’ll learnhow to implement a RSS service provider that can feed RSS from any type of data store such asSQL Server, XML documents, Oracle, flat files, XML Web services, and so on.

    03_793507 flast.qxp 6/29/06 7:20 PM Page xxviii