ASRNET is the latest incarnation of Microsoft's Active Server Pages (ASP) - a powedul server-
based technology, designed to create dynamic and interactive HTML pages for your web site,
or corporate intranet. ASRNET also constitutes a core element in Microsoft's .NET vision,
providing web-based access to an immensely powerful new development environment, .NET;
in this respect alone, it's a great leap ahead of all previous versions of ASP.
This book will provide you with a step-by-step introduction to ASP. NET using C#, with plenty
of worked examples, that will help you to gain a deep understanding of what ASRNET is all
about, and how you can harness it to build powerful web applications.
Also available as Beginning ASRNET using VB.NET (1-861005-04-0)
Who is this book for?
This book is aimed at relatively inexperienced web builders who are looking to enrich their
sites with dynamically-generated content, and want to learn how to start building web
applications using ASRNET. Developers who have a little experience with previous versions of
ASP (and are looking to move over to ASRNET), may also find this book helpful in getting a
simple grasp of what ASRNET is, what it does, and how it can be used.
Experience of basic HTML is required, but previous experience of ASP is not essential. We'll
be teaching the basics of C# in this book, so prior experience of C# is not required.
What does this book cover?
Creating basic ASRNET pages
Learning the basics of C#
Understanding the concepts of Object Oriented Programm!ng
Working with data and XML
The ASP. NET Server Controls
Creating User Controls and Components
Exploring the world of Web Services
Configuring your ASRNET Applications
Introduction
Chapter 1: Getting Started With ASP.NET
What Is A Static Web Page?
How Are Static Web Pages Served?
The Limitations of Static Web Pages
What is a Web Server?
How Are Dynamic Web Pages Served?
TWO Ways of Providing Dynamic Web Page Content
An Overview of the Technologies
What is ASP. NET?
How Does ASP.NET Differ From ASP?
The Installation Process
installing the IlS 5.x Web Server
Testing the installation
Managing Directories on your Web Server
Prerequisites for Installing ASP.NET
Installing ASP.NET and the .NET Framework SDK
ASP.NET Test Example
ASP. NET Troubleshooting
Summary
Chapter 2: Anatomy of an ASP.NET Page
What is .NET?
The .NET Base Classes
Flow ASP.NET Works
The .NET Framework and ASP. NET in Action
Summary
Chapter 3: Forms and HTML Server Controls
Forms in the Real World
Web Pages, HTML Forms and Web Forms
Simple Web Theory
Client-Server
The HTTP Protocol
Where ASP.NET Fits in with the .NET Framework
HTML Forms
The Tag
Embedding HTML Form Controls
Introduction to Server Controls
ASP.NET Server Controls
The Control
The Control
Hidden Controls
The Control
The Control
The and Controls
The and Controls
Summary
Chapter 4: Storing Variable Data using C#
What is a Variable?
Declaration
Data Types
Numeric Types
Character Data Types
Boolean Typ(~
The Object Type
Handling Dates
Naming Variables
Operators
Assignment Operator
Arithmetic Operations
Operator Precedence
Concatenating Strings
Converting Between Data Types
Implicit Conversion
Explicit Conversion
Invalid Casts
Data Conversion
What if Conversions Fail?
Constants
Structured Data Types
Arrays
Structs
Enumerations
Summary
Exercise Questions
Chapter 5: Introducing XML
Tags and Elements
Attributes
Examples of Markup Languages
SGML
HTML
How XML Came About
What is XML?
The Data Revolution
Breaking Beyond Data Display
Well-formed versus Valid Documents
Well-Formed Documents
Valid Documents
Styling XML
Why Use Style Sheets?
Cascading Style Sheets
Using XML With ASP.NET
Summary
Exercises
Chapter 6: Control Structures and Procedural Programming
A Quick Look at Control Structures
Overview of Branching Structures
Overview of Looping Structures
Overview of Functions
Examples of Control Structures
Branching Structures in Detail
Comparison Operators
Logical Comparisons using if
Logical Operators
The Conditional or Ternary Operator
Comparing Strings
Conditional Statements using switch...case
Looping Structures in Detail
The for Loop
The while loop
The do...while Loop
The foreach Loop
Break and Continue
Functions in Detail
Defining Functions
Variable Scope
Local Variables
Global Variables
Summary
Exercises
Chapter 7: Event-driven Programming and Postback
What is an Event?
What is Event-Driven Programming?
ASP.NET Events
Events in HTML
Server Control Events in ASP. NET
The ASP.NET Button Server Control
Event-Driven Programming and Postback
Changing the Way we Program on the Web
Summary
Exercises
Chapter 8: Introduction to Objects
Organizing Your Code
So, What is an Object?
Abstraction - Modeling the Real World
Encapsulation - The Black Box
Using Objects
Defining a Class
Creating Objects
Using Methods and Properties
Initializing Objects with Constructors
Overloaded Functions
Operator Overloading
Summary
Exercises
Chapter 9: Static Class Members and Class Relationships
Static Members
Static Properties
Static Methods
Class Relationships
Association - "uses a"
Containment - a "has a" relationship
Inheritance - "is a"
Advanced Inheritance Concepts
Virtual Functions
Abstract Classes and Interfaces
Converting between Object Types
Implicit Conversions
Explicit Conversions
Boxing and Unboxing
User-Defined Conversions
Summary
Exercises
Chapter 10: Objects in ASP.NET
Namespaces
Namespaces for ASP.NET
The Page Class
Redirecting the User to Another Page
ASP.NET Core Objects
Request Object
Response Object
Server Object
State Handling
Application State
Session State
Cookies
Summary
Exercises
Chapter 11: Objects and Structured Data
What is a Collection?
Different Types of Collection
Arrays as Collections
Searching an Array
Working on Multiple Elements in an Array
Data Binding
Pros and Cons of Working with Arrays
Getting More From Collections
ArrayList
Hashtable
SortedList
Summary
Exercises
Chapter 12: Reading from Data Sources
Understanding Modern Databases
Data Models
Normalization and Relational Databases
ADO.NET
Managed Providers
ADO.NET Objects
The Connection Object
The Command Object and DataReader
The DataSet and DataTable Objects
Microsoft SQL Server and ADO.NET
Dealing with Runtime Errors
Summary
Exercises
Chapter 13: Manipulating Data Sources
Disconnected Data
Methods of Updating Data
DataSets and DataTables
The DataRow Object
Updating the Original Data Source
Updating Data - Summary
Using SQL
The DataAdapter Commands
Using Stored Procedures
Direct SQL Commands
Using SQL - Summary
Working with XML
XML into Strings
XML in a DataSet
What to Study Next
Summary
Exercises
Chapter 14: ASP.NET Server Controls
Other Types Of Controls
HTML Server Controls
User Controls
ASP,NET Server Controls
Rich Object Model
Automatic Browser Detection
Properties
Events
Page Lifecycle
Page Load
Event Handling
PageUnload
Control Families
Intrinsic Controls
Validation Controls
Rich Controls
Data Rendering Controls
Calendar Implementation Details
Repeater Control Implementation Details
Editing the Data Using Templates
AutoGenerating the Columns
Summary
Chapter 15: Reusable Code for ASP.NET
From Objects to Components
Components
Why use Components?
Applying Component Theory to our Applications
User Controls
Pros and Cons of User Controls
Code-Behind
Code-Behind and User Controls
A Recap On Inheritance
Summary
Exercises
Chapter 16: .NET Assemblies and Custom Controls
Three-Tier Application Design
ASP.NET Application Design
.NET Assemblies
What is Compilation?
More about Command Line Compilation
Accessing a Component From Within an ASP.NET Page
Configuring an ASP.NET Application with web.config
XCopy Deployment
Writing Code in Other Languages
Introducing Business Objects
Custom Server Controls
How it all Fits Together
Summary
Exercises
Chapter 17: Debugging & Error Handling
A Few Good Habits
Syntax Errors
Logical Errors
System Errors
Good Coding Practice
Code Testing - the Crude Way
Finding Errors
Debug Mode
Tracing
Handling Errors using Code
On Error Goto...?
Structured Exception Handling
Using try...catch...finally
Multiple catch Blocks
Generating Exceptions using throw
Nested try Blocks
Handling Errors in ASP.NET
Notification and Logging
writing To The Event Log
Mailing the Site Administrator
Summary
Chapter 18: Web Services
What is a Web Service?
HTTP, XML and Web Services
Building an ASP.NET Web Service
Processing Directive
Namespaces
Public Class
Web Methods
Testing your Web Service
Using your Web Service
Consuming a Web Service
Creating a Proxy
Web Service Discovery
Securing a Web Service
Username/Password Combination or Registration Keys
Secure Sockets Layer (SSL)
IP Address Restriction
Other Considerations
Network Connectivity
Asynchronous Method Calls
Service Hijacking (or Piggybacking)
Provider Solvency
The Interdependency Scenario
Summary
Exercises
Chapter 19: Configuration and Optimization
Configuration Overview
The Configuration Files
The Structure of the Configuration Files
General Configuration
Page Configuration
Application Settings
Custom Errors
Performance Optimization
Caching
Tracing
Monitoring the ASP.NET Process
Tips and Tricks
Summary
Appendix A: The Common System Namespaces
Appendix B: References and Further Information
Appendix C' Support, Errata, and p2p.wrox.com
The Online Forums at p2p.wrox.com
Checking the Errata Online at www.wrox.com
Add an Erratum: E-mail Support
How to Tell Us Exactly What You Think
Index
ASP.NET is the latest incarnation of Microsoft's Active Server Pages (ASP) - a powerful server-based technology from Microsoft, designed to create dynamic and interactive HTML pages for your World Wide Web site, or corporate intranet. ASP.NET also constitutes a core element in Microsoft's .NET vision, providing web-based access to an immensely powerful new development environment, .NET; in this respect alone, it's a great leap ahead of all previous versions of ASP.
This purpose of this book is to teach you how to use ASP.NET to write web pages, whose content can be programmatically-generated from scratch every time the page is viewed. This not only saves you a lot of effort in presenting and updating your web pages, but also offers tremendous scope for adding sophisticated functionality to your site. This book will answer the fundamental questions:
What is ASP.NET?
How do I install ASP.NET and get it up and running?
How does it work?
How can I use it to produce dynamic, interactive web applications?
We'll answer these questions in a thorough and comprehensive way, with plenty of fully working examples. Even if you're totally new to this technology, you will gain a deep understanding of what ASP.NET is all about, and learn how you can harness it to build powerful web applications.
Who Is This Book For?
This book is aimed at relatively inexperienced web builders who are looking to enrich their sites with dynamically-generated content, and want to learn how to start building web applications using ASP.NET. Developers who have a little experience with previous versions of ASP (and are looking to move over to ASP.NET), may also find this book helpful in getting a simple grasp on what ASP.NET is, what it does, and how we can use it.
This is a Wrox Beginning... series book, so we will aim to teach you everything you neea to know from scratch. If you already have some experience of programming ASP.NET, you may be more comfortable starting at a somewhat quicker pace with the natural follow-up title Professional ASP. NET (Wrox Press, ISBN 186004885). For more specific information on programming with C# you should check out Beginning C# (Wrox Press, ISBN 1861004982)or Professional C# (Wrox Press, ISBN 1861004990).
We appreciate that most (if not all) of the web authors and developers who take up ASP.NET, are reasonably familiar with simple HTML, so we won't spend lots of time teaching it. However, if you don't know HTML, we suggest you take some time to get familiar with it before trying to learn about ASP.NET. There are plenty of good HTML tutorials available, both in books and on the Web. There are two kinds of beginners for whom this is the ideal book:
You're a beginner to programming and you've chosen ASP.NET as the technology with which to get started. Great choice! ASP.NET is not only easy and fun, but it's also very useful, and very, very powerful. This book will hold your hand throughout.
You can program in another language, but you're a beginner to web programming. Again, this is a great choice! You may still have a few lessons to learn about programming in .NET, but this book will introduce you to how it does things in terms you'll understand.
Most importantly, you don't need to know anything more than the basic ins and outs of how to put your own web page together. If you've never written a single line of any programming language, then you have to nothing to fear - this is the book for you. The bottom line is as follows:
This book will teach you how to write ASP.NET applications.
What Does This Book Cover?
This book was written as Microsoft released the Beta 2 version of ASP.NET. This release is almost feature complete, and stable enough for developers to begin learning about and using the new technology as well as deploying live sites. Microsoft already has several live sites running on the beta release, which have proved faster than their older counterparts. While we can't guarantee that the final release version will be identical, you can be sure that almost all of the concepts, examples, and explanations we provide are accurate within the timeframe of the first full version of .NET.
In this book, we attempt to explain just what ASP.NET is all about, how you can use it, and what you can use it for. The book can be broken down into four main sections:
An Introduction to ASP. NET
In Chapters 1 to 3, we shall introduce some of the core concepts behind the Web and look at how ASP.NET adds to the range of web programming technologies already available. We'll take you through the process of installing the Microsoft .NET Framework (on which ASP.NET relies), and demonstrate some simple applications. We'll start to consider how ASP.NET works behind the scenes, and introduce some simple techniques for generating web pages with ASP.NET.
Programming ASP. NET
Chapters 4 through 7 go on to look at various ways in which we can store and manipulate data in our
programs, look at controlling the order in which commands are executed, and consider some simple issues of
code structure. Here we will provide the basics of programming in C#, the chosen language for this book. We also introduce you to XML, an important language which is much used behind the scenes in .NET.
Objects in ASP. NET
Objects and the principles of object-oriented programming (OOP) play a fundamental role in .NET, so Chapters 8 through 11 will familiarize you with the notion of OOP, the philosophy behind it, and the ways in which we can use objects to write more effective code. In this section more advanced features of the C# language are explained and applied.
Practical ASP. NET
The final section of the book will discuss and demonstrate various techniques for making your web applications useful in the real world. Chapters 12 through 19 will consider topics such as error handling, data access, configuration, and building code components and web services.
This isone 0f two editions of Beginning ASP.NET. This version presents all code examples in C#; The Visual Basic .NET version of the book is called, "Beginning ASP. NET using VB.NET'! (ISBN 1861005040).
What Do I Need to Run ASP. NET?
In order to answer this, we need to consider the role that we'll be playing in this book - namely that of the web developer or Webmaster. In this role, we'll be writing web pages, publishing them on a web server, and testing them to see what they look like and whether they work. This is just a list of items that you will need. Don't worry if you can't locate all the bits and pieces just yet, as we'll be looking at where to get them from in the opening chapter:
A text editor (such as Windows Notepad).
A web browser (any one should do, since the hard work is all done on the server).
An ASP.NET-compliant web server (ASP.NET requires lis 5.0 or later - this means that you'll need to be running Windows 2000 or Windows XP).
The .NET Framework (currently available in several different varieties - unless you have access to the full ".NET Framework SDK", which features documentation, tutorials, and a download size of over 100MB, we suggest you download the slightly more modest but no less functional 18MB "ASP.NET Premium Edition" from www.aspnet.com).
The code in this book will not work with the -1 release of ASP.NET.
In order to make full use of .NET's data access functionality (which we look at in later chapters), you must make sure that you have version 2.7 or later of the Microsoft Data Access Components (MDAC2.7) installed on the same machine as your web server. We'll also assume you have a copy of Microsoft Access from which to access the sample data. Other databases such as MSDE and SQL Server are also fine, but most of the examples we show will require a little tweaking in order to work with these alternative databases.
Specifically for the purposes of this book, we discourage you fiom using a web page editor such as FrontPage, or a full development tool like Visual Studio. While these are powerful tools that can be very helpful in a development environment, they will often add their own code to your web pages automatically. This can often make it harder to see what,going on, and can, at this level, really get in the way of what we're supposed to be demonstrating in a particular example.
When we browse pages on the Web, or even on a local intranet, the browser and the web server software are generally hosted on two di~rent physical machines. Note however, that it's quite possible to run your text editor, browser, and web server simultaneously on the same machine. Indeed, web developers often use this technique as they write, test, rewrite and tweak their ASP.NET pages. Conventions We've used a number of different styles of text and layout in this book to help differentiate between the different kinds of information. Here are examples of the styles we used and an explanation of what they mean. Code has several fonts. If it's a word that we're talking about in the text - for example, when discussing a do... wh5 le loop, it's in this font. If it's a block of code that can be typed as a program and run, then it's also in a gray box:
<%6 Page language="c#" runat="server" %>
Sometimes we'll see code in a mixture of styles, like this:
<%6 Page language="c#" runat="server" %>
In cases like this, the code with a white background is code we are already familiar with; the line highlighted in gray is a new addition to the code since we last looked at it.
Advice, hints, and background information comes in this type of font.
Important pieces of information come in boxes like this.
Bullets appear indented, with each new bullet marked as follows:
Important Words are in a bold type font.
Words that appear on the screen, or in menus like File or Window, are in a similar font to the one you would see on a Windows desktop.
Keys that you press on the keyboard like Ctrl and Enter, are in italics.
Customer Support
We've tried to make this book as accurate and enjoyable as possible, but what really matters is what the book actually does for you. Please let us know your views, either by returning the reply card in the back of the book, or by contacting us via e-mail at feedback@wrox.com.
Source Code and Updates
As we work through the examples in this book, you may decide that you prefer to type in all the code by hand. Many readers prefer this, because it's a good way to get familiar with the coding techniques that are being used.
Whether you want to type the code in or not, we have made all the source code for this book available at our web site at the following address:
http://www.wrox.com/
If you like to type in the code, you can use our files to check the results you should be getting – they should be your first stop if you think you might have typed in an error. If you don't like typing, then downloading the source code from our web site is a must!
Either way, it'll help you with updates and debugging.
Exercises and Solutions
Most of the chapters in this book have a set of exercises for you to work through, which are based on the subject matter of the corresponding chapter. However, the solutions to these exercises are not printed in the book and if you need them, then they are available to you at this address:
http://p2p.wrox.com/
p2p.wrox.com is a web site run by Wrox Press to offer technical support for a very wide range of technologies, including ASP.NET and C#. For more information on what P2P offers, read Appendix D at the end of this book.
Errata
We've made every effort to make sure that there are no errors in the text or the code. However, to err is human, and as such, we recognize the need to keep you informed of any mistakes as they're spotted and corrected. Errata sheets are available for all our books at http://www.wrox.com. If you find an error that hasn't already been reported, please let us know. For more information on this, see Appendix D at the end of the book.
Our web site acts as a focus for other information and support, including the code from all Wrox books, sample chapters, previews of forthcoming titles, and articles and opinions on related topics.