100% found this document useful (2 votes)
15 views

ASP NET by Example 6th Edition Steven A. Smith pdf download

The document provides links to various ASP.NET-related ebooks, including titles like 'ASP.NET by Example' and 'Pro ASP.NET MVC 3 Framework.' It offers instant digital downloads in multiple formats and highlights the content of the books, which cover topics from basic introductions to advanced techniques in ASP.NET. The document serves as a resource for those looking to enhance their knowledge and skills in ASP.NET development.

Uploaded by

herailsney
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
15 views

ASP NET by Example 6th Edition Steven A. Smith pdf download

The document provides links to various ASP.NET-related ebooks, including titles like 'ASP.NET by Example' and 'Pro ASP.NET MVC 3 Framework.' It offers instant digital downloads in multiple formats and highlights the content of the books, which cover topics from basic introductions to advanced techniques in ASP.NET. The document serves as a resource for those looking to enhance their knowledge and skills in ASP.NET development.

Uploaded by

herailsney
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

ASP NET by Example 6th Edition Steven A.

Smith
pdf download

https://ebookgate.com/product/asp-net-by-example-6th-edition-
steven-a-smith/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Pro ASP NET MVC 3 Framework 3rd Edition Steven Sanderson

https://ebookgate.com/product/pro-asp-net-mvc-3-framework-3rd-edition-
steven-sanderson/

ebookgate.com

Microsoft ASP NET 4 Step by Step George Shepherd

https://ebookgate.com/product/microsoft-asp-net-4-step-by-step-george-
shepherd/

ebookgate.com

Mastering ASP Net with VB Net 1st Edition A. Russell Jones

https://ebookgate.com/product/mastering-asp-net-with-vb-net-1st-
edition-a-russell-jones/

ebookgate.com

Pro ASP NET Web API HTTP Web Services in ASP NET 1st
Edition Tugberk Ugurlu

https://ebookgate.com/product/pro-asp-net-web-api-http-web-services-
in-asp-net-1st-edition-tugberk-ugurlu/

ebookgate.com
ASP NET Core 1st Edition Fritz

https://ebookgate.com/product/asp-net-core-1st-edition-fritz/

ebookgate.com

Pro ASP NET SharePoint 2010 Solutions Techniques for


Building SharePoint Functionality into ASP NET
Applications 1st Edition Dave Milner
https://ebookgate.com/product/pro-asp-net-sharepoint-2010-solutions-
techniques-for-building-sharepoint-functionality-into-asp-net-
applications-1st-edition-dave-milner/
ebookgate.com

Flash Game Development by Example Feronato

https://ebookgate.com/product/flash-game-development-by-example-
feronato/

ebookgate.com

Debugging ASP NET 1st ed Edition Jonathan Goodyear

https://ebookgate.com/product/debugging-asp-net-1st-ed-edition-
jonathan-goodyear/

ebookgate.com

Pro ASP NET SharePoint 2010 Solutions Techniques for


Building SharePoint Functionality into ASP NET
Applications 1st Edition Dave Milner (Auth.)
https://ebookgate.com/product/pro-asp-net-sharepoint-2010-solutions-
techniques-for-building-sharepoint-functionality-into-asp-net-
applications-1st-edition-dave-milner-auth/
ebookgate.com
00 71465_FM 11/30/01 10:26 AM Page i

ASP.NET
B Y E X A M P L E

201 West 103rd Street


Steven A. Smith
Indianapolis, Indiana 46290
00 71465_FM 11/30/01 10:26 AM Page ii

Publisher
ASP.NET by Example David Culverwell
Copyright © 2002 by Que Executive Editor
All rights reserved. No part of this book shall be reproduced, Candy Hall
stored in a retrieval system, or transmitted by any means, elec- Acquisitions Editor
tronic, mechanical, photocopying, recording, or otherwise, with- Michelle Newcomb
out written permission from the publisher. No patent liability is
assumed with respect to the use of the information contained
Development Editors
herein. Although every precaution has been taken in the prepa- Robin Drake
Maureen McDaniel
ration of this book, the publisher and author assume no respon-
Sarah Robbins
sibility for errors or omissions. Nor is any liability assumed for
damages resulting from the use of the information contained Managing Editor
herein. Thomas F. Hayes
International Standard Book Number: 0-7897-2562-2 Senior Editor
Susan Ross Moore
Library of Congress Catalog Card Number: 2001090372
Copy Editors
Printed in the United States of America Margaret Berson
Michael Dietsch
First Printing: December 2001
Indexer
04 03 02 01 4 3 2 1 D&G Limited, LLC

Trademarks Proofreader
D&G Limited, LLC
All terms mentioned in this book that are known to be trade-
marks or service marks have been appropriately capitalized. Technical Editor
Que cannot attest to the accuracy of this information. Use of a Vincent W. Mayfield
term in this book should not be regarded as affecting the validity Team Coordinator
of any trademark or service mark. Cindy Teeters
Media Developer
Warning and Disclaimer Michael Hunter
Every effort has been made to make this book as complete and
Interior Designer
as accurate as possible, but no warranty or fitness is implied.
Karen Ruggles
The information provided is on an “as is” basis. The author(s)
and the publisher shall have neither liability nor responsibility Cover Designer
to any person or entity with respect to any loss or damages Rader Design
arising from the information contained in this book. Page Layout
D&G Limited, LLC
00 71465_FM 11/30/01 10:26 AM Page iii

iii

Contents at a Glance
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1
1 Overview .NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7
2 An Introduction to ASP.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19
3 Migrating from ASP to ASP.NET . . . . . . . . . . . . . . . . . . . . . . . . . .31
4 The New ADO—ADO.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .65
5 HTML/Web Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .109
6 Using ASP.NET List Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . .139
7 Using ASP.NET Rich Controls . . . . . . . . . . . . . . . . . . . . . . . . . . .171
8 Using ASP.NET Validation Controls . . . . . . . . . . . . . . . . . . . . . . .195
9 Using ASP.NET User Controls . . . . . . . . . . . . . . . . . . . . . . . . . . .227
10 ASP.NET Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .247
11 ASP.NET and Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . .275
12 Custom ASP.NET Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .307
13 Debugging ASP.NET Overview . . . . . . . . . . . . . . . . . . . . . . . . . . .343
14 Case Study in Ecommerce with ASP.NET . . . . . . . . . . . . . . . . . .365
A The ASP.NET Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .393
B The ADO.NET Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . .405
C VB.NET Programming Reference . . . . . . . . . . . . . . . . . . . . . . . . .459
D C# Programming Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . .489
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .516
00 71465_FM 11/30/01 10:26 AM Page iv

Table of Contents
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1
1 .NET Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7
The Big .NET Picture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8
The .NET Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9
Class Orientation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9
Runtime Hosts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10
The Common Language Runtime: A New Interpretation
of Older Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11
Intermediate Language and Metadata . . . . . . . . . . . . . . . . .12
The JIT Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15
2 An Introduction To ASP.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19
Moving to .NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20
A Brief History of ASP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21
Why ASP Developers Need This Book . . . . . . . . . . . . . . . . . . . . . .23
Benefits of ASP.NET over ASP . . . . . . . . . . . . . . . . . . . . . . . . . . .24
ASP.NET Is Compiled, not Interpreted . . . . . . . . . . . . . . . . .24
Separation of Code from Content . . . . . . . . . . . . . . . . . . . . .24
No More “DLL Hell” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24
Side-by-Side Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . .25
Real Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .25
Real Programming Languages . . . . . . . . . . . . . . . . . . . . . . .25
Real Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26
Directory-Based Deployment . . . . . . . . . . . . . . . . . . . . . . . . .26
File-Based Application Configuration . . . . . . . . . . . . . . . . . .26
Event-Based Programming Model . . . . . . . . . . . . . . . . . . . .26
Improved, Extensible Object Model . . . . . . . . . . . . . . . . . . .27
More Integrated Functions . . . . . . . . . . . . . . . . . . . . . . . . . .27
Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28
Performance Improvements . . . . . . . . . . . . . . . . . . . . . . . . .28
Better Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29
3 Migrating From ASP to ASP.NET . . . . . . . . . . . . . . . . . . . . . . . . .31
Preparing to Use ASP.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .32
Basic Differences Between ASP and ASP.NET . . . . . . . . . . . . . . .32
00 71465_FM 11/30/01 10:26 AM Page v

Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .32
Maintaining State Between ASP and ASP.NET . . . . . . . . . .33
Language Differences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .34
Common ASP Tasks and Their ASP.NET Equivalents . . . . . . . . .36
Read a Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .36
Validate a Form’s Entries . . . . . . . . . . . . . . . . . . . . . . . . . . .42
The Login Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .50
View Results of Database Query . . . . . . . . . . . . . . . . . . . . . .58
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .62
4 The New ADO—ADO.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .65
ADO vs. ADO.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66
The History of Microsoft Data Access . . . . . . . . . . . . . . . . . .66
ADO vs. ADO.NET Object Model . . . . . . . . . . . . . . . . . . . . .68
Connecting to the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . .69
Retrieving Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70
Using the SqlCommand Object . . . . . . . . . . . . . . . . . . . . . . . . .70
The DataReader Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72
The SqlDataAdapter Object . . . . . . . . . . . . . . . . . . . . . . . . . . .75
The DataSet Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .79
Data Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .87
The DataGrid Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .87
The Repeater Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .94
The DataList Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .99
Working with XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102
Generating XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .103
Consuming XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .106
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .107
5 HTML/Web Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .109
What Are Server Controls, Anyway? . . . . . . . . . . . . . . . . . . . . . .110
Why Two Kinds of Controls? . . . . . . . . . . . . . . . . . . . . . . . .110
When Should I Use Each Kind of Control? . . . . . . . . . . . . .111
HtmlControls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .111
HtmlControl Properties and Methods . . . . . . . . . . . . . . . . . .111
HtmlContainerControl Properties . . . . . . . . . . . . . . . . . . . . .114
An HtmlControl Example . . . . . . . . . . . . . . . . . . . . . . . . . .114
HtmlForm Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .117
Table Control Properties . . . . . . . . . . . . . . . . . . . . . . . . . . .118
00 71465_FM 11/30/01 10:26 AM Page vi

vi

HtmlInputControl Properties . . . . . . . . . . . . . . . . . . . . . . . . .119


HtmlSelect Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120
HtmlTextArea Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . .121
HtmlAnchor Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121
HtmlImage Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121
HtmlInputFile Properties . . . . . . . . . . . . . . . . . . . . . . . . . . .122
HtmlInputImage Properties . . . . . . . . . . . . . . . . . . . . . . . . . .123
WebControls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .123
WebControl Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .123
Button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .126
CheckBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .127
RadioButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .127
HyperLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .128
Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .128
ImageButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .129
Label . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .129
LinkButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .129
Literal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .129
Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .130
PlaceHolder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .130
Table, TableRow, and TableCell . . . . . . . . . . . . . . . . . . . . . . .130
TextBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .132
Xml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .133
Populating ListBoxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .133
Declarative . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .135
Programmatic with Items Collection . . . . . . . . . . . . . . . . . .135
Programmatic with Databinding . . . . . . . . . . . . . . . . . . . . .135
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .136
6 Using ASP.NET List Controls . . . . . . . . . . . . . . . . . . . . . . . . . . .139
The ListControl Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .140
Working with DropDownList . . . . . . . . . . . . . . . . . . . . . . . . .141
Getting the SelectedItem . . . . . . . . . . . . . . . . . . . . . . . . . . .141
Using the SelectedIndexChanged Event . . . . . . . . . . . . . . . .143
AutoPostBack: When You Just Can’t Wait . . . . . . . . . . . . . . .144
Using ListBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .144
Using SelectedIndex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .145
Selecting Multiple Items with SelectionMode . . . . . . . . . . . .146
00 71465_FM 11/30/01 10:26 AM Page vii

vii

Working with the Items Collection . . . . . . . . . . . . . . . . . . . . . . . .147


Adding Items with the Add Method . . . . . . . . . . . . . . . . . . .148
Removing Items with the Remove Method . . . . . . . . . . . . . .152
Databinding and List Controls . . . . . . . . . . . . . . . . . . . . . . . . . .155
Using DataTextField and DataValueField Properties . . . . . .157
Databinding List Control Selections . . . . . . . . . . . . . . . . . .159
Changing the Layout of List Controls . . . . . . . . . . . . . . . . . . . . .161
Using RepeatLayout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .161
A Change in Direction with RepeatDirection . . . . . . . . . . . .163
Fine-Tuning List Control Layout . . . . . . . . . . . . . . . . . . . .166
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .168
7 Using ASP.NET Rich Controls . . . . . . . . . . . . . . . . . . . . . . . . . . .171
Introduction to Rich Controls . . . . . . . . . . . . . . . . . . . . . . . . . . .172
Working with AdRotator . . . . . . . . . . . . . . . . . . . . . . . . . . . .172
Using the AdCreated Event . . . . . . . . . . . . . . . . . . . . . . . . . .178
Introduction to the Calendar Control . . . . . . . . . . . . . . . . . . . . . .182
Using SelectionMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .185
Databinding and Calendar . . . . . . . . . . . . . . . . . . . . . . . . . .187
Modifying Calendar Display . . . . . . . . . . . . . . . . . . . . . . . . .187
Using CSS to Control Calendar Display . . . . . . . . . . . . . . . . . . . .190
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .193
8 Using ASP.NET Validation Controls . . . . . . . . . . . . . . . . . . . . . .195
Validating HTML Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .196
What Are Validation Controls? . . . . . . . . . . . . . . . . . . . . . . . . . .196
Client-Side Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .197
Inserting a Validation Control . . . . . . . . . . . . . . . . . . . . . . . . . . .197
Validation Control Properties . . . . . . . . . . . . . . . . . . . . . . .199
Validation Control Methods . . . . . . . . . . . . . . . . . . . . . . . . .200
RequiredFieldValidator Control . . . . . . . . . . . . . . . . . . . . . . . . . .200
RangeValidator Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .201
CompareValidator Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .203
RegularExpressionValidator Control . . . . . . . . . . . . . . . . . . . . . . .207
CustomValidator Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .213
ValidationSummary Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .215
Bringing It All Together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .217
00 71465_FM 11/30/01 10:26 AM Page viii

viii

