515

The Web Server’s Role

The Web Browser’s Role

The request might look like the following:

GET /default.aspx HTTP/1.1 (Command / URI version of HTTP)

Host: www.northwindtraders.com (Name of the web site)

Text-based HTTP response:

HTTP/1.1 200 OK

Server: Microsoft-IIS/6.0

Content-Type: text/html (This indicator is in the form of a Multipurpose Internet Mail Extensions (MIME) type/Subtype)

Content-Length: 38

<html><body>Hello, world.</body><html>

HTTP Commandas : GET,POST,HEAD,PUT,OPTIONS,DELETE,TRACE,CONNECT,DEBUG

STATUS CODE GROUP : 1xx:Informational, 2xx:Success, 3xx:Redirect Command, 4xx:Client Error, 5xx:Server Error

100:Continue, 200:OK, 201:Created, 300:Multiple Choices, 301:Moved Permanently 302:Found, 400:Bad Request, 401:Unauthorized, 403:Forbidden, 404:Not Found

407:Proxy Athentication Required, 408:Request Time-Out, 413:Req. Entity Too large 500:Internal Server Error, 501:Not Implemented.

MIME Type:text,image/jpeg,gif,audio/basic,video,application/octet

<form method="POST" action="getCustomer.aspx">

Enter Customer ID:

<input type="text" name="Id">

<input type="submit" value="Get Customer">

</form>

ASP.NET Special Folders 

App_Browser : <windir>\Microsoft.NET\Framework\<ver>\CONFIG\Browsers.

App_Code : Contains source code for classes (.cs, .vb, and .jsl files)

App_Global-Resources : Contains resources (.resx and .resources files) that are compiled into satellite assemblies and have a global scope.

App_Local-Resources  : Contains resources (.resx and .resources files) that are scoped to a specific page, user control, or master page in an application.

App_Web-References  : Contains web reference files (.wsdl, .xsd, .disco, and .discomap files) that define references to web services.

App_Themes : A theme consists of files (such as .skin, .css, and image files) that define the appearance of webpages and controls.

A typical ASPX page includes three sections: page directives, code, and page layout.

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master"

AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> , <script runat=”server”></script>

Machine.config,is typically found in the %SystemRoot%\Microsoft.NET\Framework\<versionNumber>\CONFIG\  directory.

MASTER  PAGE:

Attaching Master Pages to Content Pages: <%@ Page Language="VB" MasterPageFile="MySite.Master" %>(content file), <pages masterPageFile="MySite.Master" />(config file)

Connecting to Master Page Properties from Content Pages :

<%@ Page Language="VB" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Login.aspx.vb" Inherits="Login"  title="Contoso Login" %>

<%@ MasterType VirtualPath="~/Site.master" %>

Referencing a control on the master page from a content page is through the Master.FindControl method.

Sample of C# Code

Label MyLabelBrand = (Label)Master.FindControl("LabelBrand");

MyLabelBrand.Text = "Fabrikam";

THEME:

Global Theme :1. <iis_default_root>\Aspnet_client\System_web\<version>\Themes   2. %SystemRoot%\Microsoft.NET\Framework\<version>\ASP.NETClientFiles\Themes

<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />

you can apply the theme to an entire website or to individual applications and folders by adding the <pages Theme=”themeName”> element or the

<pages StyleSheetTheme=”themeName”> element to the <system.web> section of a Web.config file.

A skin file differs from a style sheet in that the skin file uses the attributes of the actual control and not just a set of standard HTML style elements.

skin files will be applied at the control level automatically by ASP.NET. Style elements, on the other hand,can be applied automatically only to HTML items.

Skin files contain two types of skins: default skins and named skins:

<asp:Label runat="server" SkinId="Title" Font-Size="18px" />

<asp:Image runat="server" SkinID="CompanyLogo" ImageUrl="~/App_Themes/Contoso/contoso.jpg" />

1. Theme attributes in the @ Page directive

2. <pages Theme=”themeName”> elements in the <system.web> section of a

Web.config file

3. Local control attributes

4. StyleSheetTheme attributes in the @ Page directive

5. <pages StyleSheetTheme=”themeName”> elements in a Web.config file

CACHING:

Application caching, Page output caching

1.The cache object is available as a property of the Page object. It represents a collection class of type System.Web.Caching.Cache. The Page.Cache property

actually uses an application-wide cache (not just a page-specific cache).

Dependencies: A CacheDependency object identifies a file or a key to another item in the cache. Call the parameter onRemoveCallback to reload the cached item

ex: Cache.Insert("FileCache", File.ReadAllText("SourceFile.txt"),

                         new System.Web.Caching.CacheDependency(Server.MapPath("SourceFile.txt")));

You can also create multiple dependencies for a single cached item.

Absolute expiration:

If you do not wish to use absolute expiration, you can set this property to System.Web.Caching.Cache.NoAbsoluteExpiration.

Ex:Cache.Insert("FileCache", "CacheContents", null, DateTime.Now.AddMinutes(10),Cache.NoSlidingExpiration);

slidingExpiration This is the time (as a TimeSpan object) after which the object should be removed from the cache if it has not been accessed by a user. Set this to

System.Web.Caching.Cache.NoSlidingExpiration if you don’t want to use it.

Ex: Cache.Insert("CacheItem7", "Cached Item 7",null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0));

■ priority This is a CacheItemPriority enumeration value that you can use to determine which objects are removed first when memory starts to run low (this process is called

scavenging). Lower priority objects are removed sooner. The values for priority, from lowest (most likely to be removed) to highest (least likely to be removed) include the

following:

■ Low

■ BelowNormal

■ Normal (Default is equivalent to Normal)

■ AboveNormal

■ High

■ NotRemovable

 onRemoveCallback: This is an event handler that is called when the object is removed from the cache. This can be null if you don’t want to specify a callback method.

Declaratively Configuring Caching for a Single Page

You manage this by adding the @ OutputCache directive to the top of a page’s markup.

OutputCache Attributes : Duration,Location,CacheProfile,NoStore,Shared,VaryByParam,VaryByControl,SqlDependency,VaryByCustom,VaryByHeader

Location: One of the OutputCacheLocation enumeration values, such as Any, Client, Downstream, Server, None, or ServerAndClient. The default is Any.

If you need to make run-time decisions about output caching, you can do so by using the Response.Cache object

Response.Cache.SetExpires : Use this method to specify the number of seconds that the page is to be cached.

Response.Cache.SetCacheability : Use this method to specify an HttpCacheability enumeration value, such as HttpCacheability.Public (which enables caching at both

the client and the server) or HttpCacheability.Server (which enables caching at the server but disables caching at the client).

Response.Cache.SetValidUntilExpires : Pass this method a true value to configure the cache to ignore cache-invalidation headers.

Determining Whether to Return a Cached Page Prior to Rendering:

Respond to the ValidateCacheOutput event and set a valid value for the HttpValidationStatus attribute. Then, from the Page.Load event handler, call the

AddValidationCallback method and pass an HttpCacheValidateHandler object with your method.

public static void ValidateCacheOutput(HttpContext context, Object data,

ref HttpValidationStatus status)

{

if (context.Request.QueryString["Status"] != null)

{

string pageStatus = context.Request.QueryString["Status"];

if (pageStatus == "invalid")

status = HttpValidationStatus.Invalid;

else if (pageStatus == "ignore")

status = HttpValidationStatus.IgnoreThisRequest;

else

status = HttpValidationStatus.Valid;

}

else

status = HttpValidationStatus.Valid;

}

protected void Page_Load(object sender, EventArgs e)

{

Response.Cache.AddValidationCallback(

new HttpCacheValidateHandler(ValidateCacheOutput), null);

}

HttpValidationStatus.Invalid,HttpValidationStatus.Valid,.IgnoreThisRequest

Creating a Cache Page Output Dependency:

Response.AddCacheDependency: This makes the validity of a cached respons dependent on a CacheDependency object.

