Sayfalar

5 Şubat 2011 Cumartesi

Member List


Visual Studio makes it easy for you to interact with controls and classes. When you type a period (.) after
a class or object name, Visual Studio pops up a list of available properties and methods (see Figure 2-16).
It uses a similar trick to provide a list of data types when you define a variable and to provide a list of
valid values when you assign a value to an enumeration.


Visual Studio also provides a list of parameters and their data types when you call a method or
invoke a constructor. This information is presented in a tooltip below the code and is shown as you type.
Because the .NET class library heavily uses function overloading, these methods may have multiple
different versions. When they do, Visual Studio indicates the number of versions and allows you to see
the method definitions for each one by clicking the small up and down arrows in the tooltip. Each time
you click the arrow, the tooltip displays a different version of the overloaded method

Outlining


Outlining allows Visual Studio to “collapse” a subroutine, block structure, or region to a single line. It
allows you to see the code that interests you, while hiding unimportant code. To collapse a portion of
code, click the minus box next to the first line. Click the box again (which will now have a plus symbol) to
expand it You can collapse an entire code file so that it only shows definitions (such as the namespace and
class declarations, member variables and properties, method declarations, and so on), but hides all
other details (such as the code inside your methods and your namespace imports). To get this top-level
view of your code, right-click anywhere in the code window and choose Outlining ➤ Collapse to
Definitions. To remove your outlining and expand all collapsed regions so you can see everything at
once, right-click in the code window and choose Outlining ➤ Stop Outlining.

IntelliSense and Outlining


As you program with Visual Studio, you’ll become familiar with its many time-saving conveniences. The
following sections outline the most important features you’ll use (none of which is new in Visual Studio
2010).

Adding Assembly References


By default, ASP.NET makes a small set of commonly used .NET assemblies available to all web pages.
These assemblies (listed in Table 2-4) are configured through a special machine-wide configuration file.
You don’t need to take any extra steps to use the classes in these assemblies.


If you want to use additional features or a third-party component, you may need to import more
assemblies. For example, if you want to use an Oracle database, you need to add a reference to the
System.Data.OracleClient.dll assembly. To add a reference, select Website ➤ Add Reference (or
Project ➤ Add Reference in a web project). The Add Reference dialog box will appear, with a list of
registered .NET assemblies (see Figure 2-14).
■ Note Visual Studio 2010 has enhanced the Add Reference window to use asynchronous loading. As a result, it
appears much quicker and doesn’t freeze you out while it scans your system for assemblies. However, while these
assemblies are being added to the list, you may find it difficult to select the item you want before it “jumps” to a
new position.


In the Add Reference dialog box, select the component you want to use. If you want to use a
component that isn’t listed here, you’ll need to click the Browse tab and select the DLL file from the
appropriate directory (or from another project in the same solution, using the Projects tab).
If you’re working with a projectless website and you add a reference to another assembly, Visual
Studio modifies the web.config file to indicate the assembly you’re using. Here’s an example of what you
might see after you add a reference to the System.Web.Routing.dll file:


<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly=
"System.Web.Routing, Version=4.0.0.0, Culture=neutral,PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
If you’re working with a web project, and you add a reference to another assembly, Visual Studio
doesn’t need to change the web.config file. That’s because Visual Studio is responsible for compiling the
code in a web project, not ASP.NET. Instead, Visual Studio makes a note of this reference in the .csproj
project file. The reference also appears in the Solution Explorer window under the References node. You
can review your references here, and remove any one by right-clicking it and choosing Remove.
If you add a reference to an assembly that isn’t stored in the GAC (global assembly cache), Visual
Studio will create a Bin subdirectory in your web application and copy the DLL into that directory. (This
happens regardless of whether you’re using project-based or projectless development.) This step isn’t
required for assemblies in the GAC because they are shared with all the .NET applications on the
computer.
If you look at the code for a web-page class, you’ll notice that Visual Studio imports just a few core
.NET namespaces. Here’s the code you’ll see:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

Adding a reference isn’t the same as importing the namespace with the using statement. The using
statement allows you to use the classes in a namespace without typing the long, fully qualified class
names. However, if you’re missing a reference, it doesn’t matter what using statements you include—the
classes won’t be available. For example, if you import the System.Web.UI namespace, you can write
Page instead of System.Web.UI.Page in your code. But if you haven’t added a reference to the
System.Web.dll assembly that contains these classes, you still won’t be able to access the classes in the
System.Web.UI namespace.



The Code Editor


Many of Visual Studio’s handiest features appear when you start to write the code that supports your
user interface. To start coding, you need to switch to the code-behind view. To switch back and forth,
you can use two buttons that are placed just above the Solution Explorer window. The tooltips identify
these buttons as View Code and View Designer. When you switch to code view, you’ll see the page class
for your web page. You’ll learn more about code-behind later in this chapter.
ASP.NET is event-driven, and everything in your web-page code takes place in response to an event.
To create a simple event handler for the Button.Click event, double-click the button in design view.
Here’s a simple example that displays the current date and time in a label:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Current time: " + DateTime.Now.ToLongTimeString();
}
To test this page, select Debug ➤ Start Debugging from the menu. Because this is the first time
running any page in this application, Visual Studio will inform you that you need a configuration file that
specifically enables debugging, and will offer to change your current web.config file accordingly


Click OK to change the web.config configuration file. Visual Studio will then start the integrated test
web server and launch your default browser with the URL set to the current page that’s open in Visual
Studio. At this point, your request will be passed to ASP.NET, which will compile the page and execute it.
To test your event-handling logic, click the button on the page. The page will then be submitted to
ASP.NET, which will run your event-handling code and return a new HTML page with the data

Server Explorer


The Server Explorer provides a tree that allows you to explore various types of services on the current
computer (and other servers on the network). It’s similar to the Computer Management administrative
tool. Typically, you’ll use the Server Explorer to learn about available event logs, message queues,
performance counters, system services, and SQL Server databases on your computer.
The Server Explorer is particularly noteworthy because it doesn’t just provide a way for you to
browse server resources; it also allows you to interact with them. For example, you can create databases,
execute queries, and write stored procedures using the Server Explorer in much the same way that you
would using SQL Server Management Studio, the administrative utility that’s included with the full
version of SQL Server. To find out what you can do with a given item, right-click it. Figure 2-11 shows the
Server Explorer window listing the databases in a local SQL Server and allowing you to retrieve all the
records in the selected table.

Error List and Task List


The Error List and Task List are two versions of the same window. The Error List catalogs error
information that’s generated by Visual Studio when it detects problematic code. The Task List shows a
similar view with to-do tasks and other code annotations you’re tracking. Each entry in the Error List and
Task List consists of a text description and, optionally, a link that leads you to a specific line of code
somewhere in your project.


With the default Visual Studio settings, the Error List appears automatically whenever you build a
project that has errors


To see the Task List, choose View ➤ Task List. Two types of tasks exist—user tasks and comments.
You can choose which you want to see from the drop-down list at the top of the Task List. User tasks are
entries you’ve specifically added to the Task List. You create these by clicking the Create User Task icon
(which looks like a clipboard with a check mark) in the Task List. You can give your task a basic
description, a priority, and a check mark to indicate when it’s complete.

■ Note As with breakpoints, any custom tasks you add by hand are stored in the hidden solution files. This makes
them fairly fragile—if you rename or move your project, these tasks will disappear without warning (or without
even a notification the next time you open the website).