One Step Beyond: VControls . . . . . . . . . . . . . . . . . . . . . . . . . . . .220


Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .224
9 Using ASP.NET User Controls . . . . . . . . . . . . . . . . . . . . . . . . . .227
Introduction to User Controls . . . . . . . . . . . . . . . . . . . . . . . . . . .228
Creating ASP.NET User Controls . . . . . . . . . . . . . . . . . . . . . . . .228
Creating Code-behind User Controls . . . . . . . . . . . . . . . . .231
Defining Properties in User Controls . . . . . . . . . . . . . . . . .233
Defining Methods in User Controls . . . . . . . . . . . . . . . . . . .236
Raising Events from User Controls . . . . . . . . . . . . . . . . . . .238
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .245
10 ASP.NET Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .247
HTTP Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .248
global.asax—A Good Place to Start and End . . . . . . . . . . .248
Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .249
Configuring Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . .253
What Web.config Looks Like and Where to Find It . . . . . .254
Setting up Web.config . . . . . . . . . . . . . . . . . . . . . . . . . . . . .255
Authentication and Authorization in web.config . . . . . . . . .258
Building a Simple Authentication Application . . . . . . . . . . . . . .260
The Application Root . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .261
Deploying your ASP.NET Application . . . . . . . . . . . . . . . . . . . . .271
Assembly Deployment: \bin . . . . . . . . . . . . . . . . . . . . . . . .271
What If I Need to Update My DLL? . . . . . . . . . . . . . . . . . .271
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .272
11 ASP.NET and Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . .275
Distributed Computing: Many Things to Many People . . . . . . . .276
What Is a Web Service? . . . . . . . . . . . . . . . . . . . . . . . . . . . .277
Coming Clean About SOAP . . . . . . . . . . . . . . . . . . . . . . . . .278
WSDL: A Service Contract Language . . . . . . . . . . . . . . . . .278
Disco and UDDI—The Discovery Protocols . . . . . . . . . . . . .279
Writing Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .279
The ASP.NET Pipeline and Handler Architecture . . . . . . . .280
Writing Our First Service . . . . . . . . . . . . . . . . . . . . . . . . . .280
Processor Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .280
The [WebMethod] Attribute . . . . . . . . . . . . . . . . . . . . . . . . . .281
Generating a Client Proxy . . . . . . . . . . . . . . . . . . . . . . . . . .283
A Simple Web Service Client . . . . . . . . . . . . . . . . . . . . . . . .286
00 71465_FM 11/30/01 10:26 AM Page ix

ix

Advanced Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .288


Returning Complex Types . . . . . . . . . . . . . . . . . . . . . . . . . .289
Asynchronous Processing . . . . . . . . . . . . . . . . . . . . . . . . . .293
Transaction Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .295
Programming Web Services with Microsoft
Visual Studio .NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .296
Creating Web Services in Visual Studio .NET . . . . . . . . . .296
Visual Studio .NET Project Structure . . . . . . . . . . . . . . . . .298
Consuming Web Services in Visual Studio .NET . . . . . . . .301
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .304
12 Custom ASP.NET Server Controls . . . . . . . . . . . . . . . . . . . . . . . .307
Custom Controls Defined . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .308
Custom Controls Versus User Controls . . . . . . . . . . . . . . . . . . . .308
Third-Party Custom Controls . . . . . . . . . . . . . . . . . . . . . . . . . . .309
Internet Explorer WebControls . . . . . . . . . . . . . . . . . . . . . .309
ASPSmith VControls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .310
SoftArtisans TreeView . . . . . . . . . . . . . . . . . . . . . . . . . . . . .310
Other Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .310
Creating a Custom Control of Our Own . . . . . . . . . . . . . . . . . . .310
Command Line Building and Deployment . . . . . . . . . . . . .311
Visual Studio.NET Building and Deployment . . . . . . . . . . .312
Referencing the Control from ASP.NET . . . . . . . . . . . . . . .313
Building On Existing Controls . . . . . . . . . . . . . . . . . . . . . . . . . .313
Creating Composite Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . .316
Handling Control Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .320
Handling PostBacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .326
Using Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .329
Raising Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .335
Databinding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .339
Building Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .339
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .340
13 Debugging ASP.NET Overview . . . . . . . . . . . . . . . . . . . . . . . . . .343
ASP.NET Debugging Features . . . . . . . . . . . . . . . . . . . . . . . . . .344
System.Trace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .344
Trace Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .345
00 71465_FM 11/30/01 10:26 AM Page x

Implementing Tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .347


System.Trace.TraceContext . . . . . . . . . . . . . . . . . . . . . . . . . .349
Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .349
Application-Level Debugging . . . . . . . . . . . . . . . . . . . . . . .352
System.Diagnostics Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .353
Logging Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .354
Reading Event Logs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .355
Other System.Diagnostics Tools . . . . . . . . . . . . . . . . . . . . . .358
Visual Studio.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .359
Frequently Encountered Bugs . . . . . . . . . . . . . . . . . . . . . . . . . . .359
Runat=”Server” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .359
Type Mismatches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .360
VB/VBScript Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .360
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .361
14 Case Study: E-commerce with ASP.NET . . . . . . . . . . . . . . . . . . .365
Building a Web Store—IBuySpy.com . . . . . . . . . . . . . . . . . . . . . . .366
IBuySpy Store Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .366
Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .366
Design Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . .367
Functional Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .373
Some Recommended Improvements . . . . . . . . . . . . . . . . . .382
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .390
A ASP.NET Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .393
File Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .394
Page Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .395
Other Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .395
Adding Code-Behind Pages . . . . . . . . . . . . . . . . . . . . . . . . .395
Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .396
Dealing with Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .397
Creating a Connection with ADO.NET . . . . . . . . . . . . . . . .397
Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .397
Retrieving Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .398
DataSets and XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .399
Viewing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .399
Databinding Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .400
00 71465_FM 11/30/01 10:26 AM Page xi

xi

Using Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .401


Declaring a Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .401
Referencing a Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . .401
Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .401
System.Trace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .401
Application-Level Tracing . . . . . . . . . . . . . . . . . . . . . . . . . .402
Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .403
B ADO.NET Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .405
System.Data Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .406
DataColumn Object Members . . . . . . . . . . . . . . . . . . . . . . . . .406
DataRow Object Members . . . . . . . . . . . . . . . . . . . . . . . . . . .409
DataSet Object Members . . . . . . . . . . . . . . . . . . . . . . . . . . .412
DataTable Object Members . . . . . . . . . . . . . . . . . . . . . . . . . .417
DataView Object Members . . . . . . . . . . . . . . . . . . . . . . . . . .421
DataViewManager Object Members . . . . . . . . . . . . . . . . . . . . .423
System.Data.OleDb Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . .425
OleDbCommand Object Members . . . . . . . . . . . . . . . . . . . . . . .425
OleDbConnection Object Members . . . . . . . . . . . . . . . . . . . . .428
OleDbDataReader Object Members . . . . . . . . . . . . . . . . . . . . .430
OleDbDataAdapter Object Members . . . . . . . . . . . . . . . . . . . .433
OleDbError Object Members . . . . . . . . . . . . . . . . . . . . . . . . .438
OleDbParameter Object Members . . . . . . . . . . . . . . . . . . . . .439
System.Data.SqlClient Namespace . . . . . . . . . . . . . . . . . . . . . . . .441
SqlCommand Object Members . . . . . . . . . . . . . . . . . . . . . . . . .440
SqlConnection Object Members . . . . . . . . . . . . . . . . . . . . . .444
SqlDataReader Object Members . . . . . . . . . . . . . . . . . . . . . .447
SqlDataAdapter Object Members . . . . . . . . . . . . . . . . . . . . .450
SqlError Object Members . . . . . . . . . . . . . . . . . . . . . . . . . .454
SqlParameter Object Members . . . . . . . . . . . . . . . . . . . . . . .455
C Visual Basic.NET Language Reference . . . . . . . . . . . . . . . . . . . .459
Changes from Previous Versions of VB . . . . . . . . . . . . . . . . . . . .459
General Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .459
Procedure Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .460
Property Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .461
Changes to Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .462
Data Type Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .463
00 71465_FM 11/30/01 10:26 AM Page xii

xii

New Features in VB.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .464


Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .464
Structures Replace UDTs . . . . . . . . . . . . . . . . . . . . . . . . . .465
Constructors and Destructors . . . . . . . . . . . . . . . . . . . . . . .465
Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .465
Namespaces and Assemblies . . . . . . . . . . . . . . . . . . . . . . . .466
Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .466
Threading Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .466
Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . .466
Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .466
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .467
Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .468
Expressions and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . .468
Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .469
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .469
Statement Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .469
Labeled . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .470
Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .470
Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .470
Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .470
Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .471
Control-Flow Statements . . . . . . . . . . . . . . . . . . . . . . . . . .472
Try . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .473
Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .474
Value Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .474
Reference Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .476
Component-Based Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . .484
Namespaces and Assemblies . . . . . . . . . . . . . . . . . . . . . . . .484
Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .485
D C# Language Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .489
Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .490
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .490
Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .491
Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .492
Operators and Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . .492
Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .492
00 71465_FM 11/30/01 10:26 AM Page xiii

xiii

Blocks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .493
Statement Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .493
Empty Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .493
Labeled . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .493
Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .493
Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .494
Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .494
Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .495
jump . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .496
try . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .497
checked and unchecked . . . . . . . . . . . . . . . . . . . . . . . . . . . . .498
lock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .498
using . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .498
Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .498
Value Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .498
Reference Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .500
Component-Based Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . .512
Namespaces and Assemblies . . . . . . . . . . . . . . . . . . . . . . . .512
Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .513
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .516
00 71465_FM 11/30/01 10:26 AM Page xiv

xiv

About the Authors


Steven A. Smith is a Managing Consultant and Internet Specialist for
Software Architects, Inc., a Chicago-based consulting firm with offices in more
than a dozen U.S. cities. Steve has been a “SARK” for more than four years and
is currently working in the Cleveland office, focusing on highly scalable compo-
nent-based architectures. In his spare time, Steve runs the #1 ASP.NET commu-
nity site, ASPAlliance.com, and maintains a column there with dozens of articles
on ASP and ASP.NET. He has also written a number of articles for ASPToday.com
and continues to work as a technical reviewer for WROX, Prentice Hall, and
QUE. Steve has an MCSE+Internet (4.0) certification and previously completed
the MCSD. He is also a graduate of The Ohio State University with a degree in
Computer Science Engineering. His development experience prior to .NET was
mainly focused on ASP, Visual Basic, SQL Server, and COM+.
When he isn’t bonding with his laptop computer, Steve enjoys biking, swim-
ming, foosball, and spending time with his wife, Michelle, and their two dogs,
Jaegerin and Mojo.
Steve can be reached at ssmith@aspalliance.com.
Nicholas Chase has been involved in Web site development for companies such
as Lucent Technologies, Sun Microsystems, Oracle Corporation, and the Tampa
Bay Buccaneers. Nick has been a high school physics teacher, a low-level
radioactive waste facility manager, an online science fiction magazine editor, a
multimedia engineer, and an Oracle instructor. More recently, he was the Chief
Technology Officer of Site Dynamics Interactive Communications in Clearwater,
Florida, and is the author of three books on Web development, including Java
and XML From Scratch (Que). He loves to hear from readers and can be
reached at nicholas@nicholaschase.com.
Glenn Cook has been programming and teaching ASP since 1997. His tutorials
and award-winning source code continue to make his column at the AspAlliance,
the #1 ASP.NET Community, one of the most popular in its history.
He is the founder of simpleCsharp.com and is a Senior Consultant with
Fahrenheit Technology in Richmond, VA. He has lead projects for clients such as
Land Rover, Charles Schwab, The Yellow Pages, Marriot, and most recently for
CapitalOne.
When he’s not playing with code, he is spending time with his family in the
D.C./VA area.
Nathen Grass is a consultant with RDA Corporation (http://www.
rdacustomsoftware.com) in Atlanta, Georgia. RDA builds custom software
and Web-based applications to solve complex business problems for mid-market
and large-scale companies. Nathen specializes in DNA architecture development
00 71465_FM 11/30/01 10:26 AM Page xv

xv

using various Microsoft technologies and lately has been heavily involved in
learning and developing on the .NET platform. Nathen can be reached at
grass@rdacustomsoftware.com.

Vincent W. Mayfield is a Senior Software Engineer, Microsoft Certified


Solutions Developer, and Vice President/Co-Founder of Bit-Wizards IT
Solutions, Inc., of Fort Walton Beach, Florida. He has more than 12 years of
experience developing software, and over 8 years developing applications for the
Microsoft Windows Family of Operating Systems with C and C++. He has
served in the U.S. Army Reserves and the U.S. Air Force, and is an FAA
Commercial Instrument rated pilot. Vincent has authored/co-authored several
programming books to include: Wait Group’s COM/DCOM Primer Plus, ActiveX
Programming Unleashed, and Visual C++ 5.0 Developer’s Guide. Vincent holds a
BS in Mathematics with Minors in Computer Science and Aerospace Science as
well as a MS in International Relations. Bit-Wizards IT Solutions is a cutting-
edge technology company that provides professional software engineering,
e-commerce, wireless, Web, consulting, and information technology solutions.
Wynn Netherland is President of Houston, Texas-based Praexis, Inc., a soft-
ware consulting firm specializing in developing hosted applications using .NET.
Wynn has worked in Web development since 1995 and is currently working on
his second .NET title. When he’s not churning out code or chapters, he enjoys
traveling and attending Astros games with his wife, Paula. He can be reached
at wynn.netherland@praexis.com.
Scott Swigart is living proof that being a geek at age 12 pays off. He is cur-
rently a senior principal at 3 Leaf Solutions, where he spends the bulk of his
time providing training and consulting services for .NET early adopters. Scott
started working with .NET as soon as the first bits would complete an install.
In addition to working with .NET early adopters, Scott is actively involved in
various .NET projects for Microsoft.
William Wise holds a Master’s degree in Software Engineering from Brandeis
University, a Bachelor’s degree in Philosophy and Religious Studies, and has
done a fair amount of graduate work at the University of Virginia studying
Christianity and Judaism in antiquity. Professionally, he has worked as a devel-
oper, trainer, network administrator, and database administrator and has devel-
oped a number of two-tier and three-tier applications to meet the business
objectives of a variety of employers, primarily in the biotech business sector. His
interests include playing guitar, reading Tolkien’s fiction over and over, and
learning the ins and outs of Linux. William currently resides in the historic
community of Williamsburg, VA, along with his fiancé and several old, close
friends.
00 71465_FM 11/30/01 10:26 AM Page xvi

xvi

Dedication
To my wife, Michelle, with my thanks.
00 71465_FM 11/30/01 10:26 AM Page xvii

xvii

Acknowledgments
I would like to thank two Michelles in my life: my wife, Dr. Michelle Smith,
who has put up with many long hours devoted to my computer, and my editor,
Michelle Newcomb. They have both been very patient with me while I have
worked on this, my first print book. It’s been a long road with a few surprises,
and I’ve really appreciated the support. Thanks also to Chris, for many hours of
diversion while I should have been concentrating.
00 71465_FM 11/30/01 10:26 AM Page xviii

xviii

Tell Us What You Think!


As the reader of this book, you are our most important critic and commentator.
We value your opinion and want to know what we’re doing right, what we could
do better, what areas you’d like to see us publish in, and any other words of
wisdom you’re willing to pass our way.
As an Associate Publisher for Que, I welcome your comments. You can fax,
e-mail, or write me directly to let me know what you did or didn’t like about
this book—as well as what we can do to make our books stronger.
Please note that I cannot help you with technical problems related to the topic of
this book, and that due to the high volume of mail I receive, I might not be able
to reply to every message.
When you write, please be sure to include this book’s title and author as well as
your name and phone or fax number. I will carefully review your comments and
share them with the author and editors who worked on the book.
Fax: 317-581-4666
E-mail: feedback@quepublishing.com