Response.AddCacheItemDependency and Response.AddCacheItemDependencies: These make the validity of a cached response dependent on one or more other

items in the cache.

Response.AddFileDependency and Response.AddFileDependencies: These make the validity of a cached response dependent on one or more files.

Configuring Caching for an Entire Application:

<caching>

    <outputCacheSettings>

        <outputCacheProfiles>

            <add name="OneMinuteProfile" enabled="true" duration="60"/>

        </outputCacheProfiles>

    </outputCacheSettings>

</caching>

<%@ OutputCache CacheProfile="OneMinuteProfile" VaryByParam="none" %>

Creating Custom Controls:

You can add controls to a form at run time by handling the Page.PreInit event (if you are not using master pages) or the Page.Init event (if you are using master pages and you are adding

the control to a content page). If you add controls in Init or Load, you will need to manually call the Control.ApplyStyleSheetSkin method.

VIEWSTATE:

The Page.ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This object is of the type StateBag. When an ASP.NET

page is processed, the current state of the page and its controls is hashed into a string and saved in the page as an HTML hidden field called __ViewState. If the data is too long for a

single field (as specified in the Page.MaxPageStateFieldLength property), ASP.NET performs view state chunking to split it across multiple hidden fields.

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTEzNjkxMzkwNjRkZAVvqsMGC6PVDmbCxBlPkLVKNahk" />

<configuration> (Application level)

    <system.web>

        <pages viewStateEncryptionMode="Always"/>

         <pages enableViewState="true/false">

    </system.web>

</configuration>

<%@ Page Language="C#" AutoEventWireup="true" ViewStateEncryptionMode="Always"%> (Page level)

COOKIES:

Response.Cookies.Add(New HttpCookie("userId", userId));

Request.Cookies("userId").Value

if (Request.Cookies["lastVisit"] != null)

// Encode the cookie in case the cookie contains client-side script

Label1.Text = Server.HtmlEncode(Request.Cookies["lastVisit"].Value);

else

Label1.Text = "No value defined";

// Define the cookie for the next visit

Response.Cookies["lastVisit"].Value = DateTime.Now.ToString();

Response.Cookies["lastVisit"].Expires = DateTime.Now.AddDays(1);

Response.Cookies["lastVisit"].Path = "/MyApplication";

Response.Cookies["lastVisit"].Domain = "contoso.com";

The size of your cookie is dependent on the browser. Each cookie can be up to 4 KB in length.In addition, you can typically store up to 20 cookies per site.

if you need multiple values in a single named cookie, you can add multiple keys. The following code shows an example

Response.Cookies["info"]["visit"] = DateTime.Now.ToString();

Response.Cookies["info"]["firstName"] = "Tony";

Response.Cookies["info"]["border"] = "blue";

Response.Cookies["info"].Expires = DateTime.Now.AddDays(1);

QUERY STRING:

Request.QueryString["mkt"] - 2,083-character limit on the length of the URL

SESSION STATE:

<configuration>

<system.web>

<sessionState mode="off"/>

</system.web>

</configuration>

http://www.example.com/s(lit3py55t21z5v55vlm25s55)/orderform.aspx

<configuration>

<system.web>

<sessionState cookieless="true"

regenerateExpiredSessionId="true" />

</system.web>

</configuration>

<configuration>

<system.web>

<sessionState mode="SQLServer" cookieless="true" regenerateExpiredSessionId="true"timeout="30"

sqlConnectionString="Data Source=MySqlServer;Integrated Security=SSPI;" compressionEnabled="true" stateNetworkTimeout="30"/>

</system.web>

</configuration>

WEB SERVER CONTROLS:

web server controls inherit from the WebControl class

<system.web>

<pages controlRenderingCompatibilityVersion="3.5"/>

</system.web>

TextBox.TextMode= SingleLine (the default), MultiLine, or Password

CheckBox.CheckedChanged

DropDownList.SelectedIndexChanged

DropDownList.Items.Add

BirthYearDropDownList.SelectedIndex = 85;

ListBox.SelectionMode = Multiple.

Button command: The Command event makes it easy to write a single method that handles the clicks of multiple buttons.

CommandArgument property of the Button control to provide additional information about the command to perform

protected void Button_Command(object sender, CommandEventArgs e)

{

switch (e.CommandName)

{

case "Back":

FeedbackLabel.Text = "Back";

break;

case "Up":

FeedbackLabel.Text = "Up";

break;

case "Forward":

FeedbackLabel.Text = "Forward";

break;

}

}

Set the CausesValidation property to false when you want the Button control to bypass page validation.

Reset and help buttons are examples

The Image Control:

The Image control inherits directly from the WebControl class. The ImageMap and ImageButton controls inherit directly from the Image control.

AlternateText,ImageAlign,DescriptionUrl,GenerateEmptyAlternateText

ImageButton: Has a data type of ImageClickEventArgs, which lets you retrieve the x-coordinate and y-coordinate of the user’s click.

ImageMap control differs from the ImageButton control in that the ImageMap control allows you to define regions or “hot spots”

that cause a postback, whereas clicking anywhere on an ImageButton causes a postback

A hot spot is a predefined area on an image that can be clicked to perform an action. Hot spots can be created to define areas on the image that are displayed by the ImageMap control.

HotSpotMode: The behavior of the HotSpot when it is clicked. This can be NotSet,Inactive, Navigate, or PostBack.

The Calendar control event SelectionChanged,

CompareValidator:Type(string,int,date)ValueToCompare,Operator(Equal, NotEqual, GreaterThan, GreaterThanEqual,

LessThan, LessThanEqual, or DataTypeCheck)

RangeValidatorSalesDate.MinimumValue = "1990";

RangeValidatorSalesDate.MaximumValue =

Cross-Page Posting: Page.PreviousPage

if(Page.PreviousPage == null)

{

LabelData.Text = "No previous page in post";

}

else

{

LabelData.Text =

Server.HtmlEncode(((TextBox)PreviousPage.FindControl("TextBox1")).Text);

}

The SiteMap class provides programmatic access to the site navigation hierarchy from within

your code-behind page. Its two primary properties are RootNode and CurrentNode, and both

return SiteMapNode instances.

The SiteMapNode object represents a node in the site map and has the Title, Url, and Description properties. To access nodes in the hierarchy, you can

use the SiteMapNode instance’s ParentNode, ChildNodes, NextSibling, and PreviousSibling properties.

<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" StartingNodeOffset="0" ShowStartingNode="False" />

We must add a navigational control and connect it to the SiteMapDataSource control : Menu, TreeView, and SiteMapPath

GLOBALIZATION AND ACCESSIBILITY:

ASP.NET uses resource files to support multiple languages. A resource file contains a language-specific set of text for a page or for an entire site.

There are two types of resources in ASP.NET: local and global. Local resources are those specific to a page. Global resources are shared throughout the site.

Local resources must be stored in the special App_LocalResources folder.

Global resources must be stored in the special App_GlobalResources folder.

Each local resource file is page specific. Therefore, it is named by using the page name plus the .resx extension, as in PageName.aspx.resx.

In ASP.NET development, the term culture refers to regional language and formatting differences.

Visual Studio did not generate resources for all the text on the page. Rather, it only generated a resource for those items that were string properties of controls.

Localizing Text Outside of Controls: ASP.NET includes the <asp:Localize> control to assist with localizing text.

<asp:Localize ID="LabelTitle" runat="server" Text="Customer Lookup" meta:resourcekey="LabelTitleResource1"></asp:Localize>

Attaching Controls and Resources Implicitly:

<asp:Button ID="ButtonFind" runat="server" Text="Find" CssClass="submitButton" meta:resourcekey="ButtonFindResource1" />

Attaching Controls and Resources Explicitly:

<asp:Button ID="ButtonFind" runat="server" CssClass="submitButton" Text="<%$ Resources:, ButtonFindResource1.Text %>" />