The comment entries are more interesting because they’re added automatically and they link to a
specific line in your code. To try the comment feature, move somewhere in your code, and enter the
comment marker (//) followed by the word TODO (which is commonly referred to as a token tag). Now
type in some descriptive text:
// TODO: Replace this hard-coded value with a configuration file setting.
string fileName = @"c:\myfile.txt"
Because your comment uses the recognized token tag TODO, Visual Studio recognizes it and
automatically adds it to the Task List


To move to the line of code, double-click the new task entry. Notice that if you remove the
comment, the task entry is automatically removed as well.
Three token tags are built-in: HACK, TODO, and UNDONE. However, you can add more. Simply
select Tools ➤ Options. In the Options dialog box, navigate to the Environment ➤ Task List tab. You’ll
see a list of comment tokens, which you can modify, remove, and add to. Figure 2-10 shows this window
with a new ASP comment token that you could use to keep track of sections of code that have been
migrated from classic ASP pages.






Toolbox


The Toolbox works in conjunction with the document window. Its primary use is providing the controls
that you can drag onto the design surface of a web form. However, it also allows you to store code and
HTML snippets.
The content of the Toolbox depends on the current designer you’re using as well as the project type.
For example, when designing a web page, you’ll see the set of tabs described in Table 2-3. Each tab
contains a group of buttons. To view a tab, click the heading, and the buttons will slide into view.

You can customize both the tabs and the items in each tab. To modify the tab groups, right-click a
tab heading, and select Rename Tab, Add Tab, or Delete Tab. To add an item to a tab, right-click the
blank space on a Toolbox tab, and click Choose Items. You can also drag items from one tab group to
another.

Document Window


The document window is the portion of Visual Studio that allows you to edit various types of files using
different designers. Each file type has a default editor. To learn a file’s default editor, simply right-click
that file in the Solution Explorer, and then select Open With from the pop-up menu. The default editor
will have the word Default alongside it.

Solution Explorer


The Solution Explorer is, at its most basic, a visual filing system. It allows you to see the files that are in
the web application directory.
Table 2-2 lists some of the file types you’re likely to see in an ASP.NET web application.
In addition, your web application can contain other resources that aren’t ASP.NET file types. For
example, your web application directory can hold image files, HTML files, or CSS files. These resources
might be used in one of your ASP.NET web pages, or they can be used independently.
Visual Studio distinguishes between different file types. When you right-click a file in the list, a
context menu appears with the menu options that apply for that file type. For example, if you right-click
a web page, you’ll have the option of building it and launching it in a browser window.
Using the Solution Explorer, you can rename, rearrange, and add files. All these options are just a
right-click away. To delete a file, just select it in the Solution Explorer and press the Delete key.


You can also add new files by right-clicking the Solution Explorer and selecting Add ➤ Add New
Item. You can add various different types of files, including web forms, web services, and stand-alone
classes. You can also copy files that already exist elsewhere on your computer (or an accessible network
path) by selecting Add ➤ Add Existing Item. Use Add ➤ New Folder to create a new subdirectory inside
your web application. You can then drag web pages and other files into or out of this directory. Use the
Add ASP.NET Folder submenu to quickly insert one of the folders that has a specific meaning to
ASP.NET (such as the App_LocalResources and App_GlobalResources folders for globalization, or the
Theme folder for website-specific themes). ASP.NET recognizes these folders based on their names.
Visual Studio also checks for project management events such as when another process changes a
file in a project you currently have open. When this occurs, Visual Studio will notify you and give you the
option to refresh the file.

The Visual Studio IDE


Now that you’ve created a basic website, it’s a good time to take a tour of the different parts of the Visual
Studio interface. Figure 2-7 identifies each part of the Visual Studio window, and Table 2-1 describes the
most commonly used windows.
If you don’t see a particular window, it’s easy enough to summon it into view. You can pick the most
common windows directly from the View window (for example, View􀀂Solution Explorer) and you can
find less common windows under the Other Windows submenu (for example, View􀀂Other
Windows􀀂Macro Explorer). Finally, you’ll find windows that are used for debugging under the
Debug􀀂Windows submenu.

Structuring HTML Markup


There are endless ways to format the same chunk of HTML. Nested tags can be indented, and long tags
are often broken over several lines for better readability. However, the exact amount of indentation and
the preferred line length vary from person to person.
Because of these variations, Visual Studio doesn’t enforce any formatting. Instead, it always
preserves the capitalization and indenting you use. The drawback is that it’s easy to be inconsistent and
create web pages that use widely different formatting conventions or have messily misaligned tags.
To help sort this out, Visual Studio offers an innovative feature that lets you define the formatting
rules you want to use and then apply them anywhere you want. To try this, switch to the source view for
a page. Now, highlight some haphazard HTML, right-click the selection, and choose Format Selection.
Visual Studio will automatically straighten out the selected HTML content, giving it the correct
capitalization, indenting, and line wrapping.

Of course, this raises an excellent question—namely, who determines what the correct formatting
settings are? Although Visual Studio starts with its own sensible defaults, you have the ability to fine-tune
them extensively. To do so, right-click anywhere in the HTML source view, and choose Formatting and
Validation. This shows the Options dialog box, positioned at the Text Editor ➤ HTML ➤ Formatting
group of settings (see Figure 2-6).

This section lets you control what capitalization settings are used and how long lines can be before
they have to wrap. By default, lines don’t wrap until they hit an eye-straining 80 characters, so many
developers choose to decrease this number. You can also control how attributes are quoted and set
whether Visual Studio should automatically add the matching closing tag when you add an opening tag.


If you’re even more ambitious, you can click the Tag Specific Options button to set formatting rules
that apply only to specific tags. For example, you can tell Visual Studio to add line breaks at the
beginning and end of a <div> tag. Or, you can tell Visual Studio to use different colors to highlight
specific tags, such as tags that you often need to locate in a hurry or tags you plan to avoid. (For example,
developers who are planning to move to a CSS-based layout might try avoiding <table> tags and use
color-coding to highlight them.)
Along with the formatting settings, the Options dialog box also has several useful settings in the
subgroups of the HTML group:
General: Lets you configure Visual Studio’s automatic statement completion, use automatic
wrapping, and turn on line numbers to help you locate hard-to-remember places in your pages.
Tabs: Lets you choose the number of spaces to insert when you press Tab.
Miscellaneous: Includes the handy Format HTML on Paste option, which isn’t enabled by default.
Switch this on, and your formatting rules are applied whenever you paste new content into the
source view.

Validation: Lets you set the browser or type of markup you’re targeting (for example, HTML 4.01 or
XHTML 1.1). Depending on your choices, Visual Studio will flag violations, such as the use of
deprecated elements. (You can also change this option using the HTML Source Editing toolbar,
where the option appears as a drop-down list.)
As these settings show, Visual Studio is a great partner when adding ordinary HTML content to
ASP.NET pages.



HTML Tables


Visual Studio provides good design-time support for creating HTML tables. To try it, drag a table from
the HTML tab of the Toolbox. You’ll start with a standard 3×3 table, but you can quickly transform it
using editing features that more closely resemble a word processor than a programming tool. Here are
some of the tricks you’ll want to use:
• To move from one cell to another in the table, press the Tab key or use the arrow
keys. The current cell is highlighted with a blue border. Inside each cell you can
type static HTML or drag and drop controls from the Toolbox. If you tab beyond
the final cell, Visual Studio adds a new row.
• To add new rows and columns, right-click inside a cell, and choose from one
of the many options in the Insert submenu to insert rows, columns, and
individual cells.
• To resize a part of the table, just click one of the borders and drag.

• To format a cell, right-click inside it, click the Style box in the Properties window,
and then click the ellipsis (…) button. This shows the same Modify Style dialog
box you saw in Figure 2-5.
• To work with several cells at once, hold down Ctrl while you click each cell. You
can then right-click to perform a batch formatting operation.
• To merge cells (for example, change two cells into one cell that spans two
columns), just select the cells, right-click, and choose Modify ➤ Merge Cells.
With these conveniences, you might never need to resort to a design tool like Dreamweaver or
Expression Web.

Static HTML Tags


As you know, ASP.NET pages contain a mixture of ordinary HTML tags and ASP.NET controls. To add
HTML tags, you simply type them in or drag them from the HTML tab of the Toolbox.
Visual Studio provides a valuable style builder for formatting any static HTML element with CSS
style properties. To test it, add the <div> element from the HTML section of the Toolbox. The <div> will
appear on your page as a borderless panel. Then click to select the panel, and click the Style box in the
Properties window. An ellipsis (…) button will appear in the Style box. When you click it, the Modify
Style dialog box (shown in Figure 2-5) will appear, with options for configuring the colors, font, layout,
and border for the element.

When you create a new style in this way, it will be stored as an inline style, and recorded in the style
attribute of the element you’re modifying. Alternatively, you can define a named style in the current
page (the default) or in a separate stylesheet. You’ll learn more about these techniques and Visual
Studio’s support for stylesheets in Chapter 16.
If you want to configure the HTML element as a server control so that you can handle events and
interact with it in code, you need to switch to source view and add the required runat="server" attribute
to the control tag.

Smart Tags


Smart tags make it easier to configure complex controls. Smart tags aren’t offered for all controls, but
they are used for rich controls such as GridView, TreeView, and Calendar.
You’ll know a smart tag is available if, when you select a control, you see a small arrow in the topright
corner. If you click this arrow, a window will appear with links (and other controls) that trigger
higher-level tasks. For example, Figure 2-4 shows how you can use this technique to access Calendar
autoformatting. (Smart tags can include many more features, but the Calendar smart tag provides only a
single link.)

Absolute Positioning


To position a control on the page, you need to use all the usual tricks of HTML design, such as
paragraphs, line breaks, tables, and styles. Visual Studio assumes you want to position your elements
using flexible “flow” positioning, so content can grow and shrink dynamically without creating a layout
problem. However, you can also use absolute positioning mode (also known as grid layout) with the help
of the CSS standard. All you need to do is add an inline CSS style for your control that specifies absolute
positioning. Here’s an example that places a button exactly 100 pixels from the left edge of the page and
50 pixels from the top:


<asp:Button id="cmd" style="POSITION: absolute; left: 100px; top: 50px;"
runat="server" ... />
Once you’ve made this change, you’re free to drag the button around the window at will, and Visual
Studio will update the coordinates in the style correspondingly.
It rarely makes sense to position individual controls using absolute positioning. It doesn’t allow
your layout to adapt to different web browser window sizes, and it causes problems if the content in one
element expands, causing it to overlap another absolutely positioned element. It’s also a recipe for
inflexible layouts that are difficult to change in the future. However, you can use absolute positioning to
place entire containers, and then use flow content inside your container. For example, you could use
absolute positioning to keep a menu bar at the side, but use ordinary flow layout for the list of links
inside. The <div> container is a good choice for this purpose, because it has no built-in appearance
(although you can use style rules to apply a border, background color, and so on). The <div> is
essentially a floating box. In this example, it’s given a fixed 200 pixel width, and the height will expand to
fit the content inside.
<div style="POSITION: absolute; left: 100px; top: 50px; width:200px">
...
</div>

Designing a Web Page


To start designing a web page, double-click the web page in the Solution Explorer. If you’re using the
ASP.NET Empty Web Site template, start by creating a new page (right-click the website in the
Solution Explorer, choose Add New Item, and pick the Web Form template). A new page begins with
the bare minimum markup that it needs, but has no visible content, so it will appear like a blank page
in the designer.
Visual Studio gives you three ways to look at a web page: source view, design view, and split view.
You can choose the view you want by clicking one of the three buttons at the bottom of the web page
window (Source, Design, or Split). Source view shows the markup for your page (the HTML and ASP.NET
control tags). Design view shows a formatted view of what your page looks like in the web browser. Split
view combines the other two views so that you can see the markup for a page and a live preview at the
same time.

The easiest way to add an ASP.NET control to a page is to drag the control from the Toolbox on the
left. (The controls in the Toolbox are grouped in numerous categories based on their functions, but
you’ll find basic ingredients in the Standard tab.) You can drag a control onto the visual design surface of
a page (using design view), or you can drop it in a specific position of your web page markup (using
source view). Either way, the result is the same. Alternatively, you can type in the control tag that you
need by hand in the source view. In this case, the design view won't be updated until you click in the
design portion of the window or press Ctrl+S to save the web page.
Once you’ve added a control, you can resize it and configure its properties in the Properties window.
Many developers prefer to lay out new web pages in design view, but switch to source view to rearrange
their controls or perform more detailed tweaking. The exception is with ordinary HTML markup—
although the Toolbox includes a tab of HTML elements, it’s usually easiest to type the tags you need by
hand, rather than dragging and dropping them one at a time.
Figure 2-3 shows a web page in split view, with the source markup in the top half and the graphical
surface in the bottom half.

The Location


The location specifies where the website files will be stored. Typically, you’ll choose File System and
then use a folder on the local computer or a network path. However, you can also edit a website directly
over HTTP or FTP (File Transfer Protocol). This is occasionally useful if you want to perform live website
edits on a remote web server. However, it also introduces additional overhead. Of course, you should
never edit a production web server directly because changes are automatic and irreversible. Instead,
limit your changes to test servers.
If you simply want to create your project in a folder on the file system, you may decide to type it into
the Location box by hand. But if you prefer to see all your options, and hunt for the right location, you
can click the Browse button, which shows the Choose Location dialog box (Figure 2-2).
Along the left side of Choose Location dialog box, you’ll see four buttons that let you connect to
different types of locations:
File System: This is the easiest choice—you simply need to browse through a tree of drives and
directories or through the shares provided by other computers on the network. If you want to create
a new directory for your application, just click the Create New Folder icon above the top-right
corner of the directory tree. (You can also coax Visual Studio into creating a directory by adding a
new directory name to the end of your path.)
Local IIS: This choice allows you to browse the virtual directories made available through the IIS
web hosting software, assuming it’s running on the current computer. Chapter 18 describes virtual
directories in detail and shows you how to create them with IIS Manager. Impressively, you can also
create them without leaving Visual Studio. Just select the Default Web Site node and then click the
Create New Web Application icon at the top-right corner of the virtual directory tree.

FTP Site: This option isn’t quite as convenient as browsing for a directory—instead, you’ll need to
enter all the connection information, including the FTP site, the port, the directory, a user name,
and a password before you can connect.
Remote Web Site: This option accesses a website at a specified URL (uniform resource locator)
using HTTP. For this to work, the web server must have the FrontPage Extensions installed. When
you connect, you’ll be prompted for a user name and password.


The Template


Once you choose a language (in the list on the left), you’ll see a list of all the templates that Visual Studio
provides for that language (in the large box in the center). The template determines what files your
website starts with.
Visual Studio supports several types of ASP.NET applications, but all of them are compiled and
executed in the same way. The only difference is the files that Visual Studio creates by default. For
example, if you create a WCF Service, Visual Studio generates a website that starts with a single WCF
service in it, rather than an ASP.NET web page.
Here’s a rundown of your template choices:
ASP.NET Web Site: This creates a full-featured ASP.NET website, with its basic infrastructure
already in place. This website includes a master page that defines the overall layout (with a header,
footer, and menu bar), and ready-made default.aspx and about.aspx pages. It also includes an
Accounts folder with pages for registration, login, and password changing, and a Scripts folder with
the jQuery library for client-side JavaScript.
ASP.NET Empty Web Site: This creates a nearly empty website. It includes a stripped-down
web.config configuration file, and nothing else. Of course, it’s easy to fill in the pieces you need as
you start coding.

ASP.NET Dynamic Data Entites Web Site: This creates an ASP.NET website that uses the ASP.NET
Dynamic Data feature described in Chapter 33. This website is designed to use the Entity Model to
access the back-end database, while the similarly named ASP.NET Dynamic Data LINQ to SQL Web
Site template uses the older LINQ to SQL approach.
WCF Service: This creates a WCF service—a library of server-side methods that remote clients (for
example, Windows applications) can call. Although you won’t examine the WCF model in detail in
this book, you will create WCF services to provide server-side functionality for Silverlight pages in
Chapter 34.
ASP.NET Reports Web Site: This creates an ASP.NET website that uses the ReportView control and
SQL Server Reporting Services (a tool for generating database reports that can be viewed and
managed over the Web). The ASP.NET Crystal Reports Web Site template provides a similar service,
but it uses the competing Crystal Reports software.
Although most developers prefer to start with the ASP.NET Empty Web Site or ASP.NET Web Site
template and begin coding, there are still more specialized templates for specific types of web applications.
To view them, click the Online Templates heading on the far left of the New Web Site dialog box. There will
be a short delay while Visual Studio contacts the Microsoft web servers, after which it will add a list of
template subcategories, each with its own group of ready-made templates. For example, ASP.NET
developers can download a template to create a DotNetNuke website (which uses the popular DotNetNuke
portal framework) or an ASP.NET MVC website that uses OpenID for user authentication.

The Framework Version


Older versions of Visual Studio were tightly coupled to specific versions of .NET. You used Visual Studio
.NET to create .NET 1.0 applications, Visual Studio .NET 2003 to create .NET 1.1 applications, and Visual
Studio 2005 to create .NET 2.0 applications.
Visual Studio 2008 removed this restriction with multitargeting, and Visual Studio 2010 continues the
trend. It allows you to create web applications that are designed to work with .NET 2.0, .NET 3.0, .NET 3.5,
or .NET 4. Typically, you’ll choose the latest version that your web server supports. Later versions give you
access to more recent features, and all the samples that are included with this book target .NET 4.

To provide accurate multitargeting, Visual Studio 2010 includes reference assemblies for each version
of .NET. These assemblies include the metadata of every type, but none of the code that’s required to
implement it. That means Visual Studio 2010 can use the reference assembly to tailor its Intellisense and
error checking, ensuring that you aren’t able to use controls, classes, or members that aren’t available in
the version of .NET that you’re targeting. It also uses this metadata to determine what controls should
appear in the toolbox, what members should appear in the Properties window and Object Browser, and
so on, ensuring that the entire IDE is limited to the version you’ve chosen.
You can also change the version of .NET that you’re targeting after you’ve created your website. To
do that, follow these steps:
1. Choose Website ➤ Start Options.
2. In the list on the left, choose the Build category.
3. In the Target Framework list, choose the version of .NET you want to target.
■ Note This process is slightly different in a web project. In a web project, you begin by double-clicking the
Properties node in the Solution Explorer. Then, choose the Application tab, which contains the Target Framework
list in which you can choose the version of .NET you want to target.
When you change the .NET version, Visual Studio modifies your web.config file quite significantly.
For example, the web.config file for a .NET 4 application is short and streamlined, because all of the
plumbing it needs is set up in the computer’s root web.config file. But the web.config file for a .NET 3.5
application needs a good deal of extra boilerplate to explicitly enable support for Ajax and C# 3.5
features.

The Development Language


The language identifies the .NET programming language you’ll use to code your website. The language
you choose is simply the default language for the project. This means you can explicitly add Visual Basic
web pages to a C# website, and vice versa.

The Hidden Solution File


Although projectless development simplifies life, the last vestiges of Visual Studio’s solution-based system
are still lurking behind the scenes.
When you create a web application, Visual Studio actually creates solution files (.sln and .suo) in a userspecific
directory like c:\Users\[UserName]\Documents\Visual Studio 2010\Projects\[WebsiteFolderName].
The solution files provide a few Visual Studio-specific features that aren’t directly related to ASP.NET, such
as debugging settings. For example, if you add a breakpoint to the code in a web page (as discussed in the
“Visual Studio Debugging” section later in this chapter), Visual Studio stores the breakpoint in the .suo file.
The next time you open the website, Visual Studio locates the matching solution files automatically.
Similarly, Visual Studio uses the solution files to keep track of the files that are currently open in the design
environment so that it can restore your view when you return to the website. This approach to solution
management is fragile—obviously, if you move the website from one location to another, you lose all this
information. However, because this information isn’t really all that important (think of it as a few projectspecific
preferences), losing it isn’t a serious problem. The overall benefits of a projectless system are
usually worth the trade-off.
If you want a more permanent solution, you can save your solution files explicitly in a location of your
choosing. To do so, simply click the top item in the Solution Explorer (which represents your solution). For
example, if you open a folder named MyWebSite, the top item is named Solution 'MyWebSite'. Then,
choose File ➤ Save [SolutionName] As. This technique is handy if you’ve created a solution that combines
multiple applications (for example, a projectless website and a class library component) and you want to
edit and debug them at the same time.

Websites and Web Projects


Somewhat confusingly, Visual Studio offers two ways to create an ASP.NET-powered web application:
• Project-based development: When you create a web project, Visual Studio
generates a .csproj project file (assuming you’re coding in C#) that records the files
in your project and stores a few debugging settings. When you run a web project,
Visual Studio compiles all your code into a single assembly before launching your
web browser.

• Projectless development: An alternate approach is to create a simple website
without any project file. In this case, Visual Studio assumes that every file in the
website directory (and its subdirectories) is part of your web application. In this
scenario, Visual Studio doesn’t need to precompile your code. Instead, ASP.NET
compiles your website the first time you request a page. (Of course, you can use
precompilation to remove the first-request overhead for a deployed web
application. Chapter 18 explains how.)
The first .NET version of Visual Studio used the project model. Visual Studio 2005 removed the
project model in favor of projectless development. However, a small but significant group of developers
revolted. Realizing that there were specific scenarios that worked better with project-based
development, Microsoft released a download that added the project feature back to Visual Studio 2005.
Now, both options are supported in Visual Studio 2010.
In this chapter, you’ll begin by creating the standard projectless website, which is the simpler, more
streamlined approach. Later in this chapter, you’ll learn what scenarios work better with project-based
development, and you’ll see how to create web projects.

Introducing Visual Studio


Writing and compiling code by hand would be a tedious task for any developer. But the Visual Studio
IDE offers a slew of high-level features that go beyond basic code management. These are some of Visual
Studio’s advantages:
An integrated web server: To host an ASP.NET web application, you need web server software like
IIS, which waits for web requests and serves the appropriate pages. Setting up your web server isn’t
difficult, but it can be inconvenient. Thanks to the integrated development web server in Visual
Studio, you can run a website directly from the design environment. You also have the added
security of knowing no external computer can run your test website, because the test server only
accepts connections from the local computer.
Multilanguage development: Visual Studio allows you to code in your language or languages of
choice using the same interface (IDE) at all times. Furthermore, Visual Studio allows you to create
web pages in different languages, but include them all in the same web site. There are only two
limitations: you can’t use more than one language in the same web page (which would create
obvious compilation problems), and you must use the projectless website model (not web projects).
Less code to write: Most applications require a fair bit of standard boilerplate code, and ASP.NET
web pages are no exception. For example, when you add a web control, attach event handlers, and
adjust formatting, a number of details need to be set in the page markup. With Visual Studio, these
details are set automatically.
Intuitive coding style: By default, Visual Studio formats your code as you type, indenting
automatically and using color-coding to distinguish elements such as comments. These minor
differences make code much more readable and less prone to error. You can even configure what
automatic formatting Visual Studio applies, which is great if you prefer different brace styles (such
as K&R style, which always puts the opening brace on the same line as the preceding declaration).
■ Tip To change the formatting options in Visual Studio, select Tools ➤ Options, and then look at the groups
under the Text Editor ➤ C# ➤ Formatting section. You’ll see a slew of options that control where curly braces
should be placed
Faster development time: Many of the features in Visual Studio are geared toward helping you get
your work done faster. Convenience features allow you to work quickly and efficiently, such as
IntelliSense (which flags errors and can suggest corrections), search-and-replace (which can hunt
for keywords in one file or an entire project), and automatic comment and uncomment features
(which can temporarily hide a block of code).
Debugging: The Visual Studio debugging tools are the best way to track down mysterious errors and
diagnose strange behavior. You can execute your code one line at a time, set intelligent breakpoints
that you can save for later use, and view current in-memory information at any time.
Visual Studio also has a wealth of features that you won’t see in this chapter, including project
management, integrated source code control, code refactoring, macros, and a rich extensibility model.
Furthermore, if you’re using Visual Studio 2010 Team System you’ll gain advanced unit testing,
collaboration, and code versioning support (which is far beyond that available in simpler tools such as
Visual SourceSafe). Although Visual Studio Team System isn’t discussed in this chapter, you can learn
more from http://msdn.microsoft.com/teamsystem.

Visual Studio


With ASP.NET, you have several choices for developing web applications. If you’re inclined (and don’t
mind the work), you can code every web page and class by hand using a bare-bones text editor. This
approach is appealingly straightforward but tedious and error-prone for anything other than a simple
page. Professional ASP.NET developers rarely go this route.
Instead, almost all large-scale ASP.NET websites are built using Visual Studio. This professional
development tool includes a rich set of design tools, including legendary debugging tools and
IntelliSense, which catches errors and offers suggestions as you type. Visual Studio also supports the
robust code-behind model, which separates the .NET code you write from the web-page markup tags.
To seal the deal, Visual Studio adds a built-in test web server that makes debugging websites easy.
In this chapter, you’ll tour the Visual Studio IDE (Integrated Development Environment) and
consider the two ways you can create an ASP.NET web application in Visual Studio—either as a
straightforward website or as a web project. You’ll also learn about the code model used for ASP.NET
web pages and the compilation process used for ASP.NET web applications. Finally, you’ll take a quick
look at the Web Development Helper, a browser-based debugging tool that you can use in conjunction
with Visual Studio.
■ What’s New Although Visual Studio 2010 follows the same basic model as earlier versions, it gets a significant
facelift. In fact, Visual Studio 2010 has been completely rewritten using WPF (Microsoft’s .NET-based user-interface
technology), and the result is a cleaner, more modern interface. Most of the changes are in the details, such as
reduced on-screen clutter and streamlined IntelliSense (as described in the “Visual Studio 2010 Improvements”
section). But developers working with WPF or Silverlight (Chapter 34) get a long-awaited designer that lets them build
user interfaces by dragging and dropping controls from the Toolbox, just like in an ASP.NET page.

Silverlight


Recently, there’s been a lot of excitement about Silverlight, a rapidly evolving Microsoft technology that
allows a variety of browsers on a variety of operating systems to run true .NET code. Silverlight works
through a browser plug-in, and provides a subset of the .NET Framework class library. This subset
includes a slimmed-down version of WPF, the technology that developers use to craft next-generation
Windows user interfaces.
So where does Silverlight fit into the ASP.NET world? Silverlight is all about client code—quite simply,
it allows you to create richer pages than you could with HTML, DHTML, and JavaScript alone. In many
ways, Silverlight duplicates the features and echoes the goals of Adobe Flash. By using Silverlight in a web
page, you can draw sophisticated 2D graphics, animate a scene, and play video and other media files.
Silverlight is perfect for creating a mini-applet, like a browser-hosted game. It’s also a good choice
for adding interactive media and animation to a website. However, Silverlight obviously isn’t a good
choice for tasks that require server-side code, such as performing a secure checkout in an e-commerce
shop, verifying user input, or interacting with a server-side database. And because Silverlight is still a
new, emerging technology, it’s too early to make assumptions about its rate of adoption. That means it’s
not a good choice to replace basic ingredients in a website with Silverlight content. For example,
although you can use Silverlight to create an animated button, this is a risky strategy. Users without the
Silverlight plug-in won’t be able to see your button or interact with it. (Of course, you could create more
than one front end for your web application, using Silverlight if it’s available or falling back on regular
ASP.NET controls if it’s not. However, this approach requires a significant amount of work.)
In many respects, Silverlight is a complementary technology to ASP.NET. ASP.NET 4 doesn’t
include any features that use Silverlight, but you can freely mix ASP.NET pages and Silverlight pages
on a website—or place Silverlight content in an ASP.NET page. It’s also possible that developers will
some day use ASP.NET web controls that render Silverlight content. Using these controls, you just
might gain the best of both worlds—the server-side programming model of ASP.NET and the rich interactivity of client-side Silverlight.

ASP.NET Dynamic Data


ASP.NET Dynamic Data is a scaffolding framework that allows you to quickly build a data-driven
application. When used in conjunction with LINQ to SQL or LINQ to Entities (as it almost always is),
Dynamic Data gives you an end-to-end solution that takes you from database schema to a full-fledged
web application with support for viewing, editing, inserting, and deleting records.
It’s important to realize that Dyanmic Data isn’t just a code and markup generation tool for
developers who are too lazy to build their own custom applications. Instead, it’s a template-based,
componentized, and thoroughly customizable framework that’s ideal for creating applications that are
all about data. In fact, Dynamic Data can be seen as a logical extension of the rich data controls that
ASP.NET already provides (like the GridView, DetailsView, and FormView). But instead of forcing you to
modify many different data controls on many different pages to get the effect you want, Dynamic Data
uses field-based templates that are defined once and shared everywhere. Combine this clean design with
new features—such as validation that’s based on the database schema and easier filtering based on
foreign key relationships—and you can see why Dynamic Data is a compelling approach for web
applications that focus on viewing and editing database records. You’ll explore ASP.NET Dynamic Data
in Chapter 33.

ASP.NET MVC


ASP.NET MVC (which stands for Model-View-Controller) offers a dramatically different way to build web
pages than the standard web forms model. The core idea is that your application is separated into three
logical parts. The model includes the application-specific business code—for example, data-access logic
and validation rules. The view creates a suitable representation of the model by rendering it to HTML
pages. The controller coordinates the whole show, handling user interactions, updating the model, and
passing the information to the view.
The MVC pattern sidelines several traditional ASP.NET concepts, including web forms, web
controls, view state, postbacks, and session state. As a result, it forces developers to adopt a new way of
thinking (and accept a temporary drop in productivity). To some, the MVC pattern is cleaner and more
suited to the Web. To others, it’s extra effort with no clear payoff. But if any of the following points are
important to you, it’s worth at least considering ASP.NET MVC:
Test-driven development: Thanks to the clean separation of parts in an ASP.NET MVC application,
it’s easy to create unit tests that exercise it. With web forms, automated testing is tedious and often
impossible.
Control over HTML markup: With web forms, you program against a rich set of objects that take
care of state management and HTML rendering. With ASP.NET MVC, you inject content in a way
that’s more like data binding. While this means that complex formatted pages may take more work
to design, it also means that you have complete control over every markup detail. This control is
useful if you plan to write client-side JavaScript or use a third-party JavaScript library like jQuery.
(On the other hand, if you aren’t comfortable or interested in mucking around with HTML, web
forms is probably a better framework for your applications.)
Control over URLs: Although ASP.NET continues to give developers more control over URL routing,
ASP.NET MVC has the concept built-in. Controllers handle the mapping between URLs and your
application logic, which means it’s easy to use URL configurations such as /Products/List/Beverages
instead of /Products/List.aspx?category=Beverages. These clear, readable URLs make search-engine
optimization easier and more effective.

On the other hand, if you prefer to have rapid application design, a high-level model that manages
state for you, and a range of rich web controls, web forms will probably remain your first choice
development model.
Most of this book focuses on web forms, ASP.NET’s core model. You’ll get an introduction to
ASP.NET MVC in Chapter 32. For much more information, you can visit the official ASP.NET MVC
website at http://www.asp.net/mvc, or refer to the excellent book Pro ASP.NET MVC Framework by
Steven Sanderson (Apress, 2009).

ASP.NET 4


In its latest version, ASP.NET continues to plug in new enhancements and refinements. The most
significant ones include:
Consistent XHTML rendering; ASP.NET 3.5 made it possible to render ASP.NET web pages as
XHTML documents, but there were still a few issues to trip up unsuspecting developers. (For
example, you had to opt-in through a configuration file setting to get true, strict XHTML.) ASP.NET 4
smooths out the wrinkles and makes clean, quirk-free XHTML the standard. Chapter 3 covers the
details.
Updated browser detection: ASP.NET 4 ships with updated browser definition files, which means its
server-side rendering engine can recognize and provide properly targeted support to a wider range
of browsers. Better-supported browsers include Google Chrome, Internet Explorer 8, Firefox 3.5,
Opera 10, Safari 4, and the mobile browsers for the BlackBerry, IPhone, IPod, and Windows Mobile
operating system. You’ll learn more about browser definitions in Chapter 27.
Session state compression: Microsoft added the System.IO.Compression namespace with gzip
support in .NET 2.0. Now, ASP.NET can use it to compress the data it passes to an out-of-processs
session state service. This technique makes sense in a fairly narrow set of circumstances, but if it
applies to you, the performance improvement is almost automatic. Chapter 6 explains how it works.
Opt-in view state. Rather than disabling view state selectively, per control, you can now turn it off
for an entire page and then opt-in when necessary. This allows you to easily slim down your page
size. Chapter 6 shows you how to use this feature.
Extensible caching: Caching is one of ASP.NET’s premiere features, but with the exception of SQL
Server cache dependencies, caching hasn’t seen any new features since .NET 1.0. With ASP.NET 4,
Microsoft finally begins exposing the caching extensibility points that will allow them (and other
developers) to use new types of cache storage, including distributed caching solutions such as
Windows Server AppFabric and memcached. Although these extra bits of infrastructure aren’t all
there yet, Chapter 11 shows how the model works.
The Chart control: For years, ASP.NET developers have been forced to master the GDI+ drawing
model or purchase a third-party control to create a respectable graph. Now, ASP.NET includes an
impressive Chart control that supports a range of beautifuly rendered two- and three-dimensional
graphs (including line, bar, curve, area, pie, doughnut, and point charts, complete with features like
error bars and Bollinger bands). You’ll explore the Chart control in Chapter 28.

Revamped Visual Studio: Although the Visual Studio 2010 interface still follows the same basic
design, it’s been completely rebuilt using .NET and WPF (Windows Presentation Foundation). Along
the way, Microsoft managed to introduce a few frills, like the enhanced IntelliSense you’ll learn
about in Chapter 2, and the new visual designer that makes designing Silverlight content a breeze
(Chapter 34).
Routing: ASP.NET MVC includes support for meaningful, search-engine-friendly URLs. In ASP.NET
4, you can use the same routing technology to redirect web form requests. Chapter 17 demonstrates
this technique.
Better deployment tools: Visual Studio now allows you to create web packages, compressed files
that contain your application content and other details such as SQL Server database schemas and
IIS settings. Web packages also work in conjunction with a new web.config transformation feature
that allows you to cleanly separate the settings that apply to the test build of your application and
the ones that apply to the deployed instance. Finally, you can load and precompile a newly
deployed application more easily with the IIS application warm-up module. Chapter 18 has the
details on all these features.
Although these features are undeniably useful, the most impressive new additions to ASP.NET
development come from two separate add-ins: ASP.NET MVC and ASP.NET Dynamic Data. Both of
these features invite you to abandon part of the traditional ASP.NET development model for a different
approach, with a different set of benefits and drawbacks. In many ways, they represent the start of a new
direction in web application programming. But if either one fits your needs, it has the potential to
reduce your work dramatically.

ASP.NET AJAX


Because traditional ASP.NET code does all its work on the web server, every time an action occurs in the
page the browser needs to post some data to the server, get a new copy of the page, and refresh the
display. This process, though fast, introduces a noticeable flicker. It also takes enough time that it isn’t
practical to respond to events that fire frequently, such as mouse movements or key presses.
Web developers work around these sorts of limitations using JavaScript, the only broadly supported
client-side scripting language. In ASP.NET, many of the most powerful controls use a healthy bit of
JavaScript. For example, the Menu control responds immediately as the user moves the mouse over
different subheadings. When you use the Menu control, your page doesn’t post back to the server until
the user clicks an item.
In traditional ASP.NET pages, developers use server controls such as Menu and gain the benefit of
the client-side script these controls emit. However, even with advanced controls, some postbacks are
unavoidable. For example, if you need to update the information on a portion of the page, the only way
to accomplish this in ordinary ASP.NET is to post the page back to the server and get an entirely new
HTML document. The solution works, but it isn’t seamless.
Restless web developers have responded to challenges like these by using more client-side code and
applying it in more advanced ways. One of the most talked about examples today is Ajax (Asynchronous
JavaScript and XML). Ajax is programming shorthand for a client-side technique that allows your page to
call the server and update its content without triggering a complete postback. Typically, an Ajax page
uses client-side script code to fire an asynchronous request behind the scenes. The server receives this
request, runs some code, and then returns the data your page needs (often as a block of XML markup).
Finally, the client-side code receives the new data and uses it to perform another action, such as
refreshing part of the page. Although Ajax is conceptually quite simple, it allows you to create pages that
work more like seamless, continuously running applications. Figure 1-3 illustrates the differences.

Ajax and similar client-side scripting techniques are nothing new, but in recent years they’ve begun
to play an increasingly important role in web development. One of the reasons is that the
XMLHttpRequest object—the plumbing that’s required to support asynchronous client requests—is
now present in the majority of modern browsers, including the following:
• Internet Explorer 5 and newer
• Netscape 7 and newer
• Opera 7.6 and newer
• Safari 1.2 and newer
• Firefox (any version)
• Google Chrome (any version)

However, writing the client-side script in such a way that it’s compatible with all browsers and
implementing all the required pieces (including the server-side code that handles the asynchronous
requests) can be a bit tricky. As you’ll see in Chapter 29, ASP.NET provides a client callback feature that
handles some of the work. However, ASP.NET also includes a much more powerful abstraction layer
named ASP.NET AJAX, which extends ASP.NET with impressive Ajax-style features. You’ll explore
ASP.NET AJAX in Chapter 30.


ASP.NET 3.5


Developers who are facing ASP.NET 3.5 for the first time are likely to wonder what happened to ASP.NET
3.0. Oddly enough, it doesn’t exist. Microsoft used the name .NET Framework 3.0 to release new
technologies—most notably, WPF (Windows Presentation Foundation), a slick new user interface
technology for building rich clients, WCF (Windows Communication Foundation), a technology for
building message-oriented services, and WF (Windows Workflow Foundation), a technology that allows
you to model a complex business process as a series of actions (optionally using a visual flowchart-like
designer). However, the .NET Framework 3.0 doesn’t include a new version of the CLR or ASP.NET.
Instead, the next release of ASP.NET was rolled into the .NET Framework 3.5.
Compared to ASP.NET 2.0, ASP.NET 3.5 is a more gradual evolution. Its new features are
concentrated in two areas: LINQ and Ajax, as described in the following sections.
LINQ
LINQ (Language Integrated Query) is a set of extensions for the C# and Visual Basic languages. It allows
you to write C# or Visual Basic code that manipulates in-memory data in much the same way you query
a database.
Technically, LINQ defines about 40 query operators, such as select, from, in, where, and orderby (in
C#). These operators allow you to code your query. However, there are various types of data on which
this query can be performed, and each type of data requires a separate flavor of LINQ.
The most fundamental LINQ flavor is LINQ to Objects, which allows you to take a collection of
objects and perform a query that extracts some of the details from some of the objects. LINQ to Objects
isn’t ASP.NET-specific. In other words, you can use it in a web page in exactly the same way that you use
it in any other type of .NET application.
Along with LINQ to Objects is LINQ to DataSet, which provides similar behavior for querying an inmemory
DataSet object, and LINQ to XML, which works on XML data. But one of the most interesting
flavors of LINQ is LINQ to Entities, which allows you to use the LINQ syntax to execute a query against a relational database. Essentially, LINQ to Entities creates a properly parameterized SQL query based on
your code, and executes the query when you attempt to access the query results. You don’t need to write
any data access code or use the traditional ADO.NET objects.
LINQ to Objects, LINQ to DataSet, and LINQ to XML are features that complement ASP.NET, and
aren’t bound to it in any specific way. However, ASP.NET includes enhanced support for LINQ to
Entities, including a data source control that lets you perform a query through LINQ to Entities and bind
the results to a web control, with no extra code required. You’ll take a look at LINQ to Objects, LINQ to
DataSet, and LINQ to Entities in Chapter 13. You’ll consider LINQ to XML in Chapter 14.

The Evolution of ASP.NET


When Microsoft released ASP.NET 1.0, even it didn’t anticipate how enthusiastically the technology
would be adopted. ASP.NET quickly became the standard for developing web applications with
Microsoft technologies and a heavy-hitting competitor against all other web development platforms.
Since that time, ASP.NET has had several updates. The following sections explain how ASP.NET has
evolved over the years.
ASP.NET 1.0 and 1.1
When ASP.NET 1.0 first hit the scene, its core idea was a model of web page design called web forms. As
you’ll see in the early chapters in this book, the web form model is simply an abstraction that models
your page as a combination of objects. When a browser requests a specific page, ASP.NET instantiates
the page object, and then creates objects for all the ASP.NET controls inside that page. The page and its
control go through a sequence of life-cycle events, and then—when the page processing is finished—
they render the final HTML and are released from memory. The bulk of ASP.NET programming is filling
in what happens in between.
ASP.NET 2.0
It’s a testament to the good design of ASP.NET 1.0 and 1.1 that few of the changes introduced in
ASP.NET 2.0 were fixes for existing features. Instead, ASP.NET 2.0 kept the same core abstraction (the
web form model) and concentrated on adding new, higher-level features. Some of the highlights include:
• Master pages: Master pages are reusable page templates. For example, you can
use a master page to ensure that every web page in your application has the same
header, footer, and navigation controls.
• Themes: Themes allow you to define a standardized set of appearance
characteristics for web controls. Once defined, you can apply these formatting
presets across your website for a consistent look.
• Navigation. ASP.NET’s navigation framework includes a mechanism for defining
site maps that describe the logical arrangement of pages in a website. It also
includes navigation controls (such as trees and breadcrumb-style links) that use
this information to let users move through the site.
• Security and membership: ASP.NET 2.0 added a slew of security-related features,
including automatic support for storing user credentials, a role-based
authorization feature, and prebuilt security controls for common tasks like logging
in, registering, and retrieving a forgotten password.
• Data source controls: The data source control model allows you to define how
your page interacts with a data source declaratively in your markup, rather than
having to write the equivalent data access code by hand. Best of all, this feature
doesn’t force you to abandon good component-based design—you can bind to a
custom data component just as easily as you bind directly to the database.
• Web parts: One common type of web application is the portal, which centralizes
different information using separate panes on a single web page. Web parts
provide a prebuilt portal framework complete with a flow-based layout,
configurable views, and even drag-and-drop support.

• Profiles: Profiles allow you to store user-specific information in a database
without writing any database code. Instead, ASP.NET takes care of the tedious
work of retrieving the profile data when it’s needed and saving the profile data
when it changes.

ASP.NET Is Easy to Deploy and Configure


One of the biggest headaches a web developer faces during a development cycle is deploying a
completed application to a production server. Not only do the web-page files, databases, and
components need to be transferred, but components need to be registered and a slew of configuration
settings need to be re-created. ASP.NET simplifies this process considerably.
Every installation of the .NET Framework provides the same core classes. As a result, deploying an
ASP.NET application is relatively simple. For no-frills deployment, you simply need to copy all the files
to a virtual directory on a production server (using an FTP program or even a command-line command
like XCOPY). As long as the host machine has the .NET Framework, there are no time-consuming
registration steps. Chapter 18 covers deployment in detail.
Distributing the components your application uses is just as easy. All you need to do is copy the
component assemblies along with your website files when you deploy your web application. Because all
the information about your component is stored directly in the assembly file metadata, there’s no need
to launch a registration program or modify the Windows registry. As long as you place these components
in the correct place (the Bin subdirectory of the web application directory), the ASP.NET engine
automatically detects them and makes them available to your web-page code. Try that with a traditional
COM component!
Configuration is another challenge with application deployment, particularly if you need to transfer
security information such as user accounts and user privileges. ASP.NET makes this deployment process
easier by minimizing the dependence on settings in IIS (Internet Information Services). Instead, most
ASP.NET settings are stored in a dedicated web.config file. The web.config file is placed in the same
directory as your web pages. It contains a hierarchical grouping of application settings stored in an easily
readable XML format that you can edit using nothing more than a text editor such as Notepad. When you
modify an application setting, ASP.NET notices that change and smoothly restarts the application in a new
application domain (keeping the existing application domain alive long enough to finish processing any
outstanding requests). The web.config file is never locked, so it can be updated at any time.

ASP.NET Supports all Browsers


One of the greatest challenges web developers face is the wide variety of browsers they need to support.
Different browsers, versions, and configurations differ in their support of XHTML, CSS, and JavaScript.
Web developers need to choose whether they should render their content according to the lowest
common denominator, and whether they should add ugly hacks to deal with well-known quirks on
popular browsers.
ASP.NET addresses this problem in a remarkably intelligent way. Although you can retrieve
information about the client browser and its capabilities in an ASP.NET page, ASP.NET actually
encourages developers to ignore these considerations and use a rich suite of web server controls. These
server controls render their markup adaptively by taking the client’s capabilities into account. One
example is ASP.NET’s validation controls, which use JavaScript and DHTML (Dynamic HTML) to
enhance their behavior if the client supports it. Another example is the set of Ajax-enabled controls,
which uses complex JavaScript routines that test browser versions and use carefully tested workarounds
to ensure consistent behavior. These features are optional, but they demonstrate how intelligent
controls can make the most of cutting-edge browsers without shutting out other clients. Best of all, you
don’t need any extra coding work to support both types of client.

HTML Controls VS. Web Controls


When ASP.NET was first created, two schools of thought existed. Some ASP.NET developers were most
interested in server-side controls that matched the existing set of HTML controls exactly. This approach
allows you to create ASP.NET web-page interfaces in dedicated HTML editors, and it provides a quick
migration path for existing ASP pages. However, another set of ASP.NET developers saw the promise of
something more—rich server-side controls that didn’t just emulate individual HTML tags. These controls
might render their interface from dozens of distinct HTML elements while still providing a simple objectbased
interface to the programmer. Using this model, developers could work with programmable menus,
calendars, data lists, validators, and so on.
After some deliberation, Microsoft decided to provide both models. You’ve already seen an example of
HTML server controls, which map directly to the basic set of HTML tags. Along with these are ASP.NET
web controls, which provide a higher level of abstraction and more functionality. In most cases, you’ll use
HTML server-side controls for backward compatibility and quick migration, and use web controls for new
projects.
ASP.NET web control tags always start with the prefix asp: followed by the class name. For example, the
following snippet creates a text box and a check box:
<asp:TextBox id="myASPText" Text="Hello ASP.NET TextBox" runat="server" />
<asp:CheckBox id="myASPCheck" Text="My CheckBox" runat="server" />
Again, you can interact with these controls in your code, as follows:
myASPText.Text = "New text";
myASPCheck.Text = "Check me!";
Notice that the Value property you saw with the HTML control has been replaced with a Text property. The
HtmlInputText.Value property was named to match the underlying value attribute in the HTML <input> tag.
However, web controls don’t place the same emphasis on correlating with HTML syntax, so the more
descriptive property name Text is used instead.
The ASP.NET family of web controls includes complex rendered controls (such as the Calendar and
TreeView), along with more streamlined controls (such as TextBox, Label, and Button), which map closely
to existing HTML tags. In the latter case, the HTML server-side control and the ASP.NET web control
variants provide similar functionality, although the web controls tend to expose a more standardized,streamlined interface. This makes the web controls easy to learn, and it also means they’re a natural fit for
Windows developers moving to the world of the Web, because many of the property names are similar to
the corresponding Windows controls.

ASP.NET Is Object-Oriented


ASP provides a relatively feeble object model. It provides a small set of objects; these objects are really
just a thin layer over the raw details of HTTP and HTML. On the other hand, ASP.NET is truly objectoriented.
Not only does your code have full access to all objects in the .NET Framework, but you can also
exploit all the conventions of an OOP (object-oriented programming) environment. For example, you
can create reusable classes, standardize code with interfaces, extend existing classes with inheritance,
and bundle useful functionality in a distributable, compiled component.
One of the best examples of object-oriented thinking in ASP.NET is found in server-based controls.
Server-based controls are the epitome of encapsulation. Developers can manipulate control objects
programmatically using code to customize their appearance, provide data to display, and even react to
events. The low-level HTML markup that these controls render is hidden away behind the scenes.
Instead of forcing the developer to write raw HTML manually, the control objects render themselves to
HTML just before the web server sends the page to the client. In this way, ASP.NET offers server controls
as a way to abstract the low-level details of HTML and HTTP programming.

Here’s a quick example with a standard HTML text box that you can define in an ASP.NET web page:
<input type="text" id="myText" runat="server" />
With the addition of the runat="server" attribute, this static piece of HTML becomes a fully
functional server-side control that you can manipulate in C# code. You can now work with events that it
generates, set attributes, and bind it to a data source.
For example, you can set the text of this box when the page first loads using the following C# code:
void Page_Load(object sender, EventArgs e)
{
myText.Value = "Hello World!";
}
Technically, this code sets the Value property of an HtmlInputText object. The end result is that a
string of text appears in a text box on the HTML page that’s rendered and sent to the client.

ASP.NET Is Hosted by the Common Language Runtime


Perhaps the most important aspect of the ASP.NET engine is that it runs inside the runtime environment
of the CLR. The whole of the .NET Framework—that is, all namespaces, applications, and classes—is
referred to as managed code. Though a full-blown investigation of the CLR is beyond the scope of this
chapter, some of the benefits are as follows:
Automatic memory management and garbage collection: Every time your application instantiates
a reference-type object, the CLR allocates space on the managed heap for that object. However, you
never need to clear this memory manually. As soon as your reference to an object goes out of scope
(or your application ends), the object becomes available for garbage collection. The garbage
collector runs periodically inside the CLR, automatically reclaiming unused memory for
inaccessible objects. This model saves you from the low-level complexities of C++ memory handling
and from the quirkiness of COM reference counting.
Type safety: When you compile an application, .NET adds information to your assembly that
indicates details such as the available classes, their members, their data types, and so on. As a result,
other applications can use them without requiring additional support files, and the compiler can
verify that every call is valid at runtime. This extra layer of safety completely obliterates whole
categories of low-level errors.
Extensible metadata: The information about classes and members is only one of the types of
metadata that .NET stores in a compiled assembly. Metadata describes your code and allows you to
provide additional information to the runtime or other services. For example, this metadata might
tell a debugger how to trace your code, or it might tell Visual Studio how to display a custom control
at design time. You could also use metadata to enable other runtime services, such as transactions
or object pooling.
Structured error handling: .NET languages offer structured exception handling, which allows you to
organize your error-handling code logically and concisely. You can create separate blocks to deal
with different types of errors. You can also nest exception handlers multiple layers deep.
Multithreading: The CLR provides a pool of threads that various classes can use. For example, you
can call methods, read files, or communicate with web services asynchronously, without needing to
explicitly create new threads.
Figure 1-2 shows a high-level look at the CLR and the .NET Framework.

ASP.NET Is Multilanguage


Though you’ll probably opt to use one language over another when you develop an application, that
choice won’t determine what you can accomplish with your web applications. That’s because no matter
what language you use, the code is compiled into IL.
IL is a stepping stone for every managed application. (A managed application is any application
that’s written for .NET and executes inside the managed environment of the CLR.) In a sense, IL is the
language of .NET, and it’s the only language that the CLR recognizes.
To understand IL, it helps to consider a simple example. Take a look at this code written in C#:

using System;
namespace HelloWorld
{
           public class TestClass
          {
              static void Main(string[] args)
              {
                   Console.WriteLine("Hello World");
              }
          }
}

This code shows the most basic application that’s possible in .NET—a simple command-line utility
that displays a single, predictable message on the console window.
Now look at it from a different perspective. Here’s the IL code for the Main() method:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 13 (0xd)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "Hello World"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
} // end of method TestClass::Main
It’s easy enough to look at the IL for any compiled .NET application. You simply need to run the
IL Disassembler, which is installed with Visual Studio and the .NET SDK (software development kit).
Look for the file ildasm.exe in a directory like c:\Program Files\Microsoft SDKs\Windows\v7.0A\bin.
Run ildasm.exe, and then use the File ➤ Open command, and select any DLL or EXE that was created
with .NET.


If you’re patient and a little logical, you can deconstruct the IL code fairly easily and figure out
what’s happening. The fact that IL is so easy to disassemble can raise privacy and code control issues,
but these issues usually aren’t of any concern to ASP.NET developers. That’s because all ASP.NET code is
stored and executed on the server. Because the client never receives the compiled code file, the client
has no opportunity to decompile it. If it is a concern, consider using an obfuscator that scrambles code
to try to make it more difficult to understand. (For example, an obfuscator might rename all variables to
have generic, meaningless names such as f__a__234.) Visual Studio includes a scaled-down version of
one popular obfuscator, called Dotfuscator.
The following code shows the same console application in Visual Basic code:

Imports System
Namespace HelloWorld
Public Class TestClass
Shared Sub Main(args() As String)
Console.WriteLine("Hello World")
End Sub
End Class
End Namespace

If you compile this application and look at the IL code, you’ll find that it’s nearly identical to the IL
code generated from the C# version. Although different compilers can sometimes introduce their own
optimizations, as a general rule of thumb no .NET language outperforms any other .NET language,
because they all share the same common infrastructure. This infrastructure is formalized in the CLS
(Common Language Specification), which is described in the following sidebar, entitled “The Common
Language Specification.”
It’s worth noting that IL has been adopted as an Ecma and ISO standard. This adoption allows the
adoption of other common language frameworks on other platforms. The Mono project at
http://www.mono-project.com is the best example of such a project.

ASP.NET Is Compiled, Not Interpreted

ASP.NET applications, like all .NET applications, are always compiled. In fact, it’s impossible to execute
C# or Visual Basic code without it being compiled first.
.NET applications actually go through two stages of compilation. In the first stage, the C# code you
write is compiled into an intermediate language called Microsoft Intermediate Language (MSIL), or just
IL. This first step is the fundamental reason that .NET can be language-interdependent. Essentially, all
.NET languages (including C#, Visual Basic, and many more) are compiled into virtually identical IL
code. This first compilation step may happen automatically when the page is first requested, or you can
perform it in advance (a process known as precompiling). The compiled file with IL code is an assembly.
The second level of compilation happens just before the page is actually executed. At this point, the
IL code is compiled into low-level native machine code. This stage is known as just-in-time (JIT)
compilation, and it takes place in the same way for all .NET applications (including Windows
applications, for example). Figure 1-1 shows this two-step compilation process.
.NET compilation is decoupled into two steps in order to offer developers the most convenience and
the best portability. Before a compiler can create low-level machine code, it needs to know what type of
operating system and hardware platform the application will run on (for example, 32-bit or 64-bit
Windows). By having two compile stages, you can create a compiled assembly with .NET code and still
distribute this to more than one platform.

Of course, JIT compilation probably wouldn’t be that useful if it needed to be performed every time
a user requested a web page from your site. Fortunately, ASP.NET applications don’t need to be
compiled every time a web page is requested. Instead, the IL code is created once and regenerated only
when the source is modified. Similarly, the native machine code files are cached in a system directory
that has a path like c:\Windows\Microsoft.NET\Framework\[Version]\Temporary ASP.NET Files.
As you’ll learn in Chapter 2, the actual point where your code is compiled to IL depends on how
you’re creating and deploying your web application. If you’re building a web project in Visual Studio, the
code is compiled to IL when you compile your project. But if you’re building a lighter-weight projectless
website, the code for each page is compiled the first time you request that page. Either way, the code
goes through its second compilation step (from IL to machine code) the first time it’s executed.
ASP.NET also includes precompilation tools that you can use to compile your application right
down to machine code once you’ve deployed it to the production web server. This allows you to avoid
the overhead of first-time compilation when you deploy a finished application (and prevent other
people from tampering with your code). Precompilation is described in Chapter 18.

ASP.NET Is Integrated with the .NET Framework

Merhaba arkadaşlar.Uzun bir aradan sonra tekrar sizlerleyim tabi bu sefer büyük bir değişiklikle geldim.Paylaşımlarım da elimden geldiğince İngilizce dilini kullanacağım.Bu sizin programcılar dünyasına daha kolay adapte olmanızı sağlıyacaktır.

Şimdi gelelim konumuza.

The .NET Framework is divided into an almost painstaking collection of functional parts, with tens of
thousands of types (the .NET term for classes, structures, interfaces, and other core programming
ingredients). Before you can program any sort of .NET application, you need a basic understanding of
those parts—and an understanding of why things are organized the way they are.
The massive collection of functionality that the .NET Framework provides is organized in a way that
traditional Windows programmers will see as a happy improvement. Each one of the thousands of
classes in the .NET Framework is grouped into a logical, hierarchical container called a namespace.
Different namespaces provide different features. Taken together, the .NET namespaces offer
functionality for nearly every aspect of distributed development from message queuing to security. This
massive toolkit is called the class library.

Interestingly, the way you use the .NET Framework classes in ASP.NET is the same as the way you
use them in any other type of .NET application (including a stand-alone Windows application, a
Windows service, a command-line utility, and so on). Although there are Windows-specific and webspecific
classes for building user interfaces, the vast majority of the .NET Framework (including
everything from database access to multithreaded programming) is usable in any type of application. In
other words, .NET gives the same tools to web developers that it gives to rich client developers.
Bing'ı Seviyoruz. :)
Google'ı Seviyoruz. :)