Mail: Associate Publisher


Que
201 West 103rd Street
Indianapolis, IN 46290 USA
01 71465_INTRO 11/30/01 10:36 AM Page 1

Introduction

The by Example Series


How does the by Example series make you a better programmer? The by
Example series teaches programming using the best method possible. After a
concept is introduced, you’ll see one or more examples of that concept in use.
The text acts as a mentor by figuratively looking over your shoulder and show-
ing you new ways to use the concepts you just learned. The examples are
numerous. While the material is still fresh in your mind, you see example
after example demonstrating ways to use the material you’ve just learned.
The philosophy of the by Example series is simple: The best way to teach com-
puter programming is using multiple examples. Command descriptions, format
syntax, and language references are not enough to teach a newcomer a pro-
gramming language. Only by looking at many examples in which new com-
mands are immediately used and by running sample programs can
programming students get more than just a feel for the language.

How This Book Is Designed


This book is designed to quickly get you up to speed with using ASP.NET. The
Microsoft .NET Framework and ASP.NET allow you to develop powerful distrib-
uted applications using an extensive library of functions, in one of many differ-
ent programming languages. What began with Active Server Pages as a
powerful new way to develop Internet applications has evolved into ASP.NET:
a much more powerful, robust, secure, and extensible architecture.
This book is example-based. After a few introductory chapters that lay a concep-
tual foundation for the work we are going to do (and introduce you to ASP.NET),
you’ll find that every chapter is loaded with examples. I believe in the example-
based approach to learning upon which this series is based. Whenever I get into
a jam and need to learn a new programming technique, when I consult the doc-
umentation, the first thing I do is look for a good code example that fits my
needs. It’s one of the fastest ways to learn. One snippet of tight, well-
documented code is worth ten paragraphs of “how to” explanations.
To further enhance the “by Example” approach, every example in this book is
available online at the book’s online resource center. You will be able to actually
see the examples run on an ASP.NET server, as well as download the source
code.
01 71465_INTRO 11/30/01 10:36 AM Page 2

2 Introduction

Using Other Resources


The Microsoft .NET architecture encompasses nearly every part of the Microsoft
programming platform. Obviously, this book cannot hope to cover all or even
very much of the .NET architecture, of which ASP.NET is a single part. You may
find some areas of the book that refer to .NET architectural features without
much further elaboration. You can find Microsoft’s .NET documentation online
at the following URL:
http://www.microsoft.com/net/

You can also find Microsoft’s ASP.NET and Visual Studio.NET documentation
online at the following Web sites:
ASP.NET: http://www.asp.net/
VS.NET: http://msdn.microsoft.com/vstudio/

Finally, although Appendix D features a C# Reference, you can find additional


C# documentation from Microsoft at the following Web address:
http://msdn.microsoft.com/vstudio/nextgen/technology/csharpintro.asp

Who Should Use This Book


ASP.NET by Example is intended for people with some prior knowledge of
Microsoft’s Active Server Pages (ASP) technology who are familiar with pro-
gramming and dynamic data-driven Internet applications. However, you do not
need to be an expert with VBScript, JScript, or any other scripting language
because they play a very limited part in the future of ASP that is ASP.NET.
Furthermore, knowledge of ActiveX Data Objects (ADO) and knowledge of
databases in general, including some SQL (Structured Query Language), is
assumed. Some understanding of components and event-driven programming
will be helpful as well.

What We Assume You Know


We assume that you know how to develop Web pages using HyperText Markup
Language (HTML) and Active Server Pages (or a similar Web development lan-
guage). You’re familiar with either VBScript or JScript or more likely some of
both, and you’ve probably developed at least one Component Object Model
(COM) object, probably using Visual Basic. You may have used ASP 3.0 or
COM+, but many of you are still working with Internet Information Server (IIS)
4.0 on Windows NT, and will only be upgrading to Windows 2000 as this book
reaches the shelves.

What We Assume You Don’t Know


If you already know all that, what can this book do for you? Well, we assume
that you’ve heard of ASP.NET, the .NET architecture, VB Webforms, and other
01 71465_INTRO 11/30/01 10:36 AM Page 3

Introduction 3

Microsoft marketing hoopla over the last year, but that you haven’t had the
chance to work with any of it yet. We figure you’re reading this book to learn
• How ASP.NET can help you as an Internet application developer to be
more efficient and to build more powerful applications
• How the error handling in ASP.NET allows you to centralize your error
handling into one page
• How ASP.NET will make your existing applications perform better by
using compiled code
• How with ASP.NET a complete programming model is available for appli-
cations that allows for better tools and simpler form handling

This Book’s Organization


This book is organized to maximize your transition to the ASP.NET develop-
ment environment. The early chapters provide an introduction to the .NET
Framework and describe the differences between ASP.NET and its predecessor,
ASP 3.0. From there, the all-important knowledge of how to work with data
(ADO.NET) is covered early, so that you can leverage this knowledge in the
later chapters, which progressively cover more and more advanced topics.
Almost every chapter includes many examples that will help you to understand
the points being covered, and you can test the examples yourself online at the
book’s supporting Web site at http://aspauthors.com/aspnetbyexample/.
Specifically, Chapter 1 provides an overview of the .NET Framework, on which
ASP.NET is built. Chapter 2 introduces the reader to ASP.NET, and Chapter 3
provides some guidelines and examples for migrating to ASP.NET. Chapter 4
introduces the reader to ADO.NET, which is used to access data in ASP.NET.
Chapters 5 through 9 cover various controls, including List Controls, Rich
Controls, Validation Controls, User Controls, and Intrinsic Controls. In Chapter
10 we’ll look at how to manage ASP.NET applications. Chapter 11 describes
Web Services, and exciting new technology that allows separate web applica-
tions to easily communicate with one another. Chapter 12 discusses how to
build your on ASP.NET controls. Chapter 13 provides an overview of how to
debug your ASP.NET applications. Finally, Chapter 14 provides a case study
of an e-commerce site built with ASP.NET. In the appendixes you’ll find refer-
ences for the ASP.NET Object Model, the ADO.NET Object Model, the VB.NET
and C# programming languages, and a quick reference to using Visual Studio.
NET. We hope you find this useful as you continue to develop using the latest
Microsoft has to offer.
01 71465_INTRO 11/30/01 10:36 AM Page 4

4 Introduction

Conventions Used In This Book


This book uses several common conventions to help teach ASP.NET. Here is a
summary of these typographical conventions:
• Example. Examples are the most important part of any by Example title.
These provide working demonstrations of the points that are being covered
by the text in each chapter. You’ll see the Example icon beside each of
EXAMPLE those demonstrations.
• Output. The Output icon indicates a figure or code that shows the result
of the preceding example. We supply the output so that you know what to
expect when you run the example yourself.
OUTPUT • Note. Notes provide additional commentary or explanation that doesn’t fit
neatly into the surrounding text. You will find detailed explanations of how
something works, or alternate ways of doing a task.
• Tip. Tips help you work more efficiently by providing shortcuts or hints
about alternate and faster ways of accomplishing a task.
• Caution. Cautions provide a warning to you about situations that involve
possible danger to your system or to your data.
• Online Reference. These notes provide you with URLs that you can visit
to get more information or other resources relating to the topic being dis-
cussed.
• A special monospaced computer font indicates commands and computer
output.
• Because this is a book that has a limited page width, some lines of code
may be too long to fit on a single line. When you see a code continuation
character (➥), you will know that the code has wrapped to the second line.

Online Resources
In addition to the contents of this book, you will find additional resources online
at the book’s Web site. The Web site includes online sample code, any updates to
the book that may be necessary, and information for providing feedback or ques-
tions to the book’s authors. You can find the book’s support Web site at:
http://aspauthors.com/aspnetbyexample/

In addition, you will find a number of ASP.NET related Web sites on the inside
of the back cover.
01 71465_INTRO 11/30/01 10:36 AM Page 5

Introduction 5

What’s Next
OK, enough with the preliminary necessities! Let’s take a look at what all the
fuss is about with ASP.NET. In the first chapter, we’ll provide you with an intro-
duction to Microsoft’s new development architecture, the .NET Framework. This
provides the basis for all of ASP.NET (and, indeed, all Microsoft development in
the near term). Following this introduction, we’ll move into learning ASP.NET
in particular.
02 71465_CH01 11/30/01 10:12 AM Page 6
02 71465_CH01 11/30/01 10:12 AM Page 7

1
.NET Overview
“Keep on the lookout for novel ideas that others have used successfully.
Your idea has to be original only in its adaptation to the problem you’re
working on.”
—Thomas Edison
Thomas Edison did not invent the first electric light bulb or the first incan-
descent lamp. He did, however, invent the first practical and commercially
successful electric incandescent lamp. He did not invent the first electrical
power station. He improved the designs of existing generators and regula-
tors to create the first commercially successful power station capable of
delivering affordable power for electric lighting. He did not invent the tele-
graph. But he did invent the first duplex and multiplex telegraphy systems,
enabling telegraphs to send and receive messages at the same time over the
same wire.
Thomas Edison did not invent the Internet, wireless computer devices, or
even .NET. He did, however, create a framework of core technologies that
we have improved that make those technologies possible. .NET is not the
next generation of the Internet. It is the first practical set of tools that will
enable software developers to invent the next generation of the Internet.
.NET is an original adaptation of many successful and novel technologies
and ideas to solve a problem; businesses have found it very difficult and
expensive to create profitable Internet solutions with the available develop-
ment frameworks and architectures. The next generation of the Internet
will be funded by businesses who demand solutions with a short develop-
ment cycle, a quick return on their investment, long-term profitability, and
that are secure and inexpensive to maintain and upgrade.
.NET has been designed with the Internet in mind from the ground up.
.NET absorbs many successful ideas that have been in use for years, yet it
is a radical departure from the client-server framework it replaces. It is
based on time-tested, object-oriented software programming concepts, non-
proprietary standards and protocols, and programming languages that
02 71465_CH01 11/30/01 10:12 AM Page 8

8 Chapter 1: .NET Overview

many of you are already quite comfortable with. Comfortable or not,


Microsoft has decided to make a clean break from the past, which means
that nobody is completely immune from a learning curve if they care to fol-
low Microsoft into the future. If you already own a copy of Windows 2000,
or Windows XP, you will not need to purchase anything more from
Microsoft to develop, test, and deploy your own software inventions on the
.NET framework. The only thing you will need to invest in beyond that is
your future.
If you don’t buy into the hype, good for you! We encourage you to look
beyond our biased enthusiasm to examine all the facts. When you gain a
better understanding of what .NET is, and the role that ASP.NET has
within this platform, most of you will recognize the changes and invest-
ments that you will need to make to create your own personal commercial
success. The changes might even force you to take a closer look at what the
competition offers, which can’t hurt, regardless of your opinions about
.NET. If you’re starting to feel a bit overwhelmed, just look to the closest
light socket and a bit of Edison’s wisdom to guide you: “Opportunity is often
missed because it is dressed in overalls and looks a lot like work.”
This chapter will give you a high-level introduction to the key concepts and
components that make up the .NET Framework. You will have a much
shorter learning curve if you can think of ASP.NET in terms of the big
.NET picture. We know you’re anxious to dig into the fun stuff, so we’ll do
our best to keep this chapter as quick, fun, and rewarding as we can.

The Big .NET Picture


.NET is a software development and application execution environment
that allows you to create, compile, test, deploy, and execute software that
may be coded in a variety of different programming languages that adhere
to a single set of Common Language Runtime files. In .NET’s initial public
release, Microsoft presents new versions of its most popular programming
languages: Visual Basic and C++, which are now called Visual Basic .NET
and MC++ (Managed C++). Although Microsoft has retired J++, they intro-
duce two new languages: J# and C# (pronounced j-sharp and c-sharp
respectively). In terms of their respective performance and power, all of
these languages are very similar. In terms of the syntax they use, VB.NET
is the only programming language that is not derived from the C Language.
Despite the subtle differences between them and their individual compilers,
the resulting compiled code is the same for every language. This insures
completely seamless language interoperability on a common integrated
platform that is supported by the .NET Framework’s Class Library and
Runtime. Microsoft bundles support for all of these new languages in its
02 71465_CH01 11/30/01 10:12 AM Page 9

The .NET Framework 9

latest release of Visual Studio, now called Visual Studio.NET (VS.NET).


Microsoft’s entire product line of development packages has undergone sig-
nificant changes to satisfy the requirements of this new framework. Of
course, Microsoft would love it if you decided to buy Visual Studio .NET to
develop your .NET applications, but .NET’s open architecture is also an
invitation to any programming language and development environment. In
other words, the output of PASCAL’s compiler will look no different than
the output produced by C#, Eiffel, COBOL, Visual Basic .NET, and so on.
As long as a programming language has a compiler that adheres to the
.NET Framework’s extremely strict set of rules to produce a common exe-
cutable language, it is a welcome addition to the .NET family.

The .NET Framework


Currently, the .NET framework will run on the following operating sys-
tems: Windows 98, Windows ME, Windows 2000, and Windows XP. (We
expect that this list of operating systems will eventually include third-party
O/Ss, so we recommend that you check “http://msdn.microsoft.com/net/”
to check for any new additions to that list.)
From a high-level view, the .NET Framework can be described as a little
virtual operating system that runs on top of one of the operating systems
we mentioned. A closer inspection would reveal that the framework is made
up of two main components: the .NET Class Library and the Common
Language Runtime (CLR).

Class Orientation
The .NET Class Library is a huge organized hierarchy of class objects,
shown in Figure 1.1. These objects expose services that you can use to
develop your own services. They include support for things like Windows
Forms and Web Services, as well as objects for working with XML and data.
To include these services in our applications, we navigate the hierarchy
using traditional object-oriented programming principles. Navigating this
hierarchy is a lot like you would navigate hierarchy of files and folders on
your hard drive. For example, if you were referring me to a certain SQL
driver on my system (assuming we have the same OS) you would use some-
thing like “c:\WINNT\System\Data\SQLClient\”. A similar reference
included in your code would look like “System.Data.SQLClient”. The only
difference is that the object-oriented code references separate each level of
the hierarchy with a dot “.” These explicit references to groups of classes
within the Framework’s class libraries are also referred to as namespaces
in .NET. You can think of namespaces as organizing classes just as folders
organize files in a file system.
02 71465_CH01 11/30/01 10:13 AM Page 10

10 Chapter 1: .NET Overview

Windows Windows
Web HTTP
Pages Forms Service
Services Handlers
Applications Applications

ASP.NET