ASP.NET automatically determines the user’s preferred culture based on information provided by the web browser. When the request is sent to the page, ASP.NET sets the Page.UICulture

property based on the request.

Global Resource: (<%$ Resources:ResourceFile,ResourceID %>)

<asp:Label ID="LocalizeWelcome" Text="<%$ Resources:SharedLocalizedText, WelcomeString %>" runat="server"></asp:Label>

Accessing Resource Values Programmatically:(Resources.ResourceFilename.Resource)

LabelLocalizedWelcome.Text = Resources.SharedLocalizedText.WelcomeString;

Button1.Text = GetLocalResourceObject("Button1.Text").ToString();

Image1.ImageUrl = (String)GetGlobalResourceObject("WebResourcesGlobal", "LogoUrl");

In an ASP.NET webpage, you use two different Page properties to set language and culture : Culture,UICulture(which global or local resources are to be loaded for the page.)

you can also retrieve an array of all available cultures by calling the System.Globalization.CultureInfo.GetCultures method

Setting Culture Declaratively at the Page or Site Level

<globalization uiculture="es" culture="es-MX" />(web.config)

To declare a culture for a webpage, define the UICulture and Culture attributes of the @Page directive, as shown here.

<%@ Page uiculture="es" culture="es-MX" %>

The user controls that you create inherit from the UserControl class

<%@ Register src="AddressUserControl.ascx" tagname="AddressUserControl" tagprefix="uc1" %>

<uc1:AddressUserControl ID="AddressUserControl1" runat="server" AddressType="Home" />

Dynamic loading of control:

AddressUc addressControl =(AddressUc)LoadControl("AddressUserControl.ascx");

form1.Controls.Add(addressControl);

Creating a templated user control: 

A naming container is simply a control container that allows you to search for a contained child control by using FindControl.

The naming container-based class you’ll create inherits from Control and implements the INamingContainer interface

Apply the TemplateContainerAttribute,PersistenceModeAttribute attribute to the ITemplate property

[PersistenceMode(PersistenceMode.InnerProperty)]

[TemplateContainer(typeof(AddressUcContainer))]

public ITemplate LayoutTemplate { get; set; }

Creating Custom Web Server Contols:

A custom web control is a control that you write that inherits either from the WebControl class

or from an existing web server control.

using System.Web.UI;

[assembly: TagPrefix("MyUserControls", "muc")]

[ToolboxBitmap(typeof(LabeledTextBox),"LabeledTbControlIcon.bmp")]

[DefaultProperty("PromptText")]

[Bindable(true),Category("Appearance/Misc"),Description("Text that describes the purpose of the TextBox."),

Localizable(true)]

