Building a Code Sample Website


Overview of the Sample Website
The primary purpose of the website is to act as a code sample website for .NET code. Anyone who visits the website can post a new code sample entry. A code sample entry can consist of one or more code sample files. The author of the code sample entry can provide a description of each of the files. Furthermore, the author can add one or more tags to the code samples to categorize and describe their purpose. Visitors to the website can browse the existing code sample entries. They can rate code samples when they view them. Furthermore, they can copy the code samples so they can use the samples in their own applications.

The website also includes a simple blog. The administrator of the website can post blog entries about the code samples or about any other topic. Visitors to the website can add comments to a blog entry. The website exposes both an ATOM and RSS feed. If someone wants to subscribe to the blog, that person can subscribe to either the ATOM or RSS feed. The home page of the website displays a code cloud and a list of recent blog entries (see Figure 1). The code cloud consists of a distinct list of all the code entry tags. The more code entries that share a tag, the larger the tag appears in the code cloud. In the figure, you’ll notice that a lot of code samples are related to validation. If you click a tag in the code cloud, you are transferred to a page that contains a list of code samples associated with the tag.

Figure 1:

Using Client-Side ASP.NET AJAX

Making JavaScript Look Like C#
Let me start by saying that there is nothing wrong with JavaScript the language. It is not a toy language. It is not a limited language. JavaScript simply has it roots in a different programming language family than other languages you are familiar with, such as C# and VB.NET. For a great, quick introduction to JavaScript the language, I recommend that you read “A re-introduction to JavaScript” at http://developer.mozilla.org/en/docs/A_re-introduction_to_JavaScript. JavaScript is an object-oriented programming language. In fact, one could argue that it is more object-oriented than languages such as C# and VB.NET. In a language such as C#, you make a distinction between classes (Aristotelian forms) and objects (Aristotelian matter). An object is an instance of a class, but a class does not exist in its own right. In JavaScript, classes do not exist. The only thing that exists are objects (everything is matter). Objects are not related to one another by being instances of the same class. Instead, one object can be related to another object when one object is the prototype for another object. Another major difference between JavaScript and C# is that JavaScript is a dynamic language. The type of a variable can change at any moment during runtime. When JavaScript code is executed, a String might transform into an Integer and back again. The C# language, on the other hand, is statically typed. Once declared, a String is a String and it can never be anything else.

Using the Microsoft AJAX Library
The supporting code for the client-side Microsoft AJAX Framework is contained in a single JavaScript file named MicrosoftAjax.js. This file is included in a page automatically when you add an ASP.NET ScriptManager control to a page. If you add an AJAX Web Form to a website within Visual Web Developer, the page contains the ScriptManager control automatically.

Creating an AJAX Client Library
Before we do anything else, we need to discuss how you create an external JavaScript file and reference it in an AJAX Web Form page. You create a JavaScript file by selecting the menu option Website, Add New Item and selecting the AJAX Client Library  For example, the file in Listing contains a single JavaScript function called sayMessage() that displays a JavaScript alert with a message.


Ajax


Ajax, shorthand for Asynchronous Javascript and XML, is a set of technologies that allows you to create Web applications that don't need to refresh Web pages in the browser. You can operate behind the scenes, connecting to the server, uploading and downloading data, and display the results in the browser using dynamic HTML. Using Ajax gives your Web pages the feel of a desktop application-the whole display will no longer flash when you click a button. VTC Author Steve Holzner helps you get started developing and building your own Ajax capable web pages. A familiarity with JavaScript, XML, PHP is recommended for this course. To begin learning, simply click the links.

Using the ASP.NET AJAX Control Toolkit


The ASP.NET AJAX Control Toolkit is not included with the ASP.NET 3.5 Framework. The Toolkit is being continuously updated. A new release of the Toolkit is available every couple months. The Toolkit is maintained as a project at Microsoft CodePlex. You can download the latest release of the ASP.NET AJAX Control Toolkit at the following location:

When you download the Toolkit, you have the choice of either
(1) downloading the controls and the source code or
(2) downloading the controls only. You’ll need to unzip the download onto your hard drive.

As part of the download, you get a sample website that demonstrates each of the Toolkit controls. You can open the sample website by launching Visual Web Developer, selecting the menu option File, Open Website, and browsing to the SampleWebSite folder in the unzipped download.

Using Server-Side ASP.NET AJAX


The Ajax Vision
ASP.NET is a server-side technology for building web applications. Almost all the work happens on the web server and not the web browser. Whenever you perform an action in an ASP.NET page—such as clicking a button or sorting a GridView—the entire page must be posted back to the web server. Any significant action on a page results in a postback. If you think about it, this is incredibly inefficient. When you perform a postback in an ASP.NET page, the entire page must be transported across the Internet from browser to server. Next, the .NET class that corresponds to the page must re-render the entire page again from scratch. Finally, the finished page must be sent back across the Internet to the browser. This whole long, slow, agonizing process must occur even if you are updating a tiny section of the page.
Using a server-side technology such as ASP.NET results in a bad user experience. Every time a user performs some action on a page, the universe temporarily freezes. Whenever you perform a postback, the browser locks, the page jumps, and the user must wait patiently twiddling his thumbs while the page gets reconstructed. All of us have grown accustomed to this awful user experience. However, we would never design our desktop applications in the same way.

Google Docs (http://docs.google.com) demonstrates that you can build Microsoft Office better than Office by building it as a web application. Google Docs enables you to save your documents, spreadsheets, and presentations on a central server so that they don’t get lost and can be accessed anywhere. Furthermore, Google Docs enables people to collaborate on documents and spreadsheets over the Internet, which is something that you just cannot do in Microsoft Office. Google Suggest (http://www.google.com/webhp?complete=1&hl=en) was the Google application that convinced me that the future is Ajax. Google Suggest works like the normal Google home page, except for the fact that the Google Suggest page offers suggestions as you type. While you are typing, Google Suggest looks up matching words from its database and shows them to you in real time (before seeing Google Suggest, I would have thought this violated the laws of physics).

Building Templated Databound Controls

Creating Templated Controls
A template enables you to customize the layout of a control. Furthermore, a template can contain expressions that are not evaluated until runtime. The ASP.NET Framework supports two types of templates. First, you can create a one-way databinding template. You use a one-way databinding template to display data items. In a one-way databinding template, you use the Eval() expression to display the value of a data item.

Second, you have the option of creating a two-way databinding template. A two-way databinding template can be used not only to display data items, but also to update data items. You can use the Bind() expression in a two-way databinding template to both display a data item and extract the value of a data item. Typically, you use templates with a databound control. For example, the ListView, GridView, Repeater, DataList, FormView, and DetailsView controls all support an ItemTemplate that enables you to format the data items that these controls display.

Implementing the ITemplate Interface
You create a one-way databinding template by adding a property to a control that returns an object that implements the ITemplate interface. The ITemplate interface includes one method:
InstantiateIn—Instantiates the contents of a template in a particular control.

Building Custom Control


You must answer two questions before writing a custom control:
What type of control do I want to write?
From what class do I inherit?

The two basic types of controls are fully rendered and composite controls. When you build a fully rendered control, you start from scratch. You specify all the HTML content that the control renders to the browser. When you create a composite control, on the other hand, you build a new control from existing controls. For example, you can create a composite AddressForm control from existing TextBox and RequiredFieldValidator controls. When you create a composite control, you bundle together existing controls as a new control. The second question that you must address is the choice of the base control for your new control. You can inherit a new control from any existing ASP.NET control. For example, if you want to create a better GridView control, then you can inherit a new control from the GridView control and add additional properties and methods to your custom GridView control.

Typically, when building a basic control, you inherit your new control from one of the following base classes:
. System.Web.UI.Control
. System.Web.UI.WebControls.WebControl
. System.Web.UI.WebControls.CompositeControl

Configuring Applications


ASP.NET uses a hierarchical system of configuration. At the top of the hierarchy is the Machine.config file. This file contains all the default configuration settings for ASP.NET applications and all other types of applications built with the .NET Framework.

The Machine.config file is located at the following path:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\Machine.config

This same folder also contains a Web.config file. The Web.config file contains settings specific to ASP.NET applications. The Web.config file overrides particular settings in the Machine.config file.

The \CONFIG folder includes the following six files:
Machine.config—Contains the actual configuration settings.
Machine.config.default—Contains the default values for all configuration settings.
Machine.config.comments—Contains comments on each configuration setting.
Web.config—Contains the actual configuration settings.
Web.config.default—Contains the default values for all configuration settings.
Web.config.comments—Contains comments on each configuration setting.

Only the Machine.config and Web.config files are actually used. The other files are there for the purpose of documentation. You can place a Web.config file in the root folder of a website, such as the wwwroot
folder. A Web.config file located in the root folder of a website contains settings that apply to all applications contained in the website. You also can place a Web.config file in the root of a particular application. In that case, the Web.config file has application scope. Finally, you can place a Web.config file in an application subfolder. In that case, the Web.config file applies to all pages in that folder and below.

Working with the HTTP Runtime


Creating a Custom BuildProvider
When you write an ASP.NET page and save the page to your computer’s file system, the ASP.NET page gets compiled dynamically into a .NET class in the background. The page is compiled dynamically by a BuildProvider. The ASP.NET Framework includes a number of BuildProviders. Each BuildProvider is responsible for compiling a file with a particular extension that is located in a particular type of folder. For example, there are BuildProviders for Themes, Master Pages, User Controls, and Web Services. When a BuildProvider builds, it builds a new class in the Temporary ASP.NET Files folder. Any class added to the folder becomes available to your application automatically. When you use Visual Web Developer, any public properties and methods of the class appear in Intellisense.

You can create your own BuildProviders. This can be useful in a variety of different scenarios. For example, imagine that you find yourself building a lot of ASP.NET pages that display forms. You can tediously build each ASP.NET page by hand by adding all the necessary form and validation controls. Alternatively, you can create a new BuildProvider that takes an XML file and generates the form pages for you automatically.

Localizing Applications for Multiple Languages


One can localize an ASP.NET website so that it supports multiple languages and cultures. For example, you might need to create both an English language and Spanish language version of the same website.
One approach to localization is to simply create multiple copies of the same website and translate each copy into a different language. This is a common approach when building ASP Classic (or even ASP.NET 1.1) websites. The problem with this approach is it creates a website maintenance nightmare. Whenever you need to make a change to the website—no matter how simple—you must make the change in each copy of the website. When building ASP.NET applications, you do not need to create multiple copies of a website to support multiple languages. Instead, you can take advantage of resource files. A resource file contains language-specific content. For example, one resource file might contain a Spanish version of all the text in your website, and a second resource file might contain the Indonesian version of all the text in your website.

Setting the Current Culture
Two main properties of the Page class have an effect on localization:
UICulture
Culture

Caching Application Pages and Data


The ASP.NET 3.5 Framework supports the following types of caching:
. Page Output Caching
. Partial Page Caching
. DataSource Caching
. Data Caching

Using Page Output Caching
You enable Page Output Caching by adding an <%@ OutputCache %> directive to a page. For example, the page in Listing caches its contents for 15 seconds.

LISTING CachePageOutput.aspx
<%@ Page Language=”C#” %>
<%@ OutputCache Duration=”15” VaryByParam=”none” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<script runat=”server”>
void Page_Load()
{
lblTime.Text = DateTime.Now.ToString(“T”);
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Cache Page Output</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:Label id=”lblTime” Runat=”server” />
</div>
</form>
</body>
</html>

The page in Listing displays the current server time in a Label control. The page also includes an <%@ OutputCache %> directive. If you refresh the page multiple times, you will notice that the time is not updated until at least 15 seconds have passed. When you cache a page, the contents of the page are not regenerated each time you request the page.

Building ASP.NET Applications

Developers who are new to programming for the web always have difficulty understanding the problem of maintaining state. The HTTP protocol, the fundamental protocol of the World Wide Web, is a stateless protocol. What this means is that from a web server’s perspective, every request is from a new user. The HTTP protocol does not provide you with any method of determining whether any two requests are made by the same person.

However, maintaining state is important in just about any web application. The paradigmatic example is a shopping cart. If you want to associate a shopping cart with a user over multiple page requests, then you need some method of maintaining state. This chapter looks at three methods included in the ASP.NET 3.5 Framework for associating data with a particular user over multiple page requests. In the first section, you learn how to create and manipulate browser cookies. A browser cookie enables you to associate a little bit of text with each website user.

Using Browser Cookies
Cookies were introduced into the world with the first version of the Netscape browser. The developers at Netscape invented cookies to solve a problem that plagued the Internet at the time. There was no way to make money because there was no way to create a shopping cart.

Using ASP.NET Membership

In the previous chapter, you learned how to use the Login controls to create an entire user registration system. This chapter looks under the covers and examines the security frameworks on which the Login controls are built. The ASP.NET Framework includes four frameworks related to security:
  • ASP.NET Authentication—Enables you to identify users.
  • ASP.NET Authorization—Enables you to authorize users to request particular resources.
  • ASP.NET Membership—Enables you to represent users and modify their properties.
  • Role Manager—Enables you to represent user roles and modify their properties.

Configuring Authentication
Authentication refers to the process of identifying who you are. The ASP.NET Framework supports three types of authentication:
  • Windows Authentication
  • NET Passport Authentication
  • Forms Authentication

A particular application can have only one type of authentication enabled. You can’t, for example, enable both Windows and Forms authentication at the same time. Windows authentication is enabled by default. When Windows authentication is enabled, users are identified by their Microsoft Windows account names. Roles correspond to Microsoft Windows groups.

Using the Login Controls

You can use the ASP.NET Login controls to easily build a user registration system for your website. You can use the Login controls to display user registration forms, login forms, change password forms, and password reminder forms. By default, the Login controls use ASP.NET Membership to authenticate  Users, create new users, and change user properties. When you use the Login controls, you are not required to write any code when performing these tasks. ASP.NET Membership is discussed in detail in the following chapter. In the first part of this chapter, you are provided with an overview of the Login controls. You learn how to passwordprotect a section of your website and enable users to register and log in to your website. In the remainder of this chapter, you learn how to use each of the following Login controls in detail:
  • Login—Enables you to display a user login form.
  • CreateUserWizard—Enables you to display a user registration form.
  • LoginStatus—Enables you to display either a log in or log out link, depending on a user’s authentication status.
  • LoginName—Enables you to display the current user’s registered username.
  • ChangePassword—Enables you to display a form that allows users to change their passwords.
  • PasswordRecovery—Enables you to display a form that allows a user to receive an email containing his or her password.
  • LoginView—Enables you to display different content to different users depending on the user’s authentication status or role.

Advanced Navigation

Websites tend to be organic—they grow and change over time. This can create problems when other applications link to your application. You need some way of modifying your website without breaking all the existing links to it.

Remapping URLs
The simplest way to remap a URL is to specify the remapping in your application’s web configuration file.

<configuration>
<system.web>
<urlMappings>
<add
url=”~/Home.aspx”
mappedUrl=”~/Default.aspx”/>
</urlMappings>
</system.web>
</configuration>

The mappedUrl attribute can contain query strings. However, it cannot contain wildcards. You can use the <urlMappings> element only when performing simple page-topage mappings. After you add the web configuration file to your application, any requests for the Home.aspx page are modified automatically to requests for the Default.aspx page. It doesn’t matter whether the Home.aspx page actually exists. If the Home.aspx page does exist, you can never open the page.

Using Site Maps

Using the SiteMapDataSource Control
The SiteMapDataSource control enables you to represent a Site Map declaratively in a page. You can bind navigation controls such as the TreeView and Menu controls to a SiteMapDataSource control. You also can bind other controls such as the GridView or DropDownList control to a SiteMapDataSource control.

Setting SiteMapDataSource Properties
The SiteMapDataSource control includes several valuable properties that you can set to modify the nodes that the control returns:
  • ShowStartingNode—Enables you to hide the starting node.
  • StartFromCurrentNode—Enables you to return all nodes starting from the current node.
  • StartingNodeOffset—Enables you to specify a positive or negative offset from the current node.
  • StartingNodeUrl—Enables you to return all nodes, starting at a node associated with a specified URL.

The most useful of these properties is the ShowStartingNode property. Normally, when you display a list of nodes with a Menu or TreeView control, you do not want to display the starting node (the link to the home page).

Site Navigation-Using the Navigation Controls

Understanding Site Maps
Before you learn about the navigation controls, you first need to understand Site Maps. All three navigation controls use Site Maps to retrieve navigation information. A Site Map enables you to represent the navigational relationships between the pages in an application, independent of the actual physical relationship between pages as stored in the file system.

Site Maps use the provider model. In the next chapter, you learn how to create custom Site Map providers to store Site Maps in custom data stores such as database tables. The examples in this chapter take advantage of the default XML Site Map provider, which enables you to store a Site Map in an XML file. By default, the navigation controls assume the existence of an XML file named Web.sitemap, which is located in the root of your application.

A Site Map file contains <siteMapNode> elements. There can be only one top-level node. A <siteMapNode> supports three main attributes:
  • title—A brief title that you want to associate with a node.
  • description—A longer description that you want to associate with a node.
  • url—A URL that points to a page or other resource.

Data Access with LINQ to SQL

New C# and VB.NET Language Features
To get LINQ to SQL to work, Microsoft had to introduce several new language features to both C# and VB.NET. Many of these features make C# and VB.NET behave more like a dynamic language (think JavaScript). Although the primary motivation for introducing these new features was to support LINQ, the new features are also interesting in their own right.

To use these new language features, you’ll need to make sure your website is targeting .NET Framework 3.5. Ensure that you have a web.config file in your project. Next, select the menu option Website, Start Options and then select the Build tab. For Target Framework, select .NET Framework 3.5. Performing these steps will modify your web.config file so that it references the necessary assemblies and uses the right version of the C# or VB.NET compiler.

Understanding Automatic Properties
The first of these new language features we will explore is called automatic properties. Unfortunately, this feature is supported only by C# and not VB.NET. Automatic properties provide you with a shorthand method for defining a new property.

You can’t add any logic to the Getters and Setters for an automatic property. You also can’t create read-only automatic properties. Why are automatic properties relevant to LINQ to SQL? When working with LINQ to SQL, you often use classes to represent nothing more than the list of columns you want to retrieve from the database (the shape of the data) like the select list in a SQL query. In those cases, you just want to do the minimum amount of work possible to create a list of properties, and automatic properties allow you to do this. You can quickly add an automatic property to a class or page when using Visual Web Developer/Visual Studio by typing prop and hitting the Tab key twice.

Understanding Initializers
You can use initializers to reduce the amount of work it takes to create a new instance of a class.

Understanding Type Inference
Here’s a new feature that makes C# and VB.NET look much more like a dynamic language such as JavaScript: local variable type inference. When you take advantage of type inference, you allow the C# or VB.NET compiler to determine the type of a variable at compile time.

Here’s an example of how you use type inference with C#:
var message = “Hello World!”;

And here is how you would use type inference with VB.NET:
Dim message = “Hello World!”

Notice that the message variable is declared without specifying a type. The C# and VB.NET compilers can infer the type of the variable (it’s a String) from the value you use to initialize the variable. No performance impact results from using type inference (the variable is not late bound). The compiler does all the work of figuring out the data type at compile time. Notice that a new keyword has been introduced into C# to support type inference: the var keyword. You declare a variable as type var when you want the compiler to figure out the variable’s data type all by itself.

You can take advantage of type inference only when you provide a local variable with an initial value. For example, this won’t work (C#):
var message;
message = “Hello World!”;

The C# compiler will refuse to compile this code because the message variable is not initialized when it is declared. The following code will work in VB.NET (but it won’t do what you want):
Dim message
message = “Hello World!”

In this case, VB.NET will treat the message variable as type Object. At runtime, it will cast the value of the variable to a string when you assign the string to the variable. This is not good from a performance perspective. VB.NET 9.0 includes a new option called Option Infer. Option Infer must be enabled in order for the implicit typing feature to work. You can enable it for a particular class file by adding the line Option Infer On at the very top of a code file.

The relevance of type inference to LINQ to SQL will be apparent after you read the next section. In many circumstances when using LINQ to SQL, you won’t actually know the name of the type of a variable, so you have to let the compiler infer the type.

Understanding Anonymous Types
Anonymous types is another idea that might be familiar to you from dynamic languages. Anonymous types are useful when you need a transient, fleeting type and you don’t want to do the work to create a class. Here’s an example of creating an anonymous type in C#:
var customer = new {FirstName = “Stephen”, LastName = “Walther”};
Here’s how you would create the same anonymous type in VB.NET:
Dim customer = New With {.FirstName = “Stephen”, .LastName = “Walther”}

Notice that the customer variable is used without specifying a type (this looks very much like JavaScript or VBScript). However, it is important to understand that customer does have a type, you just don’t know its name: It’s anonymous. In a single line of code, we’ve managed to both create a new class and initialize its properties. The terseness brings tears to my eyes.

Anonymous types are useful when working with LINQ to SQL because you’ll discover that you’ll often need to create new types on the fly. For example, you might want to return a class that represents a limited set of database columns when performing a particular query. You’ll need to create a transient class that represents the columns.

Understanding Generics
Yes, I realize that generics are not new to .NET 3.5. However, they are such an important aspect of LINQ to SQL that it is worth using a little space to review this feature. To use generics, you need to import the System.Collections.Generic namespace. I most often use generics by taking advantage of generic collections. For example, if you want to represent a list of strings, you can declare a list of strings like this (in C#):
List<string> stuffToBuy = new List<string>();
stuffToBuy.Add(“socks”);
stuffToBuy.Add(“beer”);
stuffToBuy.Add(“cigars”);
Here’s how you would declare the list of strings in VB.NET:
Dim stuffToBuy As New List(Of String)
stuffToBuy.Add(“socks”)
stuffToBuy.Add(“beer”)
stuffToBuy.Add(“cigars”)

And, by taking advantage of collection initializers, you can now declare a strongly typed list of strings in a single line like this (in C#):
List<string> stuffToBuy2 = new List<string> {“socks”, “beer”, “cigars”};

Unfortunately, VB.NET does not support collection intializers or array initializers.

The List class is an example of a generic because you specify the type of object that the class will contain when you declare the List class. In C#, you specify the type in between the alligator mouths (< >), and in VB.NET you use the Of keyword. Alternatively, we could have  created a List class that contains integers or a custom type such as products or customers represented by a Product or Customer class. A generic collection like a List is superior to a nongeneric collection like an ArrayList because a generic is strongly typed. An ArrayList stores everything as an object. A generic stores everything as a particular type. When you pull an item out of an ArrayList, you must cast it to a particular type before you use it. An item pulled from a generic, on the other hand, does not need to be cast to a type. Generics are not limited solely to collections. You can create generic methods, generic classes, and generic interfaces.

Understanding Lambda Expressions
Lambda expressions, another new language feature introduced with .NET Framework 3.5, provide you with an extremely terse way of defining methods. Imagine, for example, that you want to programmatically wire up a Click event handler to a button control. Listing 18.6 is an example of one way of doing this. Lambda expressions take the notion of the anonymous method one step further. Lambda expressions reduce the amount of syntax required to define a method to its semantic minimum.

Understanding Extension Methods
The idea behind extension methods should also be familiar to anyone who has worked with JavaScript (think prototype). By taking advantage of extension methods, you can add new methods to existing classes. For example, you can make up any method you want and add the method to the String class. I’m constantly HTML-encoding strings because I am paranoid about JavaScript injection attacks. In .NET Framework 2.0, you HTML-encode a string by calling the Server.HtmlEncode() static method, like this:

string evilString = “<script>alert(‘boom!’)<” + “/script>”;
ltlMessage.Text = Server.HtmlEncode(evilString);
In this statement, the static HtmlEncode() method is called on the Server class. Wouldn’t
it be nice if we could just call HtmlEncode() on a string directly like this:
string evilString = “<script>alert(‘boom!’)<” + “/script>”;
ltlMessage.Text = evilString.HtmlEncode();

Using extension methods, we can do exactly that. We can add any methods to a class that we feel like. You create an extension method by creating a static class and declaring a static method that has a special first parameter.

Understanding LINQ
Finally, we get to the topic of LINQ—the last topic we need to examine before we can dive into the true subject of this chapter: LINQ to SQL. LINQ stands for Language Integrated Query. LINQ consists of a set of new language features added to both the C# and VB.NET languages that enable you to perform queries. LINQ enables you to use SQL query–like syntax within C# or VB.NET.

Here’s a simple example of a LINQ query:
var words = new List<string> {“zephyr”, “apple”, “azure”};
var results = from w in words
where w.Contains(“z”)
select w;

The first statement creates a generic List of three strings named “words.” The second statement is the LINQ query. The LINQ query resembles a backward SQL statement. It retrieves all the words from the List that contain the letter z. After you execute the query, the results variable will contain the following list of two words:
zephyr
azure

You can perform a standard LINQ query against any object that implements the IEnumerable<T> interface. An object that implements this interface is called a sequence. Notable examples of sequences are both the generic List class and the standard Array class (so anything you can dump into an array, you can query with LINQ). The C# language supports the following clauses that you can use in a query:
  • from—Enables you to specify the data source and a variable for iterating over the data source (a range variable).
  • where—Enables you to filter the results of a query.
  • select—Enables you to specify the items included in the results of the query.
  • group—Enables you to group related values by a common key.
  • into—Enables you to store the results of a group or join into a temporary variable.
  • orderby—Enables you to order query results in ascending or descending order.
  • join—Enables you to join two data sources using a common key.
  • let—Enables you to create a temporary variable to represent subquery results.

Building a LINQ query is like building a backward SQL query. You start by specifying a from clause that indicates where you want to get your data. Next, optionally, you specify a where clause that filters your data. Finally, you specify a select clause that gives shape to your data (determines the objects and properties you want to return). Under the covers, standard LINQ queries are translated into method calls on the System.Linq.Enumerable class. The Enumerable class contains extension methods that are
applied to any class that implements the IEnumerable<T> interface.

So, the query
var results = from w in words
where w.Contains(“z”)
select w;

is translated into this query by the C# compiler:
var results = words.Where( w => w.Contains(“z”) ).Select( w => w );

The first query uses query syntax and the second query uses method syntax. The two queries are otherwise identical. Notice that the query using method syntax accepts lambda expressions for its Where() and Select() methods. The lambda expression used with the Where() method filters the results so that only words that contain the letter z are returned. The Select() method indicates the object and property to return. If we had passed the lambda expression

w => w.Length to the Select() method, the query would return the length of each word instead of the word itself.

The choice of whether to use query or method syntax when building LINQ queries is purely a matter of preference. Query syntax uses language-specific syntax (C# or VB.NET). Method syntax is language independent. I find that I use method syntax more than query syntax because query syntax is a subset of method syntax. In other words, you can do more with method syntax. That said, in some cases, writing a query in method syntax is just too verbose. For example, writing left outer joins with LINQ to SQL is much easier using query syntax than method syntax. At the end of the day, the choice of whether to use method or query syntax doesn’t really matter because all the query syntax statements get translated by the compiler into method syntax. In the case of standard LINQ, those method calls are calls on methods of the Enumerable class. Lookup the System.Linq.Enumerable class in the SDK documentation to view the full list of methods that the Enumerable class supports. Here is a list of some of the more interesting
and useful methods:
  • Aggregate()—Enables you to apply a function to every item in a sequence.
  • Average()—Returns the average value of every item in a sequence.
  • Count()—Returns the count of items from a sequence.
  • Distinct()—Returns distinct items from a sequence.
  • Max()—Returns the maximum value from a sequence.
  • Min()—Returns the minimum value from a sequence.
  • Select()—Returns certain items or properties from a sequence.
  • Single()—Returns a single value from a sequence.
  • Skip()—Enables you to skip a certain number of items in a sequence and return the remaining elements.
  • Take()—Enables you to return a certain number of elements from a sequence.
  • Where()—Enables you to filter the elements in a sequence.

Creating LINQ to SQL Entities
LINQ to SQL enables you to perform LINQ queries against database data. Currently, you can use LINQ to SQL with Microsoft SQL Server 2000 or Microsoft SQL Server 2005 (including the SQL Server Express editions). Other databases—such as Oracle, DB2, and Access databases—might be supported in the future, but they are not right now. 

To use LINQ to SQL, you need to add a reference to the System.Data.Linq.dll assembly. Select the menu option Website, Add Reference and, beneath the .NET tab, select System.Data.Linq.dll. Performing this action will add a new assembly reference to the <assemblies> section of your web.config file. If you use the Object Rational Designer, this reference is added automatically.

In this section, you learn how to create LINQ to SQL entities. An entity is a C# or VB.NET class that represents a database table (or view). You can use a set of standard custom attributes to map classes and properties to tables and columns. You learn how to create entities both by hand and by using the Object Rational Designer.

Building Entities by Hand
Before you can start performing queries using LINQ to SQL, you need to create one or more entity classes that represent the data you are querying. In this section, you learn how to code these classes by hand.

The Column and Table attribute classes live in the System.Data.Linq.Mapping namespace. Furthermore, notice that the class itself is decorated with a Table attribute. This attribute marks the class as representing a database table. The Column attribute supports the following properties:
  • AutoSync—Indicates whether the value of the property is synchronized with the value of the database column automatically. Possible values are OnInsert, Always, and None.
  • CanBeNull—Indicates whether the property can represent a null value.
  • DbType—Indicates the database column data type.
  • Expression—Indicates the expression used by a computed database column.
  • IsDbGenerated—Indicates that the value of the property is generated in the database (for example, an identity column).
  • IsDiscriminator—Indicates whether the property holds the discriminator value for an inheritance hierarchy.
  • IsPrimaryKey—Indicates whether the property represents a primary key column.
  • IsVersion—Indicates whether the property represents a column that represents a row version (for example, a timestamp column).
  • Name—Indicates the name of the database column that corresponds to the property.
  • Storage—Indicates a field where the value of the property is stored.
  • UpdateCheck—Indicates whether the property participates in optimistic concurrency comparisons.
The Table attribute supports the following single property:
  • Name—Indicates the name of the database table that corresponds to the class.

Some comments about these attributes are needed. First, you don’t need to specify a Name property when your property or class name corresponds to your database column or table name. If, on the other hand, your database table were named Movies and your class were named Movie, you would need to supply the Name property for the Table attribute to map the correct table to the class. Second, you always want to specify the primary key column by using the IsPrimaryKey property. For example, if you don’t specify a primary key column, you can’t do updates against your database using LINQ.

Finally, even though we didn’t do this in our Movie class, you almost always want to include a timestamp column in your database table and indicate the timestamp column by using the IsVersion property. If you don’t do this, LINQ to SQL will check whether the values of all the properties match the values of all the columns before performing an update command to prevent concurrency conflicts. If you specify a version property, LINQ to SQL can check the value of this single property against the database rather than all the columns.

Building Entities with the Object Relational Designer
As an alternative to building entities by hand, you can use the Object Relational Designer. You can simply drag database tables from the Database Explorer (Server Explorer) onto the Designer. The Designer generates the entity classes with the correct attributes automatically. Follow these steps to use the Object Relational Designer:


1. Select the menu option Website, Add New Item to open the Add New Item dialog box.
2. Select the LINQ to SQL Classes template, give it the name MyDatabase, and click the Add button.
3. When prompted to create the LINQ to SQL classes in the App_Code folder, click the Yes button.
4. After the Object Relational Designer opens, drag one or more database tables from the Database Explorer/Server Explorer window onto the Designer surface.

You can view the code that the Designer generates by expanding the MyDatabase.dbml node in the App_Code folder and double-clicking the MyDatabase.designer.cs file. The Designer generates a strongly typed DataContext class named MyDatabaseContext. Each database table that you drag onto the Designer surface gets exposed by the DataContext class as a strongly typed property. The Designer, furthermore, generates a distinct class for each database table you drag onto the Designer. For example, after you drag the Movie table onto the Designer, a new class named Movie is created in the MyDatabase.designer.cs file. The Object Relational Designer attempts to pluralize table names automatically when you add them to the Designer. So, when you drag the Movie table onto the Designer, the Designer generates a DataContext property named Movies. Most of the time, but not all of the time, it gets the pluralization right. You can turn off this feature by selecting the menu option Tools, Options and selecting the Database Tools, O/R Designer tab.

Building Entity Associations
One entity can be associated with another entity. For example, a MovieCategory entity might be associated with one or more Movie entities. If you have defined foreign key relationships between your database tables, these relationships are preserved when you drag your tables onto the Object Relational Designer. The Object Relational Designer will generate entity associations based on the foreign key relationships automatically.

For example, the MovieCategory entity is related to the Movie entity through the Movie entity’s CategoryId property. As long as you have defined a foreign key relationship between Movie.CategoryId and MovieCategory.Id, you can use a query like this following:
MyDatabaseDataContext db = new MyDatabaseDataContext();
var category = db.MovieCategories.Single( c => c.Name == “Drama” );
var query = category.Movies;

The second statement grabs the Drama movie category. The third statement returns all movies associated with the Drama movie category. In this case, we’ve followed a one-tomany relationship and got a list of movies that match a movie category.

You can also go the opposite direction and retrieve the one and only movie category that matches a particular movie:
string categoryName = db.Movies.Single(m=>m.Id==1).MovieCategory.Name;

This query retrieves the name of the movie category associated with the movie that has an ID of 1.

Under the covers, the Object Relational Designer creates the entity relationships by adding association attributes to entity properties. The Object Relational Designer also adds some tricky synchronization logic to keep the properties of associated entities synchronized. Although I wish that I could code all my entities by hand, adding all the logic necessary to get the entity associations to work correctly is too much work. For that reason, I use the Object Relational Designer.

Using the LinqDataSource Control
I want to briefly describe the LinqDataSource control. You can use this control to represent LINQ queries. For example, the page in Listing 18.16 contains a simple search form for searching movies by director. The page uses a LinqDataSource to represent the LINQ query.

Performing Standard Database Commands with LINQ to SQL
In this section, you learn how to use LINQ to SQL as a replacement for working directly with SQL. We’ll start by discussing how LINQ to SQL queries differ from standard LINQ queries. Next, we’ll examine how you can perform standard database queries and commands using LINQ to SQL such as Select, Update, Insert, and Delete commands. We’ll also discuss how you can create dynamic queries with LINQ. Finally, we’ll investigate the very important topic of how you can debug LINQ to SQL queries.

LINQ to Objects versus LINQ to SQL
You can use standard LINQ (LINQ to Objects) with any object that implements the IEnumerable<T> interface. You can use LINQ to SQL, on the other hand, with any object that implements the IQueryable<T> interface. Standard LINQ is implemented with the extension methods exposed by the System.Linq.Enumerable class. LINQ to SQL, on the other hand, uses the extension methods exposed by the System.Linq.Queryable class.

Why the difference?
When you build a query using standard LINQ, the query executes immediately. When you build a query using LINQ to SQL, on the hand, the query does not execute until you start enumerating the results. In other words, the query doesn’t execute until you use a foreach loop to walk through the query results.

Selecting with LINQ to SQL
If you want to perform a simple, unordered select, you can use the following query (assuming that you have an entity named Movie that represents the Movie database table):
MyDatabaseDataContext db = new MyDatabaseDataContext();
var query = db.Movies;

Notice that no LINQ extension methods are used in this query. All the items are retrieved from the Movies table. If you prefer, you can use query syntax instead of method syntax, like this:
MyDatabaseDataContext db = new MyDatabaseDataContext();
var query = from m in db.Movies select m;

Selecting Particular Columns
If you want to select only particular columns, and not all the columns, from a database table, you can create an anonymous type on the fly, like this:
MyDatabaseDataContext db = new MyDatabaseDataContext();
var query = db.Movies.Select( m => new {m.Id, m.Title} );

The expression new {m.Id, m.Title} creates an anonymous type that has two properties: Id and Title. Notice that the names of the properties of the anonymous type are inferred. If you want to be more explicit, or if you want to change the names of the anonymous type’s properties, you can construct your query like this:
MyDatabaseDataContext db = new MyDatabaseDataContext();
var query = db.Movies.Select( m => new {Id = m.Id, MovieTitle = m.Title} );

Selecting Particular Rows If you want to select only particular rows from a database table and not all the rows, you can take advantage of the Where() method. The following LINQ to SQL query retrieves all the movies directed by George Lucas with box office totals greater than $100,000 dollars:
MyDatabaseDataContext db = new MyDatabaseDataContext();
var query = db.Movies
.Where( m => m.Director == “George Lucas” && m.BoxOfficeTotals > 100000.00m)
.Select( m => new {m.Title, m.Director, m.BoxOfficeTotals});

Remember to always call the Where() method before the Select() method. You need to filter your data with Where() before you shape it with Select(). Selecting Rows in a Particular Order You can use the following methods to control the order in which rows are returned from a LINQ to SQL query:
  • OrderBy()—Returns query results in a particular ascending order.
  • OrderByDescending()—Returns query results in a particular descending order.
  • ThenBy()—Returns query results using in an additional ascending order.
  • ThenByDescending()—Returns query results using an additional descending order.

The OrderBy() and OrderBy() methods return an IOrderedQueryable<T> collection instead of the normal IQueryable<T> collection type. If you want to perform additional sorting, you need to call either the ThenBy() or ThenByDescending() method.

Selecting a Single Row
If you want to select a single row from the database, you can use one of the following two query methods:
  • Single()—Selects a single record.
  • SingleOrDefault()—Selects a single record or a default instance.

The first method assumes there is at least one element to be returned (if not, you get an exception). The second method returns null (for a reference type) when no matching element is found.

Performing a LIKE Select
You can perform the equivalent of a LIKE Select with LINQ to SQL in several ways. First, you can use String methods such as Length, Substring, Contains, StartsWith, EndsWith, IndexOf, Insert, Remove, Replace, Trim, ToLower, ToUpper, LastIndexOf, PadRight, and PadLeft with LINQ to SQL queries. For example, the following query returns all movies that start with the letter t:

MyDatabaseDataContext db = new MyDatabaseDataContext();
var query = db.Movies.Where(m=>m.Title.StartsWith(“t”));

Paging Through Records
Doing database paging right when working with ADO.NET is difficult. The SQL language is not designed to make it easy to retrieve a range of records. Doing database paging using LINQ to SQL queries, on the other hand, is trivial. You can take advantage of the following two query methods to perform database paging:
  • Skip()—Enables you to skip a certain number of records.
  • Take()—Enables you to take a certain number of records.

Joining Records from Different Tables
You can perform joins when selecting entities just like you can when joining database tables. For example, imagine that you want to join the Movie and MovieCategory tables on the CategoryId key. Assuming that you have both a Movie and MovieCategory entity, you can use the following query:

MyDatabaseDataContext db = new MyDatabaseDataContext();
var query = db.MovieCategories
.Join(db.Movies, c=>c.Id, m=>m.CategoryId, (c,m)=>new {c.Id,c.Name,m.Title});

Caching Records Getting caching to work with LINQ to SQL is a little tricky. Remember that a LINQ to SQL query represents a query expression and not the actual query results. The SQL command is not executed, and the results are not retrieved until you start iterating through the query results.

Inserting with LINQ to SQL
There are two steps to adding and inserting a new record with LINQ to SQL. First, you need to use the InsertOnSubmit() method to add an entity to an existing table. Next, you call SubmitChanges() on the DataContext to execute the SQL INSERT statement against the database.

Updating with LINQ to SQL
You can use the Attach() method to attach an entity back into a data context. There are three overloads of the Attach() method:
  • Attach(Object)—Enables you to attach an unmodified entity to the data context.
  • Attach(Object, Boolean)—Enables you to attach a modified entity to the data context. The second parameter represents whether or not the entity has been modified. To use this overload, the entity must have a version/timestamp property.
  • Attach(Object, Object)—Enables you to attach a modified entity to the data context. The first parameter represents the modified entity. The second parameter represents the original entity.


Deleting with LINQ to SQL
You can delete an entity with LINQ to SQL by using code like the following:
MyDatabaseDataContext db = new MyDatabaseDataContext();
Movie movieToDelete = db.Movies.Single(m=>m.Id==1);
db.Movies.DeleteOnSubmit( movieToDelete );
db.SubmitChanges();

This code starts by retrieving the record with an Id of 1 from the Movie database table. Next, the Movie entity is removed from the Movies collection by calling the DeleteOnSubmit() method. Finally, this change is submitted to the database.


Building Data Access Components with ADO.NET

Connected Data Access
The ADO.NET Framework encompasses a huge number of classes. However, at its heart, it really consists of the following three classes:
  • Connection—Enables you to represent a connection to a data source.
  • Command—Enables you to execute a command against a data source.
  • DataReader—Enables you to represent data retrieved from a data source.

Most of the other classes in the ADO.NET Framework are built from these three classes. These three classes provide you with the fundamental methods of working with database data. They enable you to connect to a database, execute commands against a database, and represent the data returned from a database.

Now that you understand the importance of these three classes, it’s safe to tell you that they don’t really exist. ADO.NET uses the Provider model. You use different sets of ADO.NET classes for communicating with different data sources.

Using the ObjectDataSource Control

Representing Objects with the ObjectDataSource Control
The ObjectDataSource control includes five main properties:
  • TypeName—The name of the type of object that the ObjectDataSource control represents.
  • SelectMethod—The name of a method that the ObjectDataSource calls when selecting data.
  • UpdateMethod—The name of a method that the ObjectDataSource calls when updating data.
  • InsertMethod—The name of a method that the ObjectDataSource calls when inserting data.
  • DeleteMethod—The name of a method that the ObjectDataSource calls when deleting data.

An ObjectDataSource control can represent any type of object in the .NET Framework. This section discusses several types of objects you might want to represent. For example, you learn how to use the ObjectDataSource control with components that represent collections, ADO.NET DataReaders, DataSets, LINQ to SQL queries, and web services.

You can use the ObjectDataSource control to represent any object (any class that derives from the System.Object class). If the object does not support the IEnumerable interface, the ObjectDataSource control automatically wraps the object in a new object that supports the IEnumerable interface. You can even represent an ASP.NET ListBox control with an ObjectDataSource (not that a ListBox has any interesting methods).

Building Components

Components enable you to reuse application logic across multiple pages or even across multiple applications. For example, you can write a method named GetProducts() once and use the method in all the pages in your website. By taking advantage of components, you can make your applications easier to maintain and extend. For simple applications, there is no reason to take advantage of components. However, as soon as your application contains more than a few pages, you’ll discover that you are repeating the same work over and over again. Whenever you discover that you need to write the same method more than once, you should immediately rip the method out of your page and add the method to a component.

In classic ASP, programmers often used massive and difficult to maintain #INCLUDE files to create libraries of reusable subroutines and functions. In ASP.NET, you use components to build these libraries.

Using the ListView and DataPager Controls

In this chapter, we examine the two new databound controls introduced with the .NET Framework 3.5: the ListView and the DataPager controls. The ListView control is an extremely flexible control. You can use it in many of the same situations in which you would have used the GridView, DataList, FormView, or Repeater control in the past. The DataPager control works with the ListView control. It enables you to add support for paging to a ListView control.

Using the Repeater and DataList Controls

Both the Repeater and DataList controls—the subjects of this chapter—enable you to display a set of data items at a time. For example, you can use these controls to display all the rows contained in a database table. The Repeater control is entirely template driven. You can format the rendered output of the control in any way that you please. For example, you can use the Repeater control to display records in a bulleted list, a set of HTML tables, or even in a comma-delimited list.

The DataList control is also template driven. However, unlike the Repeater control, the default behavior of the DataList control is to render its contents into an HTML table. The DataList control renders each record from its data source into a separate HTML table cell.

In this chapter, you learn how to use both of these controls to display database data. You also learn how to use each of the different types of templates that each of the controls supports. Finally, you can see how to handle the different types of events that the controls expose.

Using the DetailsView and FormView Controls

The DetailsView and FormView controls, the subject of this chapter, enable you to work with a single data item at a time. Both controls enable you to display, edit, insert, and delete data items such as database records. Furthermore, both controls enable you to page forward and backward through a set of data items.

The difference between the two controls concerns the user interface that the controls render. The DetailsView control always renders each field in a separate HTML table row. The FormView control, on the other hand, uses a template that enables you to completely customize the user interface rendered by the control.

Using the DetailsView Control
In this section, you learn how to use the DetailsView control when working with database records. In particular, you learn how to display, page, edit, insert, and delete database records with the DetailsView. You also learn how to format the appearance of the DetailsView control. Displaying Data with the DetailsView Control A DetailsView control renders an HTML table that displays the contents of a single database record. The DetailsView supports both declarative and programmatic databinding.




Due to its reach, power and importance, it is now more important than ever to have a presence on the World Wide Web. In this tutorial, author James Gonzalez uses his Web design expertise and years of training experience to show you how to quickly and easily create basic Web pages and websites using Adobe Dreamweaver, Fireworks and Flash. This is not just a course covering the how of these applications, it also includes the theory needed to understand why and when to use them. At the conclusion of this tutorial, you will know everything needed to design and create attractive, effective Web sites and how to promote them using the top search engines. To being learning, simply click on any of the movie links.


Microsoft's ASP.NET is a free technology that provides programmers with the tools to create dynamic web applications. ASP.NET can be used to create solutions ranging from small, personal websites to enterprise-level web applications and web services. In this course, Microsoft Certified Trainer Mark Long teaches you the basics of ASP.NET 3.5 and show you how to use Microsoft's free Visual Web Developer to create your own ASP.NET 3.5 web applications. To begin learning today, simply click on the movie links.

Using the GridView Control

The GridView control is the workhorse of the ASP.NET Framework. It is one of the most feature-rich and complicated of all the ASP.NET controls. The GridView control enables you to display, select, sort, page, and edit data items such as database records.

GridView Control Fundamentals
In this section, you learn how to take advantage of all the basic features of the GridView control. In particular, you learn how to display, select, sort, page, and edit database data
with a GridView control. We also discuss GridView formatting options.

Displaying Data
The GridView renders its data items in an HTML table. Each data item is rendered in a distinct HTML table row. For example, the page in Listing demonstrates how you can use the GridView to display the contents of the Movies database table (see Figure)