System Class Library

System Data Web XML More…

Common Language Runtime

.NET Framework

OS

Figure 1.1: The .NET Framework’s Architecture.

A namespace is a unique hierarchical reference to a specific class or group


of similar classes. For example, the base classes that provide the services
that support the runtime environment are found in the System namespace.
This namespace includes services for things like I/O, security, data, and
Web-related operations. To access these namespaces programmatically, your
reference would look like System.Web or System.Data. The more specific a
namespace is, the more specific its services will usually be. For example, if
I wanted to connect to an SQL database, I could use the System.Data.
SqlClient namespace.

We also use the benefits of a unique class reference so that two objects with
the same name cannot clash. Imagine that you have an application that
allows remote clients to call Web services in your Customers.Customer
object. If that remote client has a local reference to its own version of an
object named Customers.Customer, there will be some major problems for
that remote client. Microsoft recommends that each developer create at
least two unique namespace levels that become the root references for all
their object creations. For example, a much better reference to my applica-
tion’s “Customer class” might look something like this:

“JoesGarage.GlennCook.SimpleCSharp.ASPWebServiceApp.Customers.Customer”

Runtime Hosts
EXAMPLE The last component in the framework that at least deserves an honorable
mention as a “main component” (especially in this book) is a .NET runtime
02 71465_CH01 11/30/01 10:13 AM Page 11

The .NET Framework 11

host. A runtime host is an application that loads the .NET runtime into its
process. ASP.NET is an example of an application that loads the runtime
into its process for its Web-related services. Internet Explorer is another
example of a runtime host allowing us to download and execute managed
code within its processes. The last runtime host component included in the
framework is shell executables. This piece is actually what calls the .NET
runtime from your operating system when you want to start a .NET appli-
cation. It will also transfer the control of the .NET application from your
system to the runtime.

The Common Language Runtime: A New Interpretation


of Older Technology
The Common Language Runtime has many similarities to the runtime
environment that executes Java applications. You’ll learn later on that
there are just as many differences as there are similarities, but it provides
a good frame of reference for learning about a managed code execution
environment.
To understand how the runtime works, let’s discuss it in terms of an imagi-
nary Web Service application you have just finished coding within Visual
Studio .NET. VS .NET will handle all the dirty details of what needs to be
passed to the appropriate compiler for your code. In earlier versions of
Visual Studio, each language had its own similar-looking IDE, but was a
separate application. In VS .NET, you have one unified development envi-
ronment that can call a number of different languages’ compilers.
Alternatively, you can pass these specific command-line arguments to the
compiler on your own using the appropriate syntax at the command-line
prompt. This will involve a bit more research and studying on your part,
but if you insist on this approach, at least do yourself a favor and download
an evaluation version of VS .NET. If nothing else, the evaluation version
will help you learn what it will pass to the compiler along with your code.
In order to compile a simple C# application, a command line call to the
compiler might look like:

“c:/>csc.exe simpleCSharp.cs”

Each programming language has its own compiler. Every one of these com-
pilers must adhere to a common set of strict rules found at the core of the
EXAMPLE CLR. These strict rules ensure that each language’s compiler will produce
the same type of compiled code. Even though your compiled .NET applica-
tion will have the same extension as a traditional Win32-based executable
(that is, EXE or DLL), the internal results of the files are completely differ-
ent. A .NET executable is compiled into what could be described as an “exe-
cutable package” that includes Microsoft’s Intermediate Language (MSIL or
02 71465_CH01 11/30/01 10:13 AM Page 12

12 Chapter 1: .NET Overview

IL), metadata, an assembly manifest, and any additional assemblies or files


the application makes reference to. In .NET, your application’s executable is
more commonly referred to as an assembly. An assembly is the compiled
code that you will distribute to clients.
Before we discuss what happens to the assembly when a client launches
the application, let’s take a closer look at the internal components that
make up a .NET assembly.

Intermediate Language and Metadata


Intermediate Language (IL) is .NET’s version of compiled code. Whether
you are compiling an ASP.NET DLL written in COBOL, or a Windows
Forms EXE written in C#, the result is always this common self-describing
intermediate language. IL is a simple text-based syntax that is comple-
mented by a self-describing component called metadata. The combination of
these two technologies gives .NET’s managed runtime the ability to perform
more operations in less time with less overhead.
The similarities between .NET and Java’s managed runtime model will
often draw comparisons with .NET’s intermediate language and Java’s byte
code. This similarity comes from the benefits of a common compiled code
that is capable of running on any machine that supports their respective
runtime environment. In terms of their form and function, however, the two
are completely different. .NET’s compiled code (IL and metadata) offers
some significant advantages over Java’s integer-based byte code compila-
tions.
.NET applications are Just-In-Time compiled a second time into native
machine code. This is the same type of machine language code a 32-bit C++
executable would be compiled into. An assembly’s descriptive text-based
syntax allows the runtime the ability to intelligently compile an application
into the most efficient set of native machine instructions for a given system.
The .NET runtime also gives the developer compilation options to instruct
the runtime to dynamically Just-In-Time (JIT) compile their application to
machine language, or pre-compile everything to native machine code during
installation. For example, if you want to avoid the overhead involved with
JIT compiling, you can instruct the runtime to compile your application to
native machine code during its initial set-up and installation process.
Java applications are compiled into an integer-based syntax that is never
compiled into native machine code. Instead, the Java runtime uses a
process that interprets its byte code compilations dynamically. Since an
interpreter is essentially software that emulates a CPU, there is additional
overhead in supporting this type of design.
02 71465_CH01 11/30/01 10:13 AM Page 13

The .NET Framework 13

In terms of performance differences, a recent benchmark comparison of the


J2EE vs .NET (released by Microsoft while .NET was still in Beta) demon-
strated that .NET greatly outperforms J2EE at almost every level while
using only a fraction of the CPU’s resources that J2EE required.
.NET precompiles its applications into native machine language with the
help of an assembly’s metadata. Metadata is XML that thoroughly
describes the location and purpose of every object, property, argument, dele-
gate, and method within a .NET application’s assembly. Metadata elimi-
nates the overhead associated with interpreting and managing the
unknown. The runtime also uses metadata to validate the accuracy and
purpose of each function to avoid errors, optimize memory management,
and protect the user from malicious attacks.
Figure 1.2 shows the process of compiling an application into an assembly.
While coded primarily in C#, you’ll notice it includes references to files
coded in many other languages.
.NET’s compiled code also addresses something commonly referred to as
“DLL Hell.” In the past, developers would have to tweak and build multiple
versions of their Win32 applications to create compatible executables for
each category of popular system configurations. All it would take to destroy
all your brilliant efforts is for another application to upgrade a shared sys-
tem DLL to a newer version. .NET developers will not have to struggle with
these issues any more, but .NET has costs associated with it that Win32
apps don’t have. In other words, you should not expect your managed .NET
applications to run as quickly as similar unmanaged Win32 applications.
Microsoft’s stance is that IL’s self-describing code will eventually allow the
runtime to compile native code so specific to an end user’s system that it
will easily be able to outperform Win32 applications. And of course,
ASP.NET runs several times faster than classic ASP, so it is by no means
slow.
The true inner beauty and power of every compiled .NET application is its
Metadata. It is a “novel” solution that preserves the benefits of a managed
code environment but uses new technology to overcome the performance
losses associated with it. The idea is that the compiled code should read
like a novel but has no room for interpretation, ambiguity, and assump-
tions: “Nothing but the facts, please.” This enables the CLR to quickly com-
pile (yes, there is a second compilation) and manage the safest and fastest
execution environment possible.
Metadata is really nothing more than XML code that describes the entire
contents of the assembly. When a user starts a .NET application, the run-
time will access the assembly manifest, which is made up of metadata that
02 71465_CH01 11/30/01 10:13 AM Page 14

14 Chapter 1: .NET Overview

Windows Form

Class
assemblies

C# .NET Application
images in VS.NET

X COM+dll

HTML

.NET CODE COMPILER