[ToolboxData(@"<{0}:LabeledTextBox runat=""server"" PromptText="""" PromptWidth=""100"" />")]

public class LabeledTextBox : TextBox

{

public string PromptText { get; set; }

public int PromptWidth { get; set; }

protected override void Render(HtmlTextWriter output)

{

output.Write(

@"<span style=""display;inline-block;width:{0}px"">{1}&nbsp;</span>",

PromptWidth, PromptText);

base.Render(output);

}

}

How to create two instances of the control inside a webpage’s the Page_Init event

protected void Page_Init(object sender, EventArgs e)

{

ContentPlaceHolder content =

(ContentPlaceHolder)this.Master.FindControl("MainContent");

int width = 150;

MyUserControls.LabeledTextBox prompt1 = new

MyUserControls.LabeledTextBox();

prompt1.PromptText = "Enter Name:";

prompt1.PromptWidth = width;

content.Controls.Add(prompt1);

LiteralControl br = new LiteralControl("<br />");

content.Controls.Add(br);

MyUserControls.LabeledTextBox prompt2 = new

MyUserControls.LabeledTextBox();

prompt2.PromptText = "Enter Address:";

prompt2.PromptWidth = width;

content.Controls.Add(prompt2);

}

Inheriting Directly from the WebControl Class:

By default, the Render method will first call RenderBeginTag, then RenderContent, and finally RenderEndTag.

Defining a Custom Icon for Your Control

To embed your image,From the Properties window, you set the Build Action property to Embedded Resource

Default Property for Your Custom Web Server Control:

By using the DefaultProperty attribute class in the System.ComponentModel namespace.

Creating a Custom Designer for a Custom Web Server Control:

Create a new class in your user control that inherits from the ControlDesigner class. This class will override the GetDesignTimeHtml method of the

ControlDesigner class to render separate design-time HTML that can be set based on the property settings of the control instance

using System.Web.UI.Design;

using System.ComponentModel;

namespace MyUserControlsCs

{

[Designer("MyUserControls.LabeledTextBoxDesigner, MyUserControls")]

class LabeledTextBoxDesigner : ControlDesigner

{

private LabeledTextBox _labeledTextBoxControl;

public override string GetDesignTimeHtml()

{

if (_labeledTextBoxControl.PromptText.Trim().Length == 0)

return "<div style='color: Gray'>[Define PromptText]</div>";

else

return base.GetDesignTimeHtml();

}

public override void Initialize(IComponent component)

{

_labeledTextBoxControl = (LabeledTextBox)component;

base.Initialize(component);

return;

}

}

}

Creating a Composite Control:

Composite control is a custom web server control that inherits from the CompositeControl class ,implements the INamingContainer interface and overrides the CreateChildControls method 

A composite control is a custom web control that contains other web server controls. This sounds a lot like a user control. However, a composite control doesn’t provide an ASCX file or a

designer that lets you drag controls on it at design time.

<system.web>

<pages>

<controls>

<add assembly="MyUserControls" namespace="MyUserControls" tagPrefix="muc" />

<add src="~/Controls/AddressUserControl.ascx" tagName="AddressUserControl" tagPrefix="uc1" />

</controls>

</pages>

</system.web>

Configuring a Custom Site-Level Error Page:

<configuration>

<system.web>

<customErrors defaultRedirect="SiteErrorPage.aspx" mode="RemoteOnly">

<error statusCode="403" redirect="RestrictedAccess.aspx" />

</customErrors>

<system.web>

</configuration>

There are many HTTP status codes. Errors fall in the range from 400 to 600. Codes with numbers 400 to 499 are reserved for request errors and codes 500 to 599 are set aside for

server errors.

400 The request is not understood (unintelligible).

403 The user does not have access to the requested resource.

404 The file is not found at the requested URL.

405 The request method is not supported.

406 The requested Multipurpose Internet Mail Extensions (MIME) type is not accepted.

408 The request has timed out.

500 An internal server error has occurred.

503 The capacity of the server has been reached.

Enabling Tracing by Using the Web.config File:

<configuration>

<system.web>

<trace enabled="true" requestLimit="100" pageOutput="false" traceMode="SortByTime" localOnly="false" mostRecent="true" />

<system.web>

</configuration>

view the trace output by navigating to the Trace.axd page on the

current website (http://server/application/trace.axd)

The tracing you enable on the server is not fired for AJAX partial-page requests. Therefore,you will see nothing in the Trace.axd log for these types of requests. Instead, you must use the

features of Sys.Debug to write out trace messages. The Debug class includes the assert, trace, clearTrace, traceDump, and fail methods.

ASP.NET health monitoring provides a set of classes in the System.Web.Management namespace for tracking the health of your application.

<configuration>

<system.web>

<healthMonitoring enabled="true" heartbeatInterval="1">

<rules>

<add name="Heart Beat"

eventName="Heartbeats"

provider="EventLogProvider"

profile="Default"/>

<add name="App Lifetime"

eventName="Application Lifetime Events"

provider="EventLogProvider"

profile="Default"

minInstances="1" minInterval=""

maxLimit="Infinite"/>

</rules>

</healthMonitoring>

<system.web>

<configuration>

REPLACING SETTING:

<configuration>

<system.web>

<customErrors defaultRedirect="GenericError.htm" mode="RemoteOnly" xdt:Transform="Replace">

<error statusCode="500" redirect="InternalError.htm"/>

</customErrors>

</system.web>

</configuration>

<configuration>

<connectionStrings>

<add name="MyDB"

connectionString="Data Source=ReleaseSQLServer;

Initial Catalog=MyReleaseDB;Integrated Security=True"

xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>

</connectionStrings>

</configuration>

REMOVE SETTING:

<configuration>

<system.web>

<compilation xdt:Transform="RemoveAttributes(debug)" />

</system.web>

</configuration>

LAUNCH CONDITIONS:

%HOMEDRIVE = "C:" (verify that the home drive is C)

IISVERSION = "#6" (check for IIS 6.0)

VersionNT = 500 (check for Windows 2000)

You can also check for ranges.

IISVERSION >= "#7" (check for IIS 4.0 or later)

Version9X <= 490 (check for Windows Me or earlier)

WindowsBuild=2600 AND ServicePackLevel=1 (check for Windows XP with Service Pack 1)

(Requirements On Target Machine) and select one of the following:

■ Add File Launch Condition

■ Add Registry Launch Condition

■ Add Windows Installer Launch Condition

■ Add .NET Framework Launch Condition

■ Add Internet Information Services Launch Condition

By default, registry keys are not removed when an application is uninstalled. To automatically remove a registry key during uninstallation, select the key and view the Properties window. Then

set the DeleteAtUninstall property to true.

The Copy Web tool can copy individual files or an entire website. You can select a source and a remote site and move files between them. You can also use the tool to synchronize files.

After the .NET Framework 4 is installed, you need to configure IIS to run ASP.NET 4 applications.by using the aspnet_regiis.exe command-line tool.

Creating AJAX-Enabled Web Forms:

AJAX is a platform-independent technology that works with web applications running in Windows Internet Explorer, Firefox, Safari, and other browsers.

It is an ECMAScript-compliant technology. (ECMAScript is the foundational language from which JavaScript and JScript are derived).

The ScriptManager and ScriptManagerProxy Controls:

<asp:ScriptManager ID="ScriptManager1" runat="server">

</asp:ScriptManager>

By default, the ScriptManager control’s EnablePartialRending property is set to true. This indicates that the page supports partial-page updates.

A page can contain only a single ScriptManager control. Having one inside your user control and another inside the page that consumes the user control,

for example, would be a problem.

The ScriptManagerProxy control can be used either by child pages that use a master page that already defines a ScriptManager control or 

by user and custom controls that you write.

The UpdatePanel Control:

The UpdatePanel control allows you to define areas of a page that should post back to the server independent of the rest of the page.

The UpdatePanel exposes the UpdateMode and ChildrenAsTriggers properties for controlling when a postback should occur to trigger an update of content contained in an UpdatePanel.

UpdateMode, has two possible settings: Always and Conditional

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<Triggers>

<asp:AsyncPostBackTrigger ControlID="ButtonSearch" EventName="Click" />

</Triggers>

<ContentTemplate>

... Grid View markup ...

</ContentTemplate>

</asp:UpdatePanel>

The UpdateProgress Control:

The UpdateProgress control is used to provide information in the form of graphics or text that is displayed to the user during a partial-page update.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>

<asp:GridView ID="GridView1" runat="server">

</asp:GridView>

<asp:UpdateProgress ID="UpdateProgress1" runat="server">

<ProgressTemplate>

<div style="font-size: large">Processing ...</div>

</ProgressTemplate>

</asp:UpdateProgress>

</ContentTemplate>

</asp:UpdatePanel>

The UpdateProgress control can also be associated directly with an UpdatePanel control through the AssociatedUpdatePanelId property.

You set this property to the ID value of the UpdatePanel control to which you want to associate.

By default, the UpdateProgress control is displayed a half-second after the partial-page update starts. 

You can set the DisplayAfter property to the number of milliseconds to wait before displaying the UpdateProgress content.

The Timer Control:

The ASP.NET Timer control is an AJAX control that can be used to update portions of a page on a periodic, timed basis.

You can add a Timer control directly to an UpdatePanel control. The Timer will then automatically

trigger a partial-page update of the UpdatePanel based on a time defined by the Timer control’s Interval property (in milliseconds).

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>

<asp:Image ID="Image1" runat="server"

ImageUrl="~/images/contoso.png" />

<asp:Timer ID="Timer1" runat="server"

Interval="5000" ontick="Timer1_Tick">

</asp:Timer>

</ContentTemplate>

</asp:UpdatePanel>

Adding Script Dynamically to an ASP.NET Page:

An instance of the ClientScriptManager class is exposed through the Page object’s ClientScript property. 

You use this property to add JavaScript to the page at run time, to determine whether a script has already been registered, and for other related tasks. 

To add a script, you define it insidea string or point to its file. You then call the Page.ClientScript.RegisterClientScriptBlock method.

To register a client script to be executed only on page submission, you use the RegisterOnSubmitStatement

method of the ClientScriptManager. This method works in a fashion similar to the operation of RegisterClientScriptBlock.

Registering Client Scripts with the ScriptManager Control:

<asp:ScriptManager ID="ScriptManager1" runat="server">

<Scripts>

<asp:ScriptReference Name="AppScripts.js" />

</Scripts>

</asp:ScriptManager>

ScriptReference sr = new ScriptReference("AppScripts.js");

ScriptManager1.Scripts.Add(sr);

This is useful when you do not have full source code files or are working with precompiled objects.

Creating Your Own Client Callbacks:

Implement the System.Web.UI.ICallbackEventHandler for your ASP.NET page. This serverside

interface is used to set up both the receive call from the client (RaiseCallbackEvent)

and the method that returns processing to the client (GetCallbackResults).

The Microsoft AJAX Library is actually written in JavaScript. It is a set of files that are sent to the browser to provide a base of capabilities on which you can build. 

ScriptManager automatically injects these scripts into the page markup.

The Microsoft AJAX Library is about two things: extending the JavaScript language and providing a base framework for common AJAX tasks.

Global The Global namespace represents an extension of JavaScript itself.Global namespace adds the Type class to JavaScript. 

The Type class is used to register object-oriented items in JavaScript like namespaces, classes,interfaces, and enumerations.

Type.registerNamespace("MyCompany.MyApplication");

The Sys namespace is the root namespace of the AJAX Library. The Global namespace extends JavaScript, whereas the Sys namespace contains a framework for AJAX

programming with JavaScript.

The Sys.Net namespace contains classes focused on the communication between the browser and the server.

The Sys.Serialization namespace is also used to communicate between client and server.

This class is used to serialize and deserialize data to be passed from browser and server in web service calls.

The Sys.Services namespace contains classes for working with the AJAX authentication and profile services from script.

The Sys.WebForms namespace encapsulates the classes for partial-page updates. These classes are used by the UpdatePanel control.

The Sys.UI namespace contains the classes used to add AJAX features to the UI. It includes the Behavior, Control, and DomElement classes

The convention for naming properties in the Microsoft AJAX Library is to use set_propertyName and get_propertyName for the setter and getter, respectively.

//create and register an enumeration

Contoso.Utilities.PasswordStrength = function(){};

Contoso.Utilities.PasswordStrength.prototype =

{

Weak: 1,

Medium: 2,

Strong: 3

}

Contoso.Utilities.PasswordStrength.registerEnum("Contoso.Utilities.PasswordStrength");

//register class as a Sys.Control

AjaxEnabled.PassTextBox.registerClass('AjaxEnabled.PassTextBox', Sys.UI.Control);

//notify loaded

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

The following code shows how you would registercode with the Sys.Application.Load event.

Sys.Application.add_load(PageLoad);

function PageLoad(sender)

{

//page-load code goes here

}

Sys.Application.remove_load(PageLoad);

Another important class with events that you might want to work with is the PageRequestManager class of the Sys.WebForms namespace. 

This class is used for partial-page updates and asynchronous postbacks.

initializeRequest-->beginRequest-->pageLoading-->pageLoaded-->endRequest

Building Client Capabilities with AJAX:

There are three types of client objects you can create with the Microsoft AJAX Library: component, control, and behavior objects.

1.This object provides a base class for creating reusable AJAX components.

2.This object provides a base class for creating reusable, AJAX-enabled client controls. These controls are typically related to a single Document Object Model

(DOM) element (such as an input box or button).

3.This object represents a base class for creating behaviors that can be added to one or more DOM elements at design time. A behavior is not associated with

a single DOM element. Rather, it can extend the DOM elements to which it is applied.

The jQuery.ajax() method enables you to call a web service and then update your page with the results. This method performs an asynchronous HTTP request, passes data to the request, and

gets the results.

Creating a Custom HTTP Handler:

The IHttpHandler interface also requires you to implement the ProcessRequest method. ASP.NET also allows you to use the .ashx extension to automatically register a custom HTTP handler.

you create a page with the .ashx extension and use the @ WebHandler directive to point to your custom HTTP handler code.

Registering the Handler by Using Web.config:

Two ways to register the handler with IIS and ASP.NET: you can either configure IIS to send the request to ASP.NET and your application, or you can add configuration code to

your Web.config file.IIS 6.0

<configuration>

<system.Web>

<httpHandlers>

<add verb="*" path="*.jpg" type="ImageHandler"/>

</httpHandlers>

</system.Web>

</configuration>

IIS 7.0

<configuration>

<system.WebServer>

<handlers>

<add verb="*" path="*.jpg" type="ImageHandler"

name="ImageHandler"/>

</handlers>

</system.WebServer>

</configuration>

Asynchronous programming allows a request to execute on a non-ASP.NET thread.You create an asynchronous handler much like you would a synchronous handler.

You use a similar interface called IHttpAsyncHandler and then override the IsReusable property and the BeginProcessRequest method.

Also provide a callback method that gets called when the asynchronous operation completes. 

Finally, you write code inside the EndProcessRequest method to deal with any cleanup when the process completes.

The method running on the separate thread invokes the callback delegate, which is of type AsyncCallback.

Creating a Custom HTTP Module:

create an HTTP module by writing code that implements the IHttpModule interface.

When each module is created, its Init method is called. You override the IHttpModule.Init method to indicate the application events to which you want to subscribe. 

These are typically application life cycle events such as BeginRequest, AuthenticateRequest, ProcessRequest, and others.

<httpModules>

<add name="LoggingModule" type="LoggingModule" />

</httpModules>

<modules>

<add name="LoggingModule" type="LoggingModule" />

</modules>

ASP.NET Web Service:

An XML web service in ASP.NET is defined in an ASMX file.

<%@ WebService Language="C#" CodeBehind="~/App_Code/Authors.cs" Class="Authors" %>

The WebService class represents a base class for creating XML web services in ASP.NET.

public class Authors : System.Web.Services.WebService

The WebServiceAttribute class can be used to provide information about your web service.

[WebService(Description = "Services related to published authors",Namespace = "http://mydomain.com/")]

public class Authors : WebService

The WebMethodAttribute Class

Your web service exposes web methods.

WebMethod(CacheDuration=300)]

public DataTable GetAuthorTitles(string authorId)

{

...

}

Referencing a Web Service:

A proxy object is generated for you when you reference a web service.

The proxy object takes care of serialization, SOAP messaging,and the related processes.

Authentication and XML Web Services:

You can use Web Services Enhancements (WSE) 3.0 to build secure XML web services.

create a NetworkCredentials class. This class contains the user name, password, and domain information.

You can then create a CredentialCache object to which you add the NetworkCredentials instance. 

You then set the web service’s generated client proxy’s Credentials property to the newly created CredentialCache object.

If you are using Windows Integrated Security between the web server and the web service,

you set the Credentials property of the web service proxy class to System.Net.CredentialCache.DefaultCredentials.

Calling a WCF Service from Client Script by Using AJAX (REST and JSON):

A REST(representational state transfer) service is a web service you create that responds to HTTP GET requests. Clients can

therefore call a REST service the same way they would access a page: by using a URL and a query string.

REST-based services do not use SOAP. Many service-based security models are based on SOAP. Therefore, if the security of the data being passed is a concern, you should use

HTTPS between the client and server for all RESTful services.

WebInvoke attribute. This indicates that the method can be called by an HTTP request. Methods marked with WebInvoke are called by

using HTTP POST.

Creating WCF Data Services:

WCF Data Services allow you to expose and work with data by using the Open Data Protocol(OData).

Transforming Results into JSON:

IEnumerable<Employee> empJson = from emp in employees

where emp.Department == "IT Department"

select emp;

DataContractJsonSerializer ser =

new DataContractJsonSerializer(typeof(IEnumerable<Employee>));

MemoryStream ms = new MemoryStream();

ser.WriteObject(ms, empJson);

string json = Encoding.Default.GetString(ms.ToArray());

ms.Close();

Response.Write(json);

The following shows an example of the message displayed in JSON format. Each employee that belongs to the IT department (see the query) is displayed.

[{"City":"Pittsburgh","Department":"IT Department","First":"Michael","ID":111,"Last":null,{"City":"Redmond","Department":"IT Department","First":"Hank","ID":112,"Last":null}]

The Data Adapter:

The DbDataAdapter object is used to retrieve and update data between a DataTable and a data store (such as a SQL Server database).

Creating Typed DataSets:

A typed DataSet is a DataSet that is based on strongly typed objects that exist at design time.A typed DataSet inherits from the DataSet object.

You can provide an XML Schema Definition (XSD) file to generate a typed DataSet class,also use the DataSet Editor to graphically create and modify an XSD file.

Comparing Data in DataSet Objects

You can use LINQ features to compare data contained in one or more DataTables. These features include the following operators:

■ Distinct Used to return distinct DataRows in a collection

■ Union Joins two like DataTable objects together

■ Intersect Returns a collection of DataRow objects that appear in both DataTable objects

■ Except Returns those DataRow objects that are different between two DataTable objects

You use the DataRowComparer when using these operators. This ensures that DataRows are compared against one another for equal values across columns.

IEnumerable<DataRow> advanceSales = dtAdvance.AsEnumerable().Intersect(dtSales.AsEnumerable(), DataRowComparer.Default);

Mapping with the Command -Line Tool

You can use the SqlMetal.exe command-line tool to generate both DBML files and O/R code for a database.

An entity model inherits from System.Data.Objects.ObjectContext.

You can use the LINQ to SQL Classes template to create a DBML file and drag tables onto the design surface. You can also use the command-line tool,SqlMetal. 

Finally, you can code your entities manually as class files that use the System.Data.Linq.Mapping attributes to identify tables and columns.

Understanding the Data Source Controls:

There are multiple data source controls in ASP.NET,such as direct access to a database, objects, XML, or LINQbased queries.

These controls can be found in the System.Web.UI.WebControls namespace.

You can then use the Configure Data Source Wizard to connect to your data and generate markup for the data source control.

Connecting to data with markup (instead of code) is referred to as declarative data binding, because you are declaring your data access rather than writing ADO.NET code.

<asp:SqlDataSource ID=”SqlDataSource1” runat=”server” ConnectionString=”<%$ ConnectionStrings:NorthwindCnnString %>”

SelectCommand=”SELECT * FROM [Alphabetical list of products]”>

</asp:SqlDataSource>

You can configure an ObjectDataSource control to provide this data to a webpage by setting the TypeName and SelectMethod attributes

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" TypeName="Shipper" SelectMethod="GetAllShippers">

</asp:ObjectDataSource>

<asp:DetailsView ID="DetailsView1" runat="server" DataSourceID="ObjectDataSource1" AllowPaging="true">

</asp:DetailsView>

An ObjectDataSource class can work with any data that implements any of the following interfaces: IEnumerable,IListSource, IDataSource, or IHierarchicalDatasource.

Passing Parameters:

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" TypeName="Customer"

SelectMethod="GetCustomersByCity">

<SelectParameters>

<asp:QueryStringParameter Name="city" QueryStringField="city" Type="String" />

</SelectParameters>

</asp:ObjectDataSource>

http://localhost:5652/DataSourceSamples/Customers.aspx?city=London

Inserting, Updating, and Deleting:

The InsertMethod, UpdateMethod, and DeleteMethod attributes can be mapped

directly to the methods of an object that are to be called when these activities are invoked.

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" TypeName="Shipper"

SelectMethod="GetAllShippers" InsertMethod="InsertShipper"

UpdateMethod="UpdateShipper" DeleteMethod="DeleteShipper">

<DeleteParameters>

<asp:Parameter Name="ShipperId" Type="Int32" />

</DeleteParameters>

<UpdateParameters>

<asp:Parameter Name="shipperId" Type="Int32" />

<asp:Parameter Name="companyName" Type="String" />

<asp:Parameter Name="phone" Type="String" />

</UpdateParameters>

<InsertParameters>

<asp:Parameter Name="companyName" Type="String" />

<asp:Parameter Name="phone" Type="String" />

</InsertParameters>

</asp:ObjectDataSource>

Defining a Filter:

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" TypeName="Customer"

SelectMethod="GetAllCustomers"

FilterExpression="city='{0}'">

<FilterParameters> 

<asp:QueryStringParameter Name="city" QueryStringField="city" Type="String" />

</FilterParameters>

</asp:ObjectDataSource>

Sorting and Paging:

<asp:ObjectDataSource

ID="ObjectDataSource1"

runat="server"

TypeName="Customer"

SelectMethod="GetPagedCustomersSorted"

EnablePaging="true"

SortParameterName="sortCol"

StartRowIndexParameterName="pageStart"

MaximumRowsParameterName="numRecords">

</asp:ObjectDataSource>

Caching Data:

To indicate caching of an ObjectDataSource, you set the EnableCaching attribute to true.

You then set the CacheDuration property to the number of seconds you want to have ASP.NET

cache the data.

<asp:ObjectDataSource

ID="ObjectDataSource1"

runat="server"

TypeName="Shipper"

SelectMethod="GetAllShippers"

EnableCaching="true"

CacheDuration="30">

</asp:ObjectDataSource>

Creating a DataObject Class:

[DataObject()]

public class Shipper

{

[DataObjectMethod(DataObjectMethodType.Select)]

public static DataTable GetAllShippers(){}

}

Connecting to Relational Databases by Using SqlDataSource:

The SqlDataSource control is used to configure access to relational databases such as SQL Server and Oracle. 

It can also be configured to work with Open Database Connectivity (ODBC) and Object Linking and Embedding (OLE) Db data connections.

<asp:SqlDataSource

ID="SqlDataSource1"

runat="server"

ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"

SelectCommandType="Text"

SelectCommand="SELECT * FROM [products] WHERE CategoryID=@CategoryId"

DataSourceMode="DataSet">

<SelectParameters>

<asp:QueryStringParameter

Name="CategoryId"

QueryStringField="catId"

Type="Int16" />

</SelectParameters>

FilterExpression="Discontinued=true"

</asp:SqlDataSource>

Working with Access Data Files and AccessDataSource Controls: 

The AccessDataSource control is meant to connect to and work with Microsoft Access file-based databases (.mdb files). 

This control is very similar to the SqlDataSource control. In fact, it derives from the SqlDataSource class.

One of the main differences between the AccessDataSource control and the SqlDataSource control is how they connect to the database. 

The AccessDataSource control replaces the SqlDataSource.ConnectionString property with the DataFile property. 

<asp:AccessDataSource ID="AccessDataSource1" runat="server"

DataFile="~/App_Data/AccessNorthwind.mdb" SelectCommand="SELECT * FROM [Products]">

</asp:AccessDataSource>

Connecting to an Entity Model by Using EntityDataSource:

<asp:EntityDataSource ID="EntityDataSource1"

runat="server"

ConnectionString="name=NorthwndEntities"

DefaultContainerName="NorthwndEntities"

EnableFlattening="False"

EntitySetName="Orders"

CommandText = "Select o.OrderId as Id, o.UnitPrice, o.Quantity,o.UnitPrice * o.Quantity as LineItemTotal

from OrderDetails as o where o.Discount > 0

order by o.ProductId"

Include="OrderDetails>

</asp:EntityDataSource>

<asp:GridView ID="GridView1" runat="server"

DataSourceID="EntityDataSource1">

</asp:GridView>

OrderBy,Filtering Data,Defining Parameters:

<asp:EntityDataSource ID="EntityDataSource1" runat="server"

ConnectionString="name=NorthwndEntities"

DefaultContainerName="NorthwndEntities"

EntitySetName="OrderDetails"

OrderBy="it.ProductId"

Where="(it.Quantity * it.UnitPrice) > @OrderValue">

<WhereParameters>

<asp:ControlParameter

ControlID="TextBoxValue" Name="OrderValue"

DbType="Int32" PropertyName="Text"

DefaultValue="0" />

</WhereParameters>

</asp:EntityDataSource>

Paging, Sorting, Editing, and Updating Data:

<asp:EntityDataSource ID="EntityDataSource1" runat="server"

ConnectionString="name=NorthwndEntities"

DefaultContainerName="NorthwndEntities"

EntitySetName="OrderDetails"

AutoPage="true"

AutoSort="true"

EnableDelete="true"

EnableInsert="true"

EnableUpdate="true">

</asp:EntityDataSource>

<asp:GridView ID="GridView1" runat="server"

DataSourceID="EntityDataSource1"

AllowPaging="True"

AllowSorting="True">

<Columns>

<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />

</Columns>

</asp:GridView>

Connecting to XML Data by Using XmlDataSource:

<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/App_Data/products.xml"

TransformFile="~/App_Data/ProductTransform.xsl" >

</asp:XmlDataSource>

<asp:TreeViewid="TreeView1" runat="server" DataSourceID="XmlDataSource1">

<DataBindings>

<asp:TreeNodeBinding DataMember="Name" TextField="#InnerText" />

<asp:TreeNodeBinding DataMember="Category" TextField="#InnerText" />

<asp:TreeNodeBinding DataMember="QuantityPerUnit" TextField="#InnerText" />

<asp:TreeNodeBinding DataMember="UnitPrice" TextField="#InnerText" />

</DataBindings>

</asp:TreeView>

Filtering XML with the XmlDataSource Control:

<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/App_Data/products.xml"

TransformFile="~/App_Data/ProductTransform.xsl"

XPath="/Products/Product[Category='Category: Beverages']" >

</asp:XmlDataSource>

Connecting to LINQ-Based Data by Using LinqDataSource:

You can use the LinqDataSource control to easily connect to data supplied by any data source that represents a collection of data. 

This includes lists, arrays, LINQ to SQL objects, and more.

In this way, it is the most flexible data source control and typically requires the least amount of supporting code.

<asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="NorthwindDataContext" EnableDelete="True"

EnableInsert="True" EnableUpdate="True" OrderBy="CompanyName" TableName="Suppliers"

Where="Country == @Country">

<WhereParameters>

<asp:QueryStringParameter DefaultValue="USA" Name="Country" QueryStringField="country" Type="String" />

</WhereParameters>

</asp:LinqDataSource>

<asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="NorthwindDataContext" EntityTypeName=""

TableName="Suppliers"

Where="Country == @Country"

Select="new ( SupplierId As Id,

     CompanyName As Name,

              Address + ' ' + City + ' ' + PostalCode As Location)">

<WhereParameters>

<asp:QueryStringParameter DefaultValue="USA" Name="Country" QueryStringField="country" Type="String" />

</WhereParameters>

</asp:LinqDataSource>

Connecting to Site Navigation Data by Using SiteMapDataSource:

The SiteMapDataSource control is used to connect to site navigation data for your website.

The data for this control is defined in a special XML file called a web.sitemap.

Data-Bound Controls:

The data-bound controls in ASP.NET can be classified as simple, composite, hierarchical, or visualization controls. 

1) Simple data-bound controls are the controls that inherit from ListControl.

2) Composite data-bound controls are classes that inherit from CompositeDataBoundControl, such

as GridView, DetailsView, FormsView, and similar controls. 

3) Hierarchical data-bound controls are the Menu and TreeView controls. 

4) Finally, the Chart control is a data visualization control that inherits directly from DataBoundControl.

The BaseDataBoundControl is the first control in the hierarchy (inheriting from WebControl).

A template control is a control that has no default UI. The control simply provides the mechanism for binding to data.

The DataBinder class provides the static Eval method to help bind data.

<%# Eval("Price", "{0:C}") %>

The Eval method is great for one-way (or read-only) data binding,cannot be used for insert and edit scenarios.

The Bind method of the DataBinder class, however, can be used for two-way data binding.

Data-Bound Controls:

LIST BOX:

<asp:ListBox ID="ListBox1" runat="server" DataSourceID="SqlDataSource1" DataTextField="CompanyName" DataValueField="ShipperID">

</asp:ListBox>

The SelectedIndex property lets you get or set the index of the selected item in the ListControl.

If you only need to access the value of the selected ListItem, use the SelectedValue property.

The ListControl also contains the property called AppendDataBoundItems, which can be set to true to keep all items that are currently in the ListControl

The ListControl also provides the SelectedIndexChanged event, which is raised when the selection in the list control changes between posts to the server

DropDownList:

To determine the item that the user has selected, you can retrieve the SelectedValue, SelectedItem, or SelectedIndex property.

<asp:DropDownList runat="server" Width="250px" ID="DropDownList1" DataSourceID="SqlDataSource1" DataTextField="TerritoryDescription" DataValueField="TerritoryID" >

</asp:DropDownList>

Label1.Text = "You selected TerritoryID: " + DropDownList1.SelectedValue;

ListBox:

The ListBox control is used to select and display items from a longer list rather than one at a time as done in the DropDownList.

<asp:ListBox runat="server" Height="225px" Width="275px"

ID="ListBox1" Rows="13" DataSourceID="SqlDataSource1" DataTextField="TerritoryDescription" DataValueField="TerritoryID"

SelectionMode="Multiple">

</asp:ListBox>

foreach (ListItem i in ListBox1.Items)

{

if(i.Selected)

Label1.Text = Label1.Text + "You selected TerritoryID: " + i.Value + "<br />";

}

The CheckBoxList and RadioButtonList Controls:

These controls contain a RepeatColumns property that is used to indicate the number of columns to be displayed horizontally. 

In addition, the RepeatDirection can be set to Horizontal or Vertical (the default) to indicate whether the data should be rendered across by rows or down by columns.

<asp:CheckBoxList runat="server" ID="CheckBoxList1" DataSourceID="SqlDataSource1" DataTextField="TerritoryDescription"

DataValueField="TerritoryID" RepeatColumns="5">

</asp:CheckBoxList>

Use the SelectedValue property to determine the item that has been selected for the RadioButtonList.

The BulletedList Control:

If the control is set to render as bulleted,select the bullet style to Disc, Circle, or Square.

If the BulletedList control is set to render numbered, you can set the BulletStyle to

LowerAlpha, UpperAlpha, LowerRoman, and UpperRoman fields

The classes that inherit from CompositeDataBoundControl directly are FormView, DetailsView, and GridView

The GridViewRow object inherits from the TableRow object, which contains the Cells property. This property is a collection of DataControlFieldCell objects.

Row = GridViewRow

Column = DataControlField

Cell = DataControlFieldCell

The GridView control has an InitializeRow method that is responsible for creating a new GridViewRow and the row’s cells by making calls to the overridden

InitializeCell method when the row is being created.

Using Styles to Format the Grid View Control:

GridViewStyle and a HeaderStyle, FooterStyle, RowStyle, AlternatingRowStyle, SelectedRowStyle, EditRowStyle, and more. You can set these styles declaratively at design time.

In addition, the RowCreated and RowDataBound events can also be used to control the style programmatically.

The DetailsView Control:

The DetailsView control is used to display the values of one record at a time from a data source in an HTML table.

The DetailsView control does not directly support sorting, whereas the GridView control does.

the DetailsView can also be used in combination with other controls such as the GridView, ListBox, or DropDownList.

The FormView Control:

Like DetailsView, the FormView control is used to display a single record from a data source. However, the FormView control does not automatically display the data in a predefined HTML table. 

Instead, it allows developers to create templates that define how the data should be displayed.

The Repeater Control:

The Repeater control also uses templates to define custom binding.

The Repeater control is a read-only template. That is, it supports only the ItemTemplate.

It does not implicitly support editing, insertion, and deletion.

The ListView Control:

The ListView control also uses templates for the display of data.

LayoutTemplate,GroupTemplate,ItemSeparatorTemplate

The Chart Control:

The Chart control allows you to display data by using chart visualization. 

The big difference is that you then indicate fields from the data source that should be bound to an axis or data series in a chart.

When the chart control runs on the server, it generate a graphic file (which is a PNG file by default, but you can change this

setting) and then sends this to the browser as part of the response.

The DataList Control:

The DataList control works like the Repeater control. It repeats data for each row in your data set,

and it displays this data according to your defined template.

The DataList control does not automatically use a data source control to edit data. Instead,

it provides command events in which you can write your own code for these scenarios.

Add a Button control to one of the templates and set the button’s CommandName property to the edit, delete, update, or cancel keyword

Hierarchical Data-Bound Controls:

The HierarchicalDataBoundControl control serves as a base class for controls that render data in a hierarchical fashion.

The classes that inherit from HierarchicalDataBoundControl are TreeView and Menu.

The TreeView Control:

The TreeView control is a data-bound control that is used to display hierarchical data, such as

a listing of files and folders, or a table of contents in a tree structure. Each entry in the tree is

called a node. The nodes of this control can be bound to XML, tabular, or relational data.

The Menu Control:

The Menu control is a data-bound control that is used to display hierarchical data in the form

of a menu system. The Menu control is often used in combination with a SiteMapDataSource

control for navigating a website.

Registering Your Data Context with the MetaModel:

The next step is to register your data context with System.Web.DynamicData.MetaModel. 

The MetaModel defines the connectivity or mapping between the scaffold templates and your data layer.

You register your data context inside the Global.asax file.

void Application_Start(object sender, EventArgs e) {

RegisterRoutes(RouteTable.Routes);

}

MetaModel is actually defined as a private application variable and exposed as a read-only property.

public static void RegisterRoutes(RouteCollection routes) {

DefaultModel.RegisterContext(typeof(NorthwindDataContext),

new ContextConfiguration() { ScaffoldAllTables = true });

routes.Add(new DynamicDataRoute("{table}/{action}.aspx") {

Constraints = new RouteValueDictionary(

new { action = "List|Details|Edit|Insert" }),

Model = DefaultModel

});

}

The Dynamic Data Classes:

ASP.NET Dynamic Data relies on several classes inside the System.Web.DynamicData namespace.

A DynamicDataRoute class is created and added to the RouteTable.Routes collection inside the Global.asax file.

[MetadataType(typeof(EmployeeMetadata))]

public partial class Employee

{

}

public class EmployeeMetadata

{

[UIHint("CalendarPicker")]

public object HireDate { get; set; }

[UIHint("CalendarPicker")]

public object BirthDate { get; set; }

}

The validation attributes include Range, StringLength, Required, and RegularExpression.

[ScaffoldColumn(false)]

public object QuantityPerUnit { get; set; }

[DisplayFormat(ApplyFormatInEditMode=false,

DataFormatString="{0:c}")]

[Display(Name = "Price")]

public object UnitPrice { get; set; }

[Range(1, 144, ErrorMessage = "Quantity must be between 1 and 144")]

public object ReorderLevel { get; set; }

There are partial methods for OnChanging and OnChanged for each property in the data context.

If you encounter an error, you throw a ValidationException from System.ComponentModel.DataAnnotations.

Creating Custom Field Templates:

Recall that the Dynamic Data templates include the FieldTemplates folder. Inside this folder is a set of user controls that inherit from FieldTemplateUserControl.

Configuring a User Profile Provider :

You store and retrieve user profiles in a database by using a provider class. This class abstracts the storage and retrieval of the profile information from the actual profile itself.

ASP.NET provides a default, configured provider for use with user profiles.  This provider is the SqlProfileProvider class found in the System.Web.Profile namespace.

<profile>

<providers>

<add name="AspNetSqlProfileProvider" connectionStringName="LocalSqlServer" applicationName="/"

type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>

</providers>

</profile>

Configuring a New Profile Database:

ASP.NET provides the Aspnet_regsql.exe to generate the database schema on the database server.The following example configures the profile table (-A p) for the server (-S) of localhost by

using Windows credentials (-E).

aspnet_regsql.exe -E -S localhost -A p

Defining the User Profile:

<configuration>

 <system.web>

  <profile>

   <properties>

    <add name="FirstName" />

    <add name="LastName" />

    <add name="LastVisit" type="System.DateTime" />

    <group name="Address">

      <add name="Street" />

      <add name="City" />

      <add name="PostalCode" />

    </group>

    <add name="Position" type="MyNamespace.OrgPosition" serializeAs="Binary" />

   </properties>

  </profile>

 </system.web>

</configuration>

Anonymous User Profiles:

<anonymousIdentification enabled="true" />

<profile>

<properties>

<add name="FirstName" allowAnonymous="true" />

<add name="LastName" allowAnonymous="true" />

<add name="LastVisit" type="System.DateTime" allowAnonymous="true" />

</properties>

</profile>

Migrating Anonymous User Profiles:

To avoid losing the user’s anonymous profile information, you respond to the MigrateAnonymous event that ASP.NET raises when a user

logs on to your site.

Setting and Saving a User Profile:

You can save a user profile by simply setting the values of individual properties and then calling the Profile.Save method

Web Site Administration Tool (WSAT) to define and manage users, roles,and security on your site.

When you select web-based security by using the WSAT, ASP.NET automatically creates the ASPNETDB.mdf file for your site and stores it in the App_Data directory.

It also updates your site’s Web.config file to enable this security feature.

<configuration>

  <system.web>

     <authentication mode="Forms" >

       <forms loginUrl="Login.aspx" />

     </authentication>

     <roleManager enabled="true" />

  </system.web>

</configuration>

<authorization>

<allow roles="Site Owner" />

</authorization>

The Login Control Classes:

There are seven controls in ASP.NET for managing the logon information of a user. These seven controls are grouped together as the logon controls.

ContinueDestinationPageUrl property should be set to the page to which you want users to go after they have completed their

account creation process. In addition, you can add your own code to the ContinueButtonClick event to add processing when the user clicks the final step in the wizard.

The FormsAuthentication Class:

The FormsAuthentication class is the basis for all forms authentication in ASP.NET.The class includes the following read-only properties.

1) FormsCookieName This property returns the configured cookie name used for the current application.

2) FormsCookiePath This property returns the configured cookie path used for the current application.

3) RequireSSL This property gets a value indicating whether the cookie must be transmitted by using SSL (that is, over HTTP Secure [HTTPS] only).

This will ensure that forms authentication is encrypted.

4) SlidingExpiration This property gets a value indicating whether sliding expiration is enabled. If sliding expiration is enabled, the user’s authentication timeout is reset with

every web request

The Membership Class:

The logon controls discussed previously use the methods of the System.Web.Security.Membership class to implement their functionality.

The Roles Class:

Role management consists of a set of classes and interfaces that establish roles for the current user and manage role information.

The most useful of these classes is System.Web.Security.Roles.

Roles.AddUserToRole(CreateUserWizard1.UserName, "Users");

Windows authentication is primarily useful for intranet sites in an Active Directory domain environment.

<configuration>

<system.web>

<authentication mode="Windows" />

<authorization>

<deny users="?" />

</authorization>

</system.web>

</configuration>

<deny users=”?” /> within <authorization> requires users to be authenticated, whereas

specifying <allow users=”*” /> within <authorization> bypasses authentication entirely.

<configuration>

<system.web>

<authentication mode="Windows" />

<authorization>

<deny users="?" />

</authorization>

</system.web>

<location path="Protected">

<system.web>

<authorization>

<allow roles="CONTOSO\IT" />

</authorization>

</system.web>

</location>

</configuration>

The ASP.NET MVC Architecture:

Requests to an ASP.NET MVC application are handled by the UrlRoutingModule HttpModule.

A controller is a class that inherits from System.Web.Mvc.Controller.

The ASP.NET MVC Request Life Cycle:

UrlRoutingModule takes a request and looks up a Route object in the RouteTable collection.

You add routes to this collection inside the Global.asax file’s RegisterRoutes method (which is called by Application_Start).

The request is then mapped to a route, and RouteData and RequestContext objects are created to represent the route and the request, respectively.

Processing of the RequestContext object is then passed to classes in the System.Web.Mvc namespace.

The MvcRouteHandler class handles the routing to your MVC controller class.

Controller then uses ControllerActionInvoker to determine which action to run based on the request.

Defining Application Areas:

An area in ASP.NET MVC is a subset of the project structure based on a logical grouping.

ASP.NET MVC site with two additional areas:DataAdministration and SecurityManagement.

The Application_Start method in the Global.asax file then includes the AreaRegistration.

RegisterAllAreas() call to ensure that the area mapping is carried out.

Model Validation Rules:

One of the easiest ways to add validation and business rules to your model is to use the DataAnnotations classes.

[Required(ErrorMessage = "Customer id is required.")]

public object CustomerId { get; set; }

The rules you define for your model will automatically be processed by the ASP.NET MVC validation engine.

Model.IsValid property to determine whether your model has thrown any validation errors.

WebFormViewEngine class is used to render the results to the user.

Returning Different ActionResult Objects:

The return type for most action methods is ActionResult. The ActionResult class is actually a base class that can be used to define several different result types.

The System.Web.Mvc.ViewDataDictionary is a collection of objects that are referenced by string keys.

Using Action Filters:

The ASP.NET MVC framework allows you to run code both before an action method is called or after it has run.

Action filters are attribute classes that implement the FilterAttribute base class.

ASP.NET MVC also includes several predefined action filters, including Authorize, OutputCache and HandleError.

Standard views (pages with the .aspx extension) inherit from the System.Web.Mvc.ViewPage class.

A URL pattern is a defined set of segments delimited by a slash (/), as in Customer/Index/5.In this case, there are three segments in the URL pattern. When the request is received, the

URL is broken into segments and placeholders.

These segments are stored as key-value pairs,in which the key is the placeholder defined in the routing definition and the value is the value

from the URL. In ASP.NET MVC, these placeholder keys are defined as {controller}/{action}/{id}.

This routing is established by calling routes.MapRoute in the Global.asax file. Routes is a RouteCollection instance.

You define a default route parameter by using a RouteValueDictionary object. By using this object, you can pass route parameter names and default values.

routes.MapRoute("Default",

"{controller}/{action}/{id}",

new { controller = "Home", action = "Index", id = UrlParameter.Optional } );

routes.MapRoute("MonthYear",

"{month}/{year}",

new RouteValueDictionary(new { month = DateTime.Now.Month,

year = DateTime.Now.Year}),

new RouteValueDictionary(new { month = @"\d{2}", year = @"\d{4}" }));

You can prevent physical files from circumventing routing. You do so in an ASP.NET MVC application by setting the RouteCollectionExtension object’s RouteExistingFiles property to

true, as in routes.RouteExistingFiles = true, inside the Global.asax file.