CSC.EXE
(C# Compiler)

Compiling Assembly

Metadata
IL Code

simpleCsharpAssembly.dll

Figure 1.2: Compiling a .NET application into an assembly.


describes the specific contents of the package. It’s like the table of contents
for a .NET application. The manifest is also the runtime’s main entry point
for gathering and examining the data it needs to begin compiling the
assembly into native machine language. You can also access this informa-
tion via a disassembler included with the framework called ILDASM.EXE.
This tool presents the high-level details of an assembly in a readable and
organized hierarchy that describes the specific details of every object,
02 71465_CH01 11/30/01 10:13 AM Page 15

Summary 15

method, argument, and property in your application. If you haven’t done


your homework, you might think this is Microsoft’s consummate security
blunder. Without digging into the specific details right now, suffice to say
that this is not a blunder, and the intellectual integrity of an application
targeted for the .NET Framework is no more or less vulnerable to hackers
than an executable compiled for any other platform.

The JIT Compiler


Another critical component in the .NET Framework is the JIT (Just-In-
Time) compiler (also known as “the JIT-ter”). This is the piece that actually
compiles the contents of the assembly into machine language. It will not
compile the entire assembly into memory all at once. Its initial responsibil-
ity is to examine the manifest to identify the critical pieces to compile and
load to ensure that the application opens quickly. Beyond that point, the
JIT compiler will only load the pieces of the application that it needs. The
final product of this “just in time” approach is a runtime environment with
more available memory space to process what is being used, faster.
Microsoft believes that this approach will also guarantee that .NET appli-
cations will be able to outperform their much older, unmanaged, and occa-
sionally delinquent cousin, the Win32 executable.
Let’s take a look at components within the Common Language Runtime
that prepare, compile, and manage a .NET application.

Summary
The .NET Framework is the infrastructure that supports an integrated
development and execution platform that allows seamless interoperability
between programs developed in a variety of languages. The framework is
governed by a common yet strict set of standards, which are enforced by the
Common Language Runtime (CLR). These rules are the foundation of
.NET’s multilanguage interoperability.
The output of a compiled .NET executable is called an assembly. An assem-
bly is made up of MSIL code and metadata. This is the package that is
delivered to the end user, which is compiled a second time into native
machine language when the user starts the application. An assembly has a
.DLL extension, but is different from a traditional Windows DLL.
Intermediate Language (IL) is an optimized compiled code developed by
Microsoft that .NET’s “jitter” (JIT) uses to compile into native machine
code.
02 71465_CH01 11/30/01 10:13 AM Page 16

16 Chapter 1: .NET Overview

Common Language Runtime (CLR)

Managed Code Execution

NATIVE MACHINE CODE

Microsoft
JIT COMPILER .net
VERIFIER

LOADER

Metadata
IL Code

XML

ASP.NET Web X
Service coded with
VB.NET and HTML Compiled
source code:
C# Class C++ C# Windows form intermediate
Libraries DCOM dll GUI Language (IL)

Figure 1.3: Compiling an assembly into native machine code for execution
within the Common Language Runtime.

An assembly’s intermediate language contains descriptive XML code that


gives the CLR detailed information about the entire application. It gives
the JIT compiler a virtual road map of your application so that the native
code can provide the runtime with information about shortcuts during rush
hour, the history of the area, unsafe areas to avoid, and when it should put
out the garbage.
• The operating systems and servers that support the framework
• The compiled applications and Web services that will run within the
framework
• The .NET Framework and its Common Language Runtime
02 71465_CH01 11/30/01 10:13 AM Page 17

What’s Next? 17

• New services yet to be invented


• Nonproprietary communication protocols like XML and SOAP for
exchanging data and services

What’s Next?
In the next chapter, we will see how ASP.NET fits into the .NET architec-
ture, what some of its most exciting features are, and how it differs from
classic ASP. By the end of the chapter, if you’re currently building web sites
using ASP, you should be eager to make the jump to ASP.NET and start
taking advantage of all of the benefits it has over ASP.
03 71465_CH02 11/30/01 10:31 AM Page 18
03 71465_CH02 11/30/01 10:31 AM Page 19

2
An Introduction To ASP.NET
Microsoft Active Server Pages (ASP) technology has evolved once more.
This time, the changes Microsoft has made are so great that they have cho-
sen not to make another point release of ASP (to 4.0), but have labeled this
next generation of their Internet technology ASP.NET. ASP.NET (formerly
Next Generation Web Services or ASP+) and the .NET framework will
change the way developers build powerful Internet applications more than
any prior evolution of ASP before it. Although entire books could be written
about the .NET framework (and, as you read this, I’m sure they have been),
we can only cover some of the major points about this new architecture
before jumping into specific ASP.NET examples.
In this chapter you will
• Take a look at a brief history of Active Server Pages (ASP)
• Learn what ASP.NET is
• Compare the benefits ASP.NET with those of “Classic ASP”
03 71465_CH02 11/30/01 10:31 AM Page 20

20 Chapter 2: An Introduction To ASP.NET

Moving to .NET
What is .NET? .NET is Microsoft’s new programming architecture, and is
an effort to unify development so that true language independence can be
achieved. Further, .NET is designed for the disconnected Internet program-
ming model, rather than the traditional two-tier client/server model that
Distributed Component Object Model (DCOM) and other earlier models
supported. ASP.NET is just one piece of this new architecture, and of course
is the focus of this book.
What does ASP.NET do for you, the developer? Well, let’s look at a list of 15
cool new things about ASP.NET as compared to ASP 3.0. This comparison is
not meant to be complete, because this is just an introduction to ASP.NET,
but it should give you a good idea of why ASP.NET is far superior to its pre-
decessor. So, in no particular order, here are some of the major improve-
ments. Don’t worry if there are some items listed that are unclear—we will
cover each point in more detail before the end of the chapter.
• Compiled code, not interpreted
• Separation of code from content
• No more “DLL hell”
• Side-by-side installation
• Real debugging
• Real programming languages
• Real error handling
• Applications can be deployed with XCOPY or FTP
• Applications can be administered with XML-structured configuration
files
• Event-based programming model
• Improved object model
• More integrated functions, such as form validation and integral form
handling
• Web Services
• Great performance enhancements from features like page caching
• Better tools—Visual Studio .NET rules!
03 71465_CH02 11/30/01 10:31 AM Page 21

A Brief History of ASP 21

This chapter will provide a brief look at the background of ASP.NET and
how it has evolved from ASP. I’ll explain the key differences between ASP
3.0 and ASP.NET in an overview fashion, and issues such as migrating
from “classic ASP” to ASP.NET will be covered in later chapters.

A Brief History of ASP


When Active Server Pages was first released in November of 1996, four
years ago as this book is going to press, it provided an easy way to create
dynamic Web pages. Although Common Gateway Interface (CGI) and Perl
were very popular at the time, ASP quickly gained popularity for four rea-
sons. These included ease of data access, ease of page design, Component
Object Model (COM) interoperability, and a relatively flat learning curve for
many programmers already familiar with Visual Basic.
For more information about the origins of ASP, originally code-named
Denali, see http://msdn.microsoft.com/library/periodic/period96/
Denali.htm.

First, if ASP had not been released with ActiveX Data Objects (ADO), it
most likely would not have gained in popularity as quickly as it did. ADO
replaced Remote Data Objects (RDO) and later Data Access Objects (DAO)
as Microsoft’s preferred method of accessing databases, and it provided a
simple, straightforward object model.
Second, with the release of ASP 1.0 came the first Microsoft Visual Studio
application suite, which includes Visual InterDev 1.0. This tool provided
many features, especially for a 1.0 product, and took advantage of
Microsoft’s FrontPage Server Extensions (FPSE) to allow easy maintenance
of Web sites without the need for a separate FTP client. Intellisense for
COM and built-in ASP objects as well as a data access control made this a
very popular editor despite its shortcomings, such as its Graphical User
Interface (GUI) editor, which relied on an early version of FrontPage.
It is probably safe to say that if it were not for ASP, the third-party compo-
nent market would not be the multimillion dollar per year industry that it
is today. Certainly this was not the only factor, as third-party controls for
Visual Basic predated the COM revolution, but in my opinion, ASP and
COM have allowed some businesses to become very profitable by selling
pre-packaged components for use on web servers. The ability to purchase
off-the-shelf components and plug them into a Web site simply did not exist
for all but the most skilled of programmers prior to the release of ASP 1.0.
By bringing this capability to the masses, ASP opened up an entirely new
market for component vendors, who continue to provide powerful off-the-
shelf tools that are easily integrated into ASP applications.
03 71465_CH02 11/30/01 10:31 AM Page 22

22 Chapter 2: An Introduction To ASP.NET

The fourth feature of ASP that sparked its popularity was its use of
VBScript as its default language. This allowed the many programmers who
were already familiar with Visual Basic to quickly jump into ASP program-
ming with minimal learning required. For the many programmers familiar
with JavaScript, or the syntactically similar C, JScript was offered as well.
In fact, Microsoft provided the ability to use other third-party languages as
well, and it wasn’t long before one could write ASP code in Perl.
As cool as it was, ASP 1.0 had some significant limitations. One major limi-
tation for anyone working with COM components was that the Web server
needed to be restarted whenever a Dynamic Link Library (DLL) needed to
be updated (A COM object is stored as a .DLL file). Other security and per-
formance issues were addressed, but the largest improvements from ASP
1.0 to 2.0 came in the form of Microsoft Transaction Server (MTS). ASP 2.0
shipped as part of Internet Information Server (IIS) 4.0 and MTS 1.0
shipped as part of the free Windows NT 4 Option Pack.
With IIS 4.0, Microsoft introduced the new Microsoft Management Console
(MMC), which was used to administer both IIS 4.0 and MTS. MTS made
life much easier for anyone developing or using COM components. It han-
dled installation and uninstallation of the components, alleviating the need
to restart the Web service (or often the server itself), and also removed a lot
of the burden of handling transactions from the developer. In addition, it
acted as an object broker, effectively caching object instances and brokering
them out on request. This technique led to the current focus on “stateless”
components because this was necessary for such object reuse to be effective.
In addition, newer versions of ADO further enhanced developers’ abilities to
work with remote data, using new techniques like XML streams, among
other things.
In February 2000, Microsoft released IIS 5.0 with Windows 2000. With IIS
5.0, ASP was in version 3.0, and MTS was replaced with COM+ services.
COM+ essentially combined the functionality of MTS with message queuing
services, and ASP gained some additional functionality, including a few
more methods and intrinsic object properties. On the whole, the major dif-
ferences between programming in ASP 2.0 and ASP 3.0 lay in the support-
ing services like COM+ more than in the language itself. Anyone who could
write VBScript in ASP 1.0 with Visual InterDev 1.0 would still be perfectly
at home using IIS 4.0 or IIS 5.0. This simply is not the case with ASP.NET.
Microsoft employees Mark Anders and Scott Guthrie began developing
what would become ASP.NET in early January of 1998. At this time, ASP
was just a year old, but some of its limitations were already quite evident.
03 71465_CH02 11/30/01 10:31 AM Page 23

Why ASP Developers Need This Book 23

For instance, the restriction to scripting languages and the lack of a compo-
nent model for ASP made it difficult to develop good tools for it. The inter-
spersing of code with output HyperText Markup Language (HTML)
frequently resulted in problems when designers and developers worked
together on the same project. ASP.NET was designed from the start to
address the limitations of ASP and overcome them.
Mark and Scott chose to build ASP.NET, then called ASP+, on the Next
Generation Web Services (NGWS) Runtime that was then in development.
NGWS, which would become .NET, provided a rich set of programming
libraries, and would soon include the new language C#, in which ASP.NET
itself is written. At this time, ASP.NET has been in development for over
three years, and Microsoft’s focus with this product remains on these
priorities:
• Factored design. ASP.NET is written as a set of modular compo-
nents that can be replaced or extended as needed.
• Scalability. Great efforts were made to build a highly scalable model,
especially with regard to maintaining state.
• Availability. ASP.NET has been designed to intelligently detect
crashes, memory leaks, and deadlocks and to recover from these
events gracefully.
• Performance. ASP.NET takes advantage of compiled languages and
early binding to improve performance, and also features extensive
caching support.
• Tools integration. Microsoft’s goal is to make building a Web site as
easy as building a form using Visual Basic. Visual Studio .NET is the
first tool to provide this functionality, but the other vendors are sure
to follow with their own toolsets.

Why ASP Developers Need This Book


If you have read the last couple of pages, you understand that the evolution
of ASP has primarily involved changes in peripheral services, not the core
ASP engine itself. ASP.NET, previously known as Next Generation Web
Services, is a truly different creature than ASP, and will require you to
rethink how you go about designing and building Internet applications.
Why should you bother to learn this new way of doing things when you
already build great applications using classic ASP? What are the benefits
that make it worth it? Or, if you’re just getting into web development, why
should you choose ASP.NET instead of the more established Active Server
Pages technology?
03 71465_CH02 11/30/01 10:31 AM Page 24

24 Chapter 2: An Introduction To ASP.NET

Benefits of ASP.NET over ASP


ASP.NET and the .NET Framework feature many advantages over classic
ASP. ASP.NET outperforms ASP, and is more robust, secure, and scalable.
It has better tools, allowing programmers to be more productive, and it will
support many different languages, allowing developers to use whichever
one they prefer. ASP.NET will also be easier to manage and deploy. Let’s
expand on our list of advantages of ASP.NET over ASP that were men-
tioned at the start of this chapter.

ASP.NET Is Compiled, not Interpreted


Compiled programs run faster than interpreted ones. Thus, ASP.NET,
which is compiled, runs faster than classic ASP, which is interpreted. Each
page is compiled the first time it is requested, and then the compiled code
of the page is kept until that page is changed or the application is
restarted. Optionally, files can be precompiled at deployment time, to
reduce latency when pages are first accessed.

Separation of Code from Content


ASP.NET will allow true separation of code from presentation, which will
allow graphic designers and programmers to work together with less frus-
tration and time spent merging pages’ looks with their functionality. This is
done through the use of “code behind” pages, which are referenced using a
page directive in the header of the page with the presentation code.

No More “DLL Hell”


Users and developers of COM components have come to refer to the prob-
lems with COM deployment as “DLL Hell.” This means that installing or
moving COM components often breaks dependent applications without
warning. Otherwise stable applications are frequently broken when a new
application updates an existing component. “DLL Hell” exists because the
COM protocol requires that components do not change the interfaces they
expose, and so any time a component’s interface changes, it gets a new
identifier that basically makes it a new version of the component. Programs
that relied on one version of a component are frequently broken when they
try to communicate with a newer version of that component. If you have
ever installed a new program on your computer only to find that some of
your other programs no longer work afterward, you have experienced “DLL
Hell.”
With ASP.NET, components don’t have to be shared across the server, but
can be placed with individual applications. Also, components are kept with
03 71465_CH02 11/30/01 10:31 AM Page 25

Benefits of ASP.NET over ASP 25

the application, and the entire application can be moved using simple file
copying. No registry changes or dealing with MTS/COM+ is necessary! This
makes it very easy to maintain an ASP.NET application remotely, such as
through a Web hosting provider. Of course, components can still be shared,
but that decision is now left to the developer or administrator.

Side-by-Side Installation
If you’re not sure you’re ready to migrate your production applications to
ASP.NET yet, don’t worry. The new services and features can be installed
and running in parallel with your existing classic ASP applications (on IIS
4 or 5). In fact, they can share the same folder structure—all that you need
do to migrate each file (after you’ve made it utilize the new features of
ASP.NET) is change the file extension from .asp to .aspx (and of course
update your links to this file accordingly). You will literally be able to
migrate your applications a page at a time.

Real Debugging
ASP.NET features easier debugging than did Classic ASP (which isn’t say-
ing much). One simple addition is a trace command that is only compiled
into the running code when a compile flag is set. No need to build your own
debugging code using if-then and Response.Write. Also, with Visual Studio
.NET, you can step through your ASP.NET code, your include files and Web
controls, and your .NET components, even if each of these uses a different
programming language, without being on the server. It is real debugging,
just as with any other Visual tool!

Real Programming Languages


Although ASP supports several scripting languages, ASP.NET (and in fact
the .NET Framework) will support any language that can be compiled to its
intermediate language (IL) format, which at the time of printing includes
over 16 different languages, including Ada, APL, COBOL, C#, Eiffel,
Haskell, Jscript, ML, Oberon, OZ, Pascal, Perl, Python, Scheme, Smalltalk,
VB, and others. Similar to Java (don’t tell anyone), ASP.NET languages are
compiled to a standard format (the Intermediate Language, or IL) that the
.NET architecture then compiles and executes with the Common Language
Runtime (CLR). Note that there are quite a few differences between the
implementation of .NET and Java, but they are beyond the scope of this
book to cover. Microsoft .NET’s language independence means that develop-
ers can use whatever programming language they feel most comfortable
with and won’t need to learn a new language to learn ASP.NET.
03 71465_CH02 11/30/01 10:31 AM Page 26

26 Chapter 2: An Introduction To ASP.NET

Real Error Handling


ASP.NET features better error handling, including the ability to send all
programming errors to a single error handler page, transferring all of the
page’s attributes (like Request and other variables) as well. Having a cen-
tral location to manage errors is a vast improvement over having to check
for errors every few lines of VBScript and write a custom error handler for
each case.
Further, Visual Basic.NET now supports the Try...Catch structure familiar
to Java and JavaScript programmers. Although On Error Resume Next is
still supported, it is not recommended and should be replaced with
Try...Catch blocks, which offer greater flexibility and better cross
language compatibility.

Directory-Based Deployment
Migrating an ASP application from one server to another is a daunting
task. FrontPage extensions, COM components, and Web settings are all
separate from the actual files in the directory to be moved. With ASP.NET,
you can deploy your application, complete with server settings and compo-
nents, using XCOPY or FTP. This makes backing up a site much easier, and
eliminates a lot of the hassle involved with remote Web hosting.
Once, in the days of MS-DOS, programs were as easy to install, move, and
uninstall as directories were to copy. Moving the files moved the program.
With the advent of Windows and the notorious system registry, this simplic-
ity was lost. Now, with .NET, we can once again install entire applications
using nothing more than a file manager or FTP client.

File-Based Application Configuration


Administering the application can be done entirely via XML configuration
files—no need for direct access to the server! Again, this makes remote
maintenance much easier than with classic ASP. And because the configu-
ration files use a standard XML format, you can expand them to include
your own application-specific settings as well, and third-party administra-
tion tools can also be written to manage ASP.NET applications by using
these files. The current beta of Visual Studio .NET does not offer a graphi-
cal means of maintaining these settings, but one is likely to be released in a
later version of VS.NET.

Event-Based Programming Model


ASP pages are simple scripts that begin execution at the top of the file and
continue line by line down the page until the script has completed. By con-
trast, ASP.NET pages feature an event-based programming model, which
Other documents randomly have
different content
Por ella supe lo que había. Llorando me lo contó todo. ¡Pobrecita! Mi
padre había muerto de celos al Juez. Pero nadie sino ella lo había
visto. Y á mí me creían el asesino, porque me habían hallado
corriendo á pie, por las calles del pueblo, á deshoras.
Mi vieja estaba muy afligida. Decía que decían, que me iban á fusilar
y que eso no podía ser, que yo qué culpa tenía.
Yo le dije: mi madrecita, yo quiero salvar á mi padre.
Ella lloraba...
En ese momento entró uno de la partida y dijo:—Ya es hora de
retirarse. Se va á entrar el sol.
Nos abrazamos, nos besamos, lloramos,—mi vieja se fué y yo me
quedé triste como un día sin sol.
Me prometió volver al día siguiente, á ver qué se nos ocurría.
Esto dijo Miguelito, y como quien tiene necesidad de respirar con
expansión para proseguir, suspiró... lágrimas de ternura arrasaron
sus ojos.
Me enterneció.
NOTAS:
[1] Nuestros paisanos le llaman así á la mujer, y viceversa.
XXIX
El gaucho es un producto peculiar de la tierra argentina.—
Monomanía de la imitación.—Continuación de la historia
de Miguelito.—Cuadro de costumbres.—¿Qué es filosofar?

Cada zona, cada clima, cada tierra, da sus frutos especiales. Ni la


ciencia, ni el arte, inteligentemente aplicados por el ingenio humano
alcanzan á producir los efectos químico-naturales de la generación
espontánea.
Las blancas y perfumadas flores del aire de las islas Paranaenses; las
esbeltas y verdes palmeras de Morería; los encumbrados y robustos
cedros del Líbano; los banianos de la India, cuyos gajos cayendo
hasta el suelo, toman raíces, formando vastísimas galerías de fresco
y tupido follaje, crecen en los invernáculos de los jardines zoológicos
de Londres y París. ¿Pero cómo? Mustios y sin olor aquéllos, bajas y
amarillentas éstas; enanos, raquíticos los unos; sin su esplendor
tropical los otros.
Lo mismo en esa bella planta indígena, que se desarrolla del interior
al exterior; que vive de la contemplación y del éxtasis, que canta y
que llora, que ama y aborrece, que muere en el presente para poder
vivir en la posteridad.
El aire libre, el ejercicio varonil del caballo, los campos abiertos como
el mar, las montañas empinadas hasta las nubes, la lucha, el
combate diario, la ignorancia, la pobreza, la privación de la dulce
libertad, el respeto por la fuerza; la aspiración inconsciente de una
suerte mejor—la contemplación del panorama físico y social de esta
patria,—produce un tipo generoso, que nuestros políticos han
perseguido y estigmatizado, que nuestros bardos no han tenido el
valor de cantar, sino para hacer su caricatura.
La monomanía de la imitación quiere despojarnos de todo; de
nuestra fisonomía nacional, de nuestras costumbres, de nuestra
tradición.
Nos van haciendo un pueblo de zarzuela. Tenemos que hacer todos
los papeles, menos el que podemos. Se nos arguye con las
instituciones, con las leyes, con los adelantos ajenos. Y es indudable
que avanzamos.
Pero ¿no habríamos avanzado más estudiando con otro criterio los
problemas de nuestra organización é inspirándonos en las
necesidades reales de la tierra?
Más grandes somos por nuestros arranques geniales, que por
nuestras combinaciones frías y reflexivas.
¿Adónde vamos por ese camino?
Á alguna parte, á no dudarlo.
No podemos quedarnos estacionarios, cuando hay una dinámica
social, que hace que el mundo marche y que la humanidad progrese.
¿Pero esas corrientes que nos modelan como blanda cera
dejándonos contrahechos, nos llevan con más seguridad y más
rápidamente que nuestros impulsos propios, turbulentos, confusos, á
la abundancia, á la riqueza, al reposo, á la libertad en la ley?
Yo no soy más que un simple cronista; ¡felizmente!
Me he apasionado de Miguelito, y su noble figura me arranca, á
pesar mío, ciertas reflexiones. Allí donde el suelo produce sin
preparación ni ayuda una alma tan noble como la suya, es permitido
creer que nuestro barro nacional empapado en sangre de hermanos,
puede servir para amasar sin liga extraña algo como un pueblo con
fisonomía propia, con el santo orgullo de sus antepasados, de sus
mártires, cuyas cenizas descansan por siempre en frías é ignoradas
sepulturas.
Miguelito siguió hablando.
—Al día siguiente vino mi madre, trayéndome una olla de
mazamorra, una caldera, hierba y azúcar; hizo ella misma el fuego
en el suelo, calentó agua y me cebó mate.
La Dolores le había mandado una platita con la peona, diciéndole
que ya sabía que andábamos en apuros; que no tuviese vergüenza,
que la ocupara si tenía alguna necesidad.
Mientras tanto, mi mujer propia no parecía. Vea, mi Coronel, lo que
es casarse uno de mala gana, por la plata, como lo hacen los ricos.
La peona de la Dolores le contó á mi madre, que la niña estaba
enferma, y le dió á entender de qué, y que yo debía ser el
malhechor.
Mi vieja me echó un sermón sobre esto. Me recordó los consejos que
yo nunca quise escuchar, porque así son siempre los hijos, y acabó
diciendo redondo: «Y ahora ¿cómo vas á remediar el mal que has
hecho?»
Me dió mucha vergüenza, mi Coronel, lo que mi madre me dijo;
porque me lo decía mucho mejor de lo que yo se lo voy contando y
con unos ojos que relumbraban como los botones de mi tirador.
¡Pobre mi vieja! Como ella no había hecho nunca mal á nadie, y la
había visto criarse á la Dolores, le daba lástima que se hubiese
desgraciado.
¡Siquiera no te hubieses casado! me decía á cada rato.
Yo suspiraba; nada más se me ocurría. ¡El hombre se pone tan bruto
cuando ve que ha hecho mal!
Una caldera llenita me tomé de mate y toda la mazamorra, que
estaba muy rica. Mi madre pisaba el maíz como pocas y lo hacía
lindo.
Me curó después las heridas con unos remedios que traía; eran
yuyos del cerro.
Después, de un atadito sacó una camisa limpia y unos calzoncillos y
me mudé.
Me armó cigarros como para toda la noche, nos sentamos en frente
uno de otro, nos quedamos mirándonos un largo rato, y cuando
estaba para irse, se presentó el que le llevaba la pluma al Juez con
unos papeles bajo el brazo y dos de la partida.
Le mandaron á mi madre que saliera y tuvo que irse.
El Juez me leyó todas mis declaraciones y una porción de otras
cosas, que no entendí bien. Por fin me preguntó que si confesaba
que yo era el que había muerto al otro Juez.
Me quedé suspenso, podían descubrir á mi padre y yo quería
salvarlo.
¿Para qué es un hijo, mi Coronel, no le parece?
—Tienes razón—le contesté.
Él prosiguió:
—No se muere más que una vez, y alguna vez ha de suceder eso.
El escribano me volvió á preguntar que qué decía. Le contesté, que
yo era el que había muerto al otro.
—¿Por qué?—me dijo.
Me volví á quedar sin saber qué contestar.
El escribano me dió tiempo.
Pensando un momento se me ocurrió decir, que porque en unas
carreras, siendo él rayero, sentenció en contra mía y me hizo perder
la carrera del gateado overo que era un pingo muy superior que yo
tenía. Y era cierto, mi Coronel, fué una trampa muy fiera que me
hicieron, y desde ese día ya anduvimos mal mi padre y yo; porque la
parada había sido fuerte y perdimos tuitito cuanto teníamos.
Después me preguntó, que si alguien me había acompañado á hacer
la muerte, y le contesté que no; que yo solo lo había hecho todo,
que no tenían que culpar á naides.
Que qué había hecho con la plata que tenía el Juez en los bolsillos.
Le dije que yo no había tocado nada.
Cuando menos los mismos de la partida lo habían saqueado, como
lo suelen hacer. Es costumbre vieja en ellos, y después le achacan la
cosa al pobre que se ha desgraciado.
No me preguntó nada más, y se fué, y me volvieron á poner
incomunicado, y de esa suerte me tuvieron una infinidad de días.
Ni con mi madre me dejaban hablar. Pero ella iba todos los días una
porción de veces á ver cuándo se podría y á llevarme que comer.
Yo me aburría mucho de la prisión y estaba con ganas de que me
despacharan pronto, para no penar tanto; porque las heridas se
habían empeorado con la humedad del cuarto, y porque las
sabandijas no me dejaban dormir, ni de día ni de noche.
Aquello no era vida.
Volvió otro día el escribano y me leyó la sentencia.
Me condenaba á muerte, vea lo que es la justicia, mi Coronel. ¡Y
dicen que los doctores saben todo! ¿Y si saben todo, cómo no
habían descubrido que no era el asesino del Juez aunque lo hubiera
confesado? ¡Y muchos que después de la patriada de Caseros, no
hablan sino de la Constitución!
Será cosa muy buena. Pero los pobres somos siempre pobres, y el
hilo se corta por lo más delgado.
Si el Juez me hubiera muerto á mí en de veras, ¿á que no lo habían
mandado matar?
He visto más cosas así, mi Coronel, y eso que todavía soy
muchacho.
El escribano me dejó solo.
Pasé una noche como nunca.
Yo no soy miedoso; ¡pero se me ponían unas cosas tan tristes! ¡tan
tristes! en la cabeza, que á veces me daba miedo la muerte.
Pensaba, pensaba en que si yo no moría moriría mi padre, y eso me
daba aliento. ¡El viejo había sido tan bueno y tan cariñoso conmigo!
Juntos habíamos andado trabajando, compadreando, comadreando
en jugadas y en riñas. Cómo no le había de querer, hasta perder la
vida por él—la vida, que, al fin, cualquier día la rifa uno por una
calaverada, ó en una trifulca, en la que los pobres salen siempre
mal.
Qué ganas de tener una guitarra tenía, mi Coronel.
En cuanto me volvieron á poner comunicado fué lo primerito que le
pedí á mi madre que llevara. Me la llevó y cantando me lo pasaba.
Los de la partida venían á oirme todos los días, y ya se iban
haciendo amigos míos. Si hubiera querido fugarme me fugo. Pero
por no comprometerlos no lo hice. El hombre ha de tener palabra, y
ellos me decían siempre: no nos vaya á comprometer, amigo.
Siempre que mi vieja iba á visitarme, me lo repetían; y el centinela
se retiraba y me dejaba platicar á gusto con ella.
Mi madre no sabía nada todavía de que me hubieran sentenciado, y
yo no lo quería decir, porque la veía muy contenta creyendo que me
iban á largar, desde que nada se descubría, y no la quería afligir.
Pero como nunca falta quien dé una mala noticia, al fin lo supo.
Se vino zumbando á preguntármelo.
¡En qué apuros me vi, mi Coronel, con aquella mujer tan buena que
me quería tanto!
Cuando le confié la verdad, lloró como una Magdalena.
Sus ojos parecían un arroyo, estuvieron lagrimeando horitas enteras.
De pregunta en pregunta me sacó que yo había confesado ser el
asesino del Juez, por salvar al viejo.
Y hubiera visto, mi Coronel, una mujer que no se enoja nunca,
enojarse, no conmigo, porque á cada momento me abrazaba y me
besaba diciéndome mi hijito, sino con mi padre.
—Él, él no más tiene la culpa de todo, decía, y yo no he de consentir
que te maten por él; todito lo voy á descubrir.
Y de pronto se secó los ojos, cesó de llorar, se levantó y se quiso ir.
—¿Adónde va, mamita?—le dije.
—Á salvar á mi hijo—me contestó.
Iba á salir, le agarré de las polleras, y á la fuerza se quedó.
Le rogué muchísimo que no hiciera nada, que tuviera confianza en la
Virgen del Rosario, de la que era tan devota, que todavía podía
hacer algo y salvarme.
Usted sabe, mi Coronel, lo que es la suerte del hombre. Cuando más
alegre anda, lo refriegan, y cuando más afligido está, Dios lo salva.
Yo he tenido siempre mucha confianza en Dios.
—Y has hecho bien—le dije.—Dios no abandona nunca á los que
creen en él.
—Así es, mi Coronel, por eso esa vez, y después otras me he
salvado.
—¿Y qué hizo tu madre?
—Cedió á mis ruegos, y se fué diciendo: esta noche le voy á poner
velas á la Virgen y ella nos ha de amparar.
Y como la Virgencita del nicho, de que antes le he hablado, mi
Coronel, era muy milagrosa, sucedió lo que mi vieja esperaba, me
salvó.
Miguelito hizo una pausa.
Yo me quedé filosofando.
¡Filosofando!
Sí; filosofar es creer en Dios ó reconocer que el mayor de los
consuelos que tienen los míseros mortales, es confiar su destino á la
protección misteriosa, omnipotente de la religión.
Por eso al grito de los escépticos, yo contesto, como Fenelón:
¡Dilatamini!
Si hay un anankè,[2] hay también quien mira, quien ve, quien
protege, resguarda, ama y salva á sus criaturas, sin interés.
Cuando me arranquéis todo, si no me arrancáis esa convicción
suave, dulce, que me consuela y me fortalece, ¿qué me habréis
arrancado?
NOTAS:
[2] ἀνάγκη en griego: fatalidad.
XXX
Mi vademécum y sus méritos.—En qué se parece Orión á
Roqueplán.—Dónde se aprende el mundo.—Concluye la
historia de Miguelito.

Quiero empezar esta carta ostentando un poco mi erudición á la


violeta.
Yo también tengo mi vademécum de citas—es un tesoro como
cualquier otro.
Pero mi tesoro tiene un mérito. No es herencia de nadie. Yo mismo
me lo he formado.
En lugar de emplear la mayor parte del tiempo en pasar el tiempo,
me he impuesto ciertas labores útiles.
De ese modo, he ido acumulando, sin saberlo, un bonito capital,
como para poder exclamar cualquier día: anche io son pittore.
Mi vademécum tiene, á más del mérito apuntado, una ventaja. Es
muy manuable y portátil. Lo llevo siempre en el bolsillo.
Cuando lo necesito, lo abro, lo hojeo y lo consulto en un verbo.
No hay cuidado que me sorprendan con él en la mano, como á esos
literatos cuyo bufete es una especie de sancta sanctórum.
¡Cuidado con penetrar en el estudio vedado sin anunciarlos cuando
están pontificando!
¡Imprudentes!
¡Os impondríais de los misteriosos secretos!
¡Le arrancaríais á la esfinge el tremendo arcano!
¡Perderíais vuestras ilusiones!
Veríais á vuestros sabios en camisa, haciéndose un traje pintado con
las plumas de la ave silvana, de negruzcas alas, de rojo pico y pies,
de grandes y negras uñas.
Yo no sé más de lo que está apuntado en mi vademécum por índice
y orden cronológico.
No es gran cosa. Pero es algo.
Hay en él todo.
Citas ad hoc, en varios idiomas que poseo bien y mal, anécdotas,
cuentos, impresiones de viaje, juicios críticos sobre libros, hombres,
mujeres, guerras terrestres y marítimas, bocetos, esbozos, perfiles,
siluetas. Por fin, mis memorias hasta la fecha del año del Señor que
corremos, escritas en diez minutos.
Si yo diera á luz mi vademécum no sería un librito tan útil como el
almanaque. Sería, sin embargo, algo entretenido.
Yo no creo que el público se fastidiaría leyendo, por ejemplo:
¿Qué puntos de contacto hay entre Epaminondas, el municipal de
Tebas, como lo llamaba el demagogo Camilo Desmoulins, y don
Bartolo?
¿Qué frac llevaba nuestro actual Presidente cuando se recibió del
poder; en qué se parece su cráneo insolvente de pelo á la cabeza de
Sócrates?
¿En qué se parece Orión á Roqueplán? este Orión, de quien sacando
una frase de mi vademécum,—ajena por supuesto,—puede decirse
que es la personalidad porteña más porteña, el hombre y el escritor
que tiene á Buenos Aires en la sangre, ó mejor dicho una
encarnación andante y pensante de esta antigua y noble ciudad; que
en este océano de barro, no hay un solo escollo que él no haya
señalado; que en los entretelones ha aprendido la política, que como
periodista y hombre á la moda, ha enriquecido la literatura de la
tierra, á los sastres y sombrereros; que las cosas suyas, después de
olvidadas aquí, van á ser cosas nuevas en provincias; que no habría
sido el primer hombre en Roma la brutal, pero que lo habría sido en
Atenas la letrada; que conoce á todo el mundo y á quien todo el
mundo conoce; que se hace aplaudir en Ginebra, que se hace
aplaudir en Córdoba la levítica, hablando con la libertad herética de
un francmasón; que se hace aplaudir en el Rosario, la ciudad
californiana, á propósito de la fraternidad universal; que se hace
aplaudir en Gualeguaichú, disertando en tiempos de Urquiza, sobre
la justicia y los derechos inalienables del ciudadano; que puede ser
profeta en todas partes ed altri siti, menos... iba á decir en su tierra;
que no ha podido ser municipal en ella, que hoy cumple treinta y
ocho años, y á quien yo saludo con el afecto íntimo y sincero del
hermano en las aspiraciones y en el dolor, aunque digan que esto es
traer las cosas por los cabellos.
Sí, Orión amigo, yo te deseo, y tú me entiendes,—«la fuerza de la
serpiente y la prudencia del león»,—como diría un Bourgeois gentil-
homme, cambiando los frenos al entrar en tu octavo lustro, frisando
en la vejez, en ese período de la vida en que ya no podemos tener
juicio, porque no es tiempo de ser locos. ¿Me entiendes?
Y con esto lector, entro en materia.
Lo que sigue es griego, griego helénico, no griego porque no se
entiende.
Ek te biblion kubernetes.
Yo también he estudiado griego.
Monsieur Rouzy puede dar fe, y tú, Santiago amigo, fuiste quien me
lo metió en la cabeza.
Es una de las cosas menos malas que le debo á tu inspiración
mefistofélica.
Tú fuiste quien me apasionó por el hombre del capirotazo.
¿Acaso yo le conocía bien en 1860?
En prueba de que sé griego, como un colegial, ahí va la traducción
de dicho anónimo:
«No se aprende el mundo en los libros».
Aquí era donde quería llegar.
Los circunloquios me han demorado en el camino.
Siento tener que desagradecer á mi ático amigo Carlos Guido, cuyo
buen gusto literario los abomina. Sírvame de excusa el carácter
confidencial del relato.
Sí, el mundo no se aprende en los libros; se aprende observando,
estudiando los hombres y las costumbres sociales.
Yo he aprendido más de mi tierra yendo á los indios Ranqueles, que
en diez años de despestañarme, leyendo opúsculos, folletos,
gacetillas, revistas y libros especiales.
Oyendo á los paisanos referir sus aventuras,—he sabido cómo se
administra la justicia, cómo se gobierna, qué piensan nuestros
criollos de nuestros mandatarios y de nuestras leyes.
Por eso me detengo más de lo necesario quizá en relatar ciertas
anécdotas, que parecerán cuentos forjados para alargar estas
páginas y entretener al lector.
¡Ojalá fuera cuento la historia de Miguelito!
Desgraciadamente ha pasado tal cual la narro, y si fija la atención un
momento, es porque es verdad. Tiene ésta un gran imperio hasta
sobre la imaginación.
Miguelito siguió hablando así:
—Las voces que andaban era que pronto me fusilarían, porque iba á
haber revolución y me podía escapar.
¡Figúrese cómo estaría mi madre, mi Coronel! Todo se le iba en velas
para la Virgen.
Día á día me visitaba, pidiéndome que no me afligiera, diciéndome
que la Virgen no nos había de abandonar en la desgracia, que ella
tenía experiencia y que más de una vez había visto milagros.
Yo no estaba afligido sino por ella.
Quería disimular. ¡Pero qué! era muy ducha y me lo conocía.
Usted sabe, mi Coronel, que los hijos por muy ladinos que sean no
engañan á los padres, sobre todo á la madre.
Vea si yo pude engañar á mi vieja cuando entré en amores con la
Dolores.
¡Qué había de poder!
En cuanto empezó la cosa me lo reconoció, y me mandó que me
fuera con la música á otra parte.
Bien me arrepiento de no haber seguido su consejo.
La Dolores no hubiera padecido tanto como padeció por mí.
Pero los hijos no seguimos nunca la opinión de nuestros padres.
Siempre creemos que sabemos más que ellos.
Al fin nos arrepentimos.
Pero entonces ya es tarde.
—Nunca es tarde cuando la dicha es buena—le interrumpí.
Suspiró y me contestó:
—¡Qué! mi Coronel, hay males que no tienen remedio.
—¿Y has vuelto á saber de la Dolores?—le pregunté.
—Sí, mi Coronel—me contestó,—se lo voy á confesar porque usted
es hombre bueno, por lo que he visto y las mentas que les he oído á
los muchachos que vienen con usted.
—Puedes tener confianza en mí—repuse.
Y él prosiguió:
—Siempre que puedo hacer una escapada, si tengo buenos caballos,
me corto solo, tomo el camino de la laguna del Bagual, llego hacia el
Cuadril, espero en los montes la noche. Paso el Río 5.º, entro en
Villa de Mercedes, donde tengo parientes, me quedo allí por unos
días, me voy después en dos galopes al Morro, me escondo en el
Cerro, en lo de un amigo, y de noche visito á mi vieja y veo á la
Dolores que viene á casa con la chiquita.
—¿Entonces tuvo una hija?—le dije.
—Sí, mi Coronel—me contestó.—¿No le conté antes que nos
habíamos desgraciado?
—¿Y á tu mujer no la sueles ver?
—¡Mi mujer!—exclamó,—lo que hizo fué enredarse con un
estanciero.
Y dice la muy perra que está esperando la noticia de mi muerte para
casarse. ¡Y que se casaban con ella! ¡Como si fuera tan linda!
—¿Y otros paisanos de los que están aquí salen como tú y van á sus
casas?
—El que quiere lo hace; usted sabe, mi Coronel, que los campos no
tienen puertas; las descubiertas de los fortines, ya sabe uno á qué
hora hacen el servicio, y luego, al frente casi nunca salen.
Es lo más fácil cruzar el Río 5.º y la línea, y en estando á retaguardia
ya está uno seguro, porque ¿á quién le faltan amigos?
—Entonces, constantemente estarán yendo y viniendo de aquí para
allá.
—Por supuesto. Si aquí se sabe todo.
Los Videla, que son parientes de don Juan Saa, cuando les da la
gana, toman una tropilla; llegan á la Jarilla, la dejan en el monte, y
con caballo de tiro se van al Morro, compran allí lo que quieren, ellos
mismos á veces, en las tiendas de los amigos y después se vuelven
con cartas para todos.
Algunas veces suelen llegar á Renca, que ya ve donde queda, mi
Coronel.
Á medida que Miguelito hablaba, yo reflexionaba sobre lo que es
nuestro país; veía la complicidad de los moradores fronterizos en las
depredaciones de los indígenas y el problema de nuestros odios, de
nuestras guerras civiles y de nuestras persecuciones, complicado con
el problema de la seguridad de las fronteras.
Le escuchaba con sumo interés y curiosidad.
Miguelito prosiguió:
—El otro día cuando usted llegó, mi Coronel, los Videla habían
andado por San Luis; vinieron con la voz de que usted y el general
Arredondo estaban en la Villa de Mercedes, y diciendo que por allí se
decía que ahora sí que las paces se harían.
Deseando conocer el desenlace de la historia de los amores de
Miguelito, le dije:
—¿Y la Dolores vive con sus padres?
—Sí, mi Coronel—me contestó,—son gente buena y rica, y cuando
han visto á su hija en desgracia no la han abandonado; la quieren
mucho á mi hijita. Si algún día me puedo casar ellos no se han de
oponer, así me lo ha dicho la Dolores.
¡Pero cuándo se muere la otra! Luego yo no puedo salir de aquí
porque la justicia me agarraría y mucho más del modo cómo me
escapé.
—¿Y cómo te escapaste?
—Seguía preso. Mi madre vino un día y me dijo:
Dice tu padre que estés alerta, que él no tiene opinión, que lo han
convidado para una jornada, que se anda haciendo rogar á ver si
son espías; que en cuanto esté seguro que juegan limpio se va á
meter en la cosa con la condición de que lo primero que han de
hacer es asaltar la guardia y salvarte; que de no, no se mete.
En eso anda. No hay nada concluido todavía. Esta noche han
quedado de ir los hombres y mañana te diré lo que convengan.
Yo lo animo á tu padre, haciéndole ver que es el único remedio que
nos queda, y le pongo velas á la Virgen para que nos ayude. Todas
las noches sueño contigo y te veo libre, y no hay duda que es un
aviso de la Virgen.
Al día siguiente volvió mi madre. Todo estaba listo. Lo que faltaba
era quien diera el grito. Decían que don Felipe Saa debía llegar de
oculto á las dos noches, y que él lo daría; que si no venía, como
había un día fijo, lo daría el que fuese más capaz de gobernar la
gente que estaba apalabrada. Don Juan Saa debía venir de Chile al
mismo tiempo.
Bueno, mi Coronel, sucedió como lo habían arreglado.
Una noche al toque de retreta, unos cuantos que estaban esperando
en la orilla del pueblo, atropellaron la casa del Juez, otros la
Comandancia, y mi padre con algunos amigos cargó la Policía.
Para esto, un rato antes ya los habían emborrachado bien á los de la
partida. Algunos quisieron hacer la pata ancha. ¡Pero qué! los de
afuera eran más. Entraron, rompieron la puerta del cuarto en que yo
estaba y me sacaron.
Cuando estuve libre mi padre me dijo: «Dame un abrazo hijo, yo no
te he querido ver porque me daba vergüenza verte preso por mi
mala cabeza, y porque no fueran á sospechar alguna cosa».
Casi me hizo llorar de gusto el viejo; le habían salido pelos blancos,
y no era hombre grande, todavía era joven.
Esa noche el Morro fué un barullo, no se oyeron más que tiros,
gritos y repiques de campana.
Murieron algunos.
Yo lo anduve acompañando á mi padre y evité algunas desgracias
porque no soy matador. Querían saquear la casa de la Dolores, con
achaque de que era salvaje, yo no lo permití, primero me hago
matar.
Por la mañana vino una gente del Gobierno y tuvimos que hacernos
humo. Unos tomaron para la Sierra de San Luis, otros para la de
Córdoba. Mi padre, como había sido tropero, enderezó para el
Rosario. Yo, por tomar un camino tomé otro,—galopé todo el santo
día,—y cuando acordé me encontré con una partida. Disparé, me
corrieron, yo llevaba un pingo como la luz, ¡qué me habían de
alcanzar! Fuí á sujetar cerca del Río 5.º, por esos lados de Santo
Tomé. Entonces no había puesto usted fuerzas allí, mi Coronel; me
topé con unos indios, me junté con ellos, me vine para acá, y acá
me he quedado, hasta que Dios, ó usted, me saquen de aquí, mi
Coronel.
—¿Y tu padre, qué suerte ha tenido, lo sabes?—le pregunté.
—Murió del cólera—me contestó con amargura, exclamando:—
¡pobre viejo! ¡era tan chupador!
Y con esto termina la historia real de Miguelito, que mutatis
mutandis, es la de muchos cristianos que han ido á buscar un asilo
entre los indios.
Ese es nuestro país.
Como todo pueblo que se organiza, él presenta cuadros los más
opuestos.
Grandes y populosas ciudades como Buenos Aires, con todos los
placeres y halagos de la civilización, teatros, clubs, jardines, paseos,
palacios, templos, escuelas, museos, vías férreas, una agitación
vertiginosa—en medio de unas calles estrechas, fangosas, sucias,
fétidas, que no permiten ver el horizonte, ni el cielo limpio y puro,
sembrado de estrellas relucientes,—en las que yo me ahogo,
echando de menos mi caballo.
Fuera de aquí, campos desiertos, grandes heredades, donde vegeta
el proletario en la ignorancia y la estupidez.
La iglesia, la escuela, ¿dónde están?
Aquí el ruido del tráfago y la opulencia que aturde.
Allá, el silencio de la pobreza y la barbarie que estremece.
Allí, todo aglomerado como un grupo de moluscos, asqueroso por el
egoísmo.
Allí, todo disperso, sin cohesión, como los peregrinos de la tierra de
promisión,—por el egoísmo también.
Tesis y antítesis de la vida de una república.
Eso dicen que es gobernar y administrar.
¡Y para lucirse mejor, todos los días clamando por gente, pidiendo
inmigración!
Me hace el efecto de esos matrimonios imprevisores, sin recursos,
miserables, cuyo único consuelo es el de la palabra del verbo,—
creced y multiplicaos.
XXXI
Ojeada retrospectiva.—El valor á media noche, es el valor
por excelencia.—Miedo á los perros.—Cuento al caso.—
Qué es loncotear.—Sigue la orgía.—Epumer se cree
insultado por mí.—Una serenata.

Estábamos en el toldo de Mariano Rosas cuando conocí por primera


vez á Miguelito.
La orgía había comenzado:

«Éste chilla, algunos lloran,


Y otros á beber empiezan,
De la chusma todo al cabo
La embriaguez se enseñorea.»

Los franciscanos comprendiendo que aquello no rezaba con ellos, se


pusieron en retirada, refugiándose en el rancho de Ayala; los
oficiales se habían colocado á distancia de poder acudir en auxilio
mío si era necesario; los asistentes rodeaban la enramada con
disimulo; Camilo Arias, con su aire taciturno, se me aparecía de vez
en cuando como una sombra, diciéndome de lejos con su mirada
ardiente, expresiva, penetrante: por aquí ando yo.
Por bien templado que tengamos el corazón, es indudable que el
silencio, la soledad, el aislamiento y el abandono hacen crecer el
peligro en la medrosa imaginación.
Es por eso que el valor á media noche, es el valor por excelencia.
Las tinieblas tienen un no sé qué de solemne, que suele helar la
sangre en las venas hasta congelarla.
Yo no creo que exista en el mundo un solo hombre que no haya
tenido miedo alguna vez de noche.
De día, en medio del bullicio, ante testigos, sobre todo ante mujeres,
todo el mundo es valiente, ó se domina lo bastante para ocultar su
miedo.
Yo he dicho por eso alguna vez: el valor es cuestión de público.
El hombre que en presencia de una dama hace acto de irresolución
puede sacar patente de cobarde.
Yo tengo un miedo cerval á los perros, son mi pesadilla; por donde
hay, no digo perros, un perro, yo no paso por el oro del mundo si
voy solo, no lo puedo remediar, es un heroísmo superior á mí mismo.
En Rojas, cuando era capitán, tenía la costumbre de cazar.
De tarde tomaba mi escopeta y me iba por los alrededores del
pueblito.
En dirección al bañado, donde los patos abundaban más, había un
rancho.
Inevitablemente debía pasar por allí si quería ahorrarme un rodeo
por lo menos de tres cuartos de legua.
Pues bien. Venirme la idea de salir y asaltarme el recuerdo de un
mastín que habitaba el susodicho rancho, era todo uno.
Desde este instante formaba la resolución valiente de medírmelas
con él.
Salía de mi casa y llegaba al sitio crítico, haciendo cálculos
estratégicos, meditando la maniobra más conveniente, la actitud
más imponente, exactamente como si se tratara de una batalla en la
que debiera batirme cuerpo á cuerpo.
En cuanto el can diabólico me divisaba, me conocía; estiraba la cola,
se apoyaba en las cuatro patas dobladas, quedando en posición de
asalto, contraía las quijadas y mostraba dos filas de blancos y
agudos dientes.
Eso sólo bastaba para que yo embolsase mi violín. Avergonzado de
mí mismo, pero diciéndome interiormente:—«El miedo es natural en
el prudente,—cambiaba de rumbo, rehuyendo al peligro».
Un día me amonesté antes de salir, me proclamé, me palpé á ver si
temblaba.
Estaba entero, me sentí hombre de empresas, y me dije: pasaré.
Salgo, marcho, avanzo y llego á Rubicón.
¡Miserable! temblé, vacilé, luché, quise hacer de tripas corazón pero
fué en vano.
Yo no era hombre, ni soy ahora, capaz de batirme con perros.
Juro que los detesto, si no son mansos, inofensivos como ovejas,
aunque sean falderos, cuscos ó pelados.
Mi adversario, no sólo me reconoció, sino que en la cara me conoció
que tenía miedo de él.
Maquinalmente bajé la escopeta que llevaba al hombro.
Sea la sospecha de un tiro, sea lo que fuese, el perro hizo una
evolución, tomó distancia y se plantó, como diciendo: descarga tu
arma y después veremos.
¿Habría hecho el perro lo mismo con cualquier otro caminante?
Probablemente no.
Era manso, yo lo averigüé después.
Pero es que yo no le había caído en gracia, y que conociendo mi
debilidad, se divertía conmigo, como yo podía haberlo hecho con un
muchacho.
No hay que asombrarse de esto. La memoria en los animales, á falta
de otras facultades, está sumamente desarrollada.
Cualquier caballo, mula, jumento ó perro, nos aventaja en conocer el
intrincado camino por donde tenemos costumbre de andar.
Los pájaros se trasladan todos los años de un país á otro, emigrando
á más ó menos distancia, según sus necesidades fisiológicas.
Ahí están las golondrinas que, después de larga ausencia vuelven á
la guarida de la misma torre, del mismo techo, del mismo tejado,
que habitaron el año anterior.
Queda de consiguiente fuera de duda que lo que el perro hacía
conmigo, lo hacía á sabiendas. ¡Pícaro perro!
Hubo un momento en que casi lo dominé. ¡Ilusión de un alma
pusilánime!
Al primer amago de carga eché á correr con escopeta y todo; los
ladridos no se hicieron esperar, esto aumentó el pánico, de tal modo,
que el animal ya no pensaba en mí y yo seguía desolado por esos
campos de Dios.
Y sin embargo, si yo hubiera ido en compañía de alguna dama, el
muy astuto no me corre.
Y ella habría huido.
Las mujeres tienen el don especial de hacernos hacer todo género
de disparates, inclusive el de hacernos matar.
Yo me bato con cualquier perro, aunque sea de presa, por una
mujer, aunque sea vieja y fea, si soy su cabaleiro servente.
Otro se suicida por una mujer, con pistola, navaja de barba, veneno
ó arrojándose de una torre. No hay que discutirlo.
Hay héroes porque hay mujeres.
Y es mejor no pensarlo—¿qué sería el hermoso planeta que
habitamos, sin ellas?
La presencia é inmediación de los míos, el orgullo de no dejarme
avasallar, ni sobrepujar por aquellos bárbaros en nada y por nada,
me hacían insistir contra las reiteradas instancias de Mariano Rosas,
en no retirarme.
Mi principal temor era embriagarme demasiado. Á una loncoteada no
le temía tanto.
Loncotear, llaman los indios á un juego de manos, bestial.
Es un pugilato que consiste en agarrarse dos de los cabellos y en
hacer fuerza para atrás, á ver cuál resiste más á los tirones.
Desde chiquitos se ejercitan en él.
Cuando á un indiecito le quieren hacer un cariño varonil, le tiran de
las mechas, y si no le saltan las lágrimas le hacen este elogio: ese
toro.
El toro es para los indios el prototipo de la fuerza y del valor. El que
es toro, entre ellos, es un nene de cuenta.
Los «yapaí, hermano» ¡no cesaban!
Epumer la había emprendido conmigo, y un indiecito Caiomuta, que
jamás quiso darme la mano, so pretexto de que yo iba de mala fe:
¡Winca engañando! salía constantemente de sus labios.
El vino y el aguardiente corrían como agua, derramados por la
trémula mano de los beodos, que ya rugían como fieras, ya lloraban,
ya cantaban, ya caían como piedras, roncando al punto ó
trasbocando, como atacados del cólera.
Aquello daba más asco que miedo.
Todos me trataban con respeto, menos Epumer y Caiomuta.
Tambaleaban de embriaguez.
Epumer llevaba de vez en cuando la mano derecha al cabo de su
refulgente facón, y me miraba con torvo ceño.
Miguelito me decía:
—No se descuide por delante, mi Coronel, aquí estoy yo por detrás.
Cuando rehusaba un yapaí, gruñían como perros, la cólera se
pintaba en sus caras vinosas y murmuraban iracundas palabras que
yo no podía entender.
Miguelito me decía:
—Se enojan porque usted no bebe, mi Coronel; dicen que lo hace
por no descubrir sus secretos con la chupa.
Yo entonces me dirigí á alguno de los presentes y lo invitaba,
diciéndole:
—Yapaí, hermano, y apuraba el cuerno ó el vaso.
Una algazara estrepitosa, producida por medio de golpes dados en la
boca abierta, con la palma de la mano, estallaba incontinenti.
¡¡¡Babababababababababababababababa!!!
Resonaba ahogándose los últimos ecos en la garganta de aquellos
sapos gritones.
Mientras el licor no se acabara, la saturnal duraría.
La tarde venía.
Yo no quería que me sorprendiera la noche entre aquella chusma
hedionda, cuyo cuerpo contaminado por el uso de la carne de
yegua, exhalaba nauseabundos efluvios; regoldaba á todo trapo,
cada eructo parecía el de un cochino cebado con ajos y cebollas.
En donde hay indios, hay olor á asafétida.
Intenté levantarme del suelo para retirarme á la sordina, viendo que
la mayoría de los concurrentes estaba ya achumada.
Epumer me lo impidió.
¡Yapaí! ¡yapaí! me dijo.
¡Yapaí! ¡yapaí! contesté.
Y uno después de otro cumplimos con el deber de la etiqueta.
El cuerno que se bebió él tenía la capacidad de una cuarta.
Una dosis semejante de aguardiente era como para voltear á un
elefante, si estos cuadrúpedos fuesen aficionados al trago.
Medio perdió la cabeza.
Al llevar yo el mío á los labios, me santigüé con la imaginación como
diciendo: Dios me ampare.
Jamás probé brebaje igual. Vi estrellas, sombras de todos colores,
un mosaico de tintes atornasolados, como cuando por efecto de un
dolor agudo apretamos los párpados, y cerrando herméticamente los
ojos la retina ve visiones informes.
Al enderezarse Epumer, yo no sé qué chuscada le dije.
El indio se puso furioso; quiso venírseme á las manos.
Mariano Rosas y otros le sujetaron; me pidieron encarecidamente
que me retirara.
Me negué; insistieron, me negué, me negué tenazmente.
Me hicieron presente que cuando se caldeaba, se ponía fuera de sí,
que era mal intencionado.
—No hay cuidado—fué toda mi contestación.
El indio pugnaba por desasirse de los que le tenían; quería
abalanzarse sobre mí, su mano estaba pegada al facón.
Pataleaba, rugía, apoyaba los talones en el suelo, endurecía el
cuerpo y se enderezaba como galvanizado.
Sus ojos me seguían, los míos no le dejaban.
En uno de los esfuerzos que hizo sacó el facón.
Era una daga acerada de dos filos, con cruz y cabo de plata; y en un
vaivén llegó á ponerse casi sobre mí.
—Cuidado, mi Coronel—me dijo Miguelito, interponiéndose, y
hablándole al salvaje en su lengua con acento dulcísimo.
—¡Cuidado!—gritaron varios.
Yo, afectando una tranquilidad que dejase bien puesto el honor de
mi sangre y de mi raza:
—No hay cuidado—contesté.
El esfuerzo convulsivo supremo, hecho por el indio, agotó el resto de
sus fuerzas hercúleas enervadas por los humos alcohólicos.
Los que le sujetaban, sintiéndole desfallecer abandonaron el cuerpo
á su propia gravedad; cumplióse la inmutable ley:
¡E caddi, come corpo morto cade!
Cesó la agitación.
Queriendo saber qué causa, qué motivo, qué palabras mías pusieran
fuera de sí á mi contendor, pregunté:
—¿Por qué se ha enojado?
—Porque usted le ha llamado perro—dijo uno.
—Es falso—dijo Miguelito en araucano; el Coronel habló de perros;
pero no dijo que Epumer fuera perro.
Nadie respondió.
Efectivamente, en la broma que intenté hacerle á Epumer, por ver si
lo arrancaba á sus malos pensamientos, no sé cómo interpolé el
vocablo perros.
Para los indios, como para los árabes, no había habido insulto mayor
que llamarles perro.
Epumer me entendió mal y se creyó ofendido.
De ahí su rapto de furia.
La noche batía sus pardas alas; los indios ebrios roncaban,
vomitaban, se revolvían por el suelo, hechos un montón, apoyando
éste sus sucios pies en la boca de aquél; el uno su panza sobre la
cara del otro.
Varias chinas y cautivas trajeron cueros de carnero y les hicieron
cabeceras, poniéndolos en posturas cómodas.
Otros se quedaron murmurando con indescriptible é inefable fruición
báquica.
Mariano Rosas me hizo decir con su hombre de confianza, que si
quería darle el resto de aguardiente que le había reservado.
—De mil amores—contesté; y aprovechando la coyuntura que se me
presentaba de abandonar el campo de mis proezas, salí de la
enramada y me dirigí al ranchito en que se habían alojado mis
oficiales.
Entregué el aguardiente.
Me tendí cansado, como si hubiera subido con un quintal en las
espaldas á la cumbre del Vesubio.
¿En qué me tendí?
Sobre un cuero de potro; era el colchón de una mala cama
improvisada con palos desiguales y nudosos.
El sueño no tardó en llevarme al mundo de la tranquilidad pasajera.
Gozaba, cuando una serenata me despertó.
Era un negro, tocador de acordeón, una especie de Orfeo de la
pampa.
Tuve que resignarme á mi estrella, que levantarme y escuchar un
cielito cantado en honor mío.
¡Qué mal rato me dió el tal negro después!
XXXII
El negro del acordeón y la música.—Reflexiones sobre el
criterio vulgar.—Sueño fantástico.—Lucius Victorius
Imperator.—Un mensajero nocturno de Mariano Rosas.—
Se reanuda el sueño fantástico.—Mi entrada triunfal en
Salinas Grandes.—La realidad.—Un huésped á quien no le
es permitido dormir.

El negro no tardó en irse con la música á otra parte. Bendije al cielo.


Como poeta festivo, como payador, no podía rivalizar con Aniceto el
Gallo ni con Anastasio el Pollo.
Ni siquiera era un artista en acordeón.
Yo tengo, por otra parte, poco desarrollado el órgano frenológico de
los tonos, pudiendo decir, como Voltaire: la musique c'est de tous les
tapages le plus supportable.
Es una fatalidad como cualquier otra, que me priva de un placer
inocente más en la vida.
Te contaría á este respecto algo muy curioso, un triunfo de la
frenología, ó en otros términos, la historia de mis padecimientos
infantiles por la guitarra.[3] Y te la contaría á pesar del natural temor
de que me creyesen más malo de lo que soy; porque tengo la
desgracia de ser insensible á la armonía.
Tú sabes, que según las reglas del criterio vulgar, no puede ser
bueno quien no ama la música, las flores, aunque ame muchas otras
cosas que embriagan y deleitan más que ellas.
Hay gentes que de buena fe, creen que el sentimiento estético ó el
arte es inseparable de los hombres de corazón.
Tal persona que ama con locura la música, es, sin embargo, incapaz
de un acto de generosidad.
Tal otra que gastaría cien mil pesos en un auténtico de Rubens, no
haría un sacrificio por el amigo más querido.
Esas gentes viven acariciando dulces errores, lo mismo que los que
subordinan la moral al sentimiento, y hay que dejar á cada loco con
su tema.
Pero semejante página sería demasiado íntima para agregarla aquí.
Me resigno, pues, á suprimirla, substrayéndome á la tentación de
una confidencia personal ajena al asunto jefe.
Apenas me vi libre de quien inhumanamente me había arrancado de
los brazos de Morfeo, volví á tenderme en mi duro y sinuoso lecho.
Poco tardé en dormirme profundamente.
Saboreaba el suave beleño; soñaba que yo era el conquistador del
desierto; que los aguerridos ranqueles, magnetizados por los ecos
de la civilización, habían depuesto sus armas; que se habían
reconcentrado formando aldeas; que la iglesia y la escuela habían
arraigado sus cimientos en aquellas comarcas desheredadas; que la
voz del Evangelio ahogaba las preocupaciones de la idolatría; que el
arado, arrancándole sus frutos óptimos á la tierra, regada con
fecundo sudor, producía abundantes cosechas; que el estrépito de
los malones invasores había cesado, pensando sólo, aquellos
bárbaros infelices, en multiplicarse y crecer, en aprovechar las
estaciones propicias, en acumular y guardar, para tener una vejez
tranquila y legarles á sus hijos un patrimonio pingüe; que yo era el
patriarca respetado y venerado, el benefactor de todos, y que el
espíritu maligno, viéndome contento de mi obra útil y buena,
humanitaria y cristiana, me concitaba á una mala acción, á dar mi
golpe de estado.
¡Mortal! me decía, aprovecha los días fugaces. ¡No seas necio,
piensa en ti, no en la Patria!
La gloria del bien es efímera, humo, puro humo. Ella pasa y nada
queda. ¿No tienes mujer é hijos? Pues bien. ¿No te obedecen y te
siguen, no te quieren y respetan estos rebaños humanos?
Pues bien.
¿No tienes poder, no eres de carne y huesos, no amas el placer?
Pues bien.
Apártate de ese camino, ¡insensato! ¡Imprevisor, loco! ¡Escucha la
palabra de la experiencia, hazte proclamar y coronar emperador!
Imita á Aurelio I. Tienes un nombre romano, Lucius Victorius
Imperator, sonará bien al oído de la multitud.
Yo escuchaba con cierto placer mezclado de desconfianza las
amonestaciones tentadoras; ideaba ya si el trono en que me había
de sentar, la diadema que había de ceñir y el cetro que había de
empuñar, cuando subiera al capitolio, serían de oro macizo, ó de
cuero de potro y de madera de caldén, cuando una voz que conocí
entre sueños llamó á mi puerta diciendo:
—¡Coronel Mansilla!
No contesté de pronto. Reconocí la voz, la había oído hacía poco;
pero no estaba del todo despierto.
—¡Coronel Mansilla! ¡Coronel Mansilla!—volvieron á decir.
Reinaba una profunda obscuridad en el desmantelado rancho donde
me había hospedado; mis oficiales roncaban, como hombres sin
penas; un ruido tumultuoso, sordo, llegaba confusamente hasta la
nocturna morada. Me senté en la cama y paré la oreja, á ver si
volvían á llamar, fijando la vista en un resquicio de la puerta, que era
un cuero de vaca colgado.
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like