ASP.NET

0
108

ASP.NET – Introduction

Whead put on is ASP.NET?

ASP.NET is a web generatement platform, which provides a programming model, a comprehensive softbattlee infrastructure and various services requireddishdish to construct up robust web applications for PC, as well as mobile devices.

ASP.NET works on top of the HTTP protocol, and uses the HTTP commands and policies to set a bcollectionser-to-server bilateral communication and cooperation.

ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiintroduced codes, generated uperform the extensible and reusable components or objects present in .Net framework. These codes can use the entire hierarchy of coursees in .Net framework.

The ASP.NET application codes can be generated in any kind of of the following languages:

  • C#
  • Visual Basic.Net
  • Jscript
  • J#

ASP.NET is used to produce interworkionive, data-driven web applications over the internet. It consists of a huge number of manages such as text containeres, buttons, and labels for assembling, configuring, and manipulating code to generate HTML pages.

ASP.NET Web Forms Model

ASP.NET web forms extend the workionuallyt-driven model of interworkionion to the web applications. The bcollectionser submit is a web form to the web server and the server returns a compallowe markup page or HTML page in response.

All claynt aspect user workionivilinks are forbattimmediateeded to the server for stateful procesperform. The server processes the out presently generally thereput of the claynt workionions and triggers the reworkionions.

Now, HTTP is a stateless protocol. ASP.NET framework helps in storing the information regarding the state of the application, which consists of:

  • Page state
  • Session state

The page state is the state of the claynt, i.e., the content of various input fields in the web form. The session state is the collective information obtained from various pages the user visited and worked with, i.e., the general session state. To clear the concept, allow us conaspectr an example of a shopping cart.

User adds items to a shopping cart. Items are selected from a page, say the items page, and the total collected items and price are shown on a various page, say the cart page. Only HTTP cannot maintain track of all the information coming from various pages. ASP.NET session state and server aspect infrastructure maintains track of the information collected globally over a session.

The ASP.NET operatetime carries the page state to and from the server acombination page requests while generating ASP.NET operatetime codes, and incorporates the state of the server aspect components in hidden fields.

This way, the server becomes abattlee of the general application state and operates in a 2-linkreddishdish connected way.

The ASP.NET Component Model

The ASP.NET component model provides various constructing blocks of ASP.NET pages. Basically it is an object model, which describes:

  • Server aspect counterparts of almany kind of all HTML elements or tags, such as <form> and <input>.

  • Server manages, which help in generateing complex user-interface. For example, the Calendar manage or the Gridwatch manage.

ASP.NET is a technology, which works on the .Net framework thead put on contains all web-related functionalilinks. The .Net framework is made of an object-oriented hierarchy. An ASP.NET web application is made of pages. When a user requests an ASP.NET page, the IIS delegates the procesperform of the page to the ASP.NET operatetime system.

The ASP.NET operatetime transforms the .aspx page into an instance of a course, which inherit is from the base course page of the .Net framework. Therefore, every ASP.NET page is an object and all it is components i.e., the server-aspect manages are furthermore objects.

Components of .Net Framework 3.5

Before going to the next session on Visual Studio.Net, allow us go through at the various components of the .Net framework 3.5. The following table describes the components of the .Net framework 3.5 and the job they perform:

Components and their Description

(1) Common Language Runtime or CLR

It performs memory management, exception handling, debugging, security checcalifornia king, thread execution, code execution, code securety, verification, and compilation. The code thead put on is immediately managed simply by the CLR is calintroduced the managed code. When the managed code is compiintroduced, the compiler converts the source code into a CPU independent intermediate language (IL) code. A Just In Time(JIT) compiler compiles the IL code into native code, which is CPU specific.

(2) .Net Framework Class Library

It contains a huge library of reusable types. coursees, interfaces, structures, and enumerated values, which are collectively calintroduced types.

(3) Common Language Specification

It contains the specifications for the .Net supinterfaceed languages and implementation of language integration.

(4) Common Type System

It provides guidecollections for declaring, uperform, and managing types at operatetime, and combination-language communication.

(5) Metadata and Assemblays

Metadata is the binary information describing the program, which is either storeddishdish in a interfaceable executable file (PE) or in the memory. Assembly is a logical device consisting of the assembly manifest, type metadata, IL code, and a set of resources like image files.

(6) Windows Forms

Windows Forms contain the graphical representation of any kind of window displayed in the application.

(7) ASP.NET and ASP.NET AJAX

ASP.NET is the web generatement model and AJAX is an extension of ASP.NET for generateing and implementing AJAX functionality. ASP.NET AJAX contains the components thead put on enable the generateer to update data on a website without presently generally there a compallowe reload of the page.

(8) ADO.NET

It is the technology used for functioning with data and databases. It provides access to data sources like SQL server, OLE DB, XML etc. The ADO.NET enables interinterconnection to data sources for retrieving, manipulating, and updating data.

(9) Windows Workflow Foundation (WF)

It helps in constructing workflow-based applications in Windows. It contains workionivilinks, workflow operatetime, workflow designer, and a rules engine.

(10)Windows Presentation Foundation

It provides a separation between the user interface and the business logic. It helps in generateing visually stunning interfaces uperform documents, media, 2 and 3 dimensional graphics, animations, and more.

(11) Windows Communication Foundation (WCF)

It is the technology used for constructing and executing connected systems.

(12) Windows CardSpace

It provides securety for accesperform resources and sharing private information on the internet.

(13) LINQ

It imparts data querying capabililinks to .Net languages uperform a syntax which is similar to the tradition query language SQL.

ASP.NET – Environment Setup

ASP.NET provides an abstrworkionion layer on top of HTTP on which the web applications are built. It provides high-level entilinks such as coursees and components within an object-oriented paradigm.

The key generatement tool for constructing ASP.NET applications and front aspect ends is Visual Studio. In this particular tutorial, we work with Visual Studio 2008.

Visual Studio is an integrated generatement environment for writing, compiling, and debugging the code. It provides a compallowe set of generatement tools for constructing ASP.NET web applications, web services, desktop applications, and mobile applications.

The Visual Studio IDE

The brand new project window enables chooperform an application template from the available templates.

Visual Studio IDE

When you start a brand new web site, ASP.NET provides the starting folders and files for the site, including 2 files for the 1st web form of the site.

The file named Default.aspx contains the HTML and asp code thead put on degreats the form, and the file named Default.aspx.cs (for C# coding) or the file named Default.aspx.vb (for VB coding) contains the code in the language you have chosen and this particular code is responsible for the workionions performed on a form.

The primary window in the Visual Studio IDE is the Web Forms Designer window. Other supinterfaceing windows are the Toolcontainer, the Solution Explorer, and the Properlinks window. You use the designer to design a web form, to add code to the manage on the form so thead put on the form works according to your own own need, you use the code editor.

Worcalifornia king with Views and Windows

You can work with windows in the following ways:

  • To change the Web Forms Designer from one watch to one more, click on the Design or source button.

  • To shut a window, click on the shut button on the upper proper corner and to reddishdishisplay, select it from the View menu.

  • To hide a window, click on it is Auto Hide button. The window then changes into a tab. To display again, click the Auto Hide button again.

  • To change the size of a window, simply drag it.

watchs and windows

Adding Folders and Files to your own own Website

When a brand new web form is generated, Visual Studio automatically generates the starting HTML for the form and displays it in Source watch of the web forms designer. The Solution Explorer is used to add any kind of other files, folders or any kind of existing item on the web site.

  • To add a standard folder, proper-click on the project or folder under which you are going to add the folder in the Solution Explorer and choose New Folder.

  • To add an ASP.NET folder, proper-click on the project in the Solution Explorer and select the folder from the list.

  • To add an existing item to the site, proper-click on the project or folder under which you are going to add the item in the Solution Explorer and select from the dialog container.

Projects and Solutions

A typical ASP.NET application consists of many kind of items: the web content files (.aspx), source files (.cs files), assemblays (.dll and .exe files), data source files (.mdb files), references, icons, user manages and miscellaneous other files and folders. All these files thead put on create up the website are contained in a Solution.

When a brand new website is generated. VB2008 automatically generates the solution and displays it in the solution explorer.

Solutions may contain one or more projects. A project contains content files, source files, and other files like data sources and image files. Generally, the contents of a project are compiintroduced into an assembly as an executable file (.exe) or a dynamic link library (.dll) file.

Typically a project contains the following content files:

  • Page file (.aspx)
  • User manage (.ascx)
  • Web service (.asmx)
  • Master page (.master)
  • Site chart (.sitechart)
  • Website configuration file (.config)

Building and Running a Project

You can execute an application simply by:

  • Selecting Start
  • Selecting Start Without presently generally there Debugging from the Debug menu,
  • presperform F5
  • Ctrl-F5

The program is built meaning, the .exe or the .dll files are generated simply by selecting a command from the Build menu.

ASP.NET – Life Cycle

ASP.NET life cycle specifies, how:

  • ASP.NET processes pages to produce dynamic out presently generally thereput
  • The application and it is pages are fastiated and processed
  • ASP.NET compiles the pages dynamically

The ASP.NET life cycle can be divided into 2 groups:

  • Application Life Cycle
  • Page Life Cycle

ASP.NET Application Life Cycle

The application life cycle has the following stages:

  • User creates a request for accesperform application resource, a page. Bcollectionser sends this particular request to the web server.

  • A unified pipecollection receives the 1st request and the following workionuallyts conaspectr place:

    • An object of the course ApplicationManager is generated.

    • An object of the course HostingEnvironment is generated to provide information regarding the resources.

    • Top level items in the application are compiintroduced.

  • Response objects are generated. The application objects such as HttpContext, HttpRequest and HttpResponse are generated and preliminaryized.

  • An instance of the HttpApplication object is generated and assigned to the request.

  • The request is processed simply by the HttpApplication course. Different workionuallyts are raised simply by this particular course for procesperform the request.

ASP.NET Page Life Cycle

When a page is requested, it is loaded into the server memory, processed, and sent to the bcollectionser. Then it is unloaded from the memory. At every of these steps, methods and workionuallyts are available, which can be overridden according to the need of the application. In other words, you can write your own own own code to override the default code.

The Page course generates a hierarchical tree of all the manages on the page. All the components on the page, except the immediateives, are part of this particular manage tree. You can see the manage tree simply by adding trace= "true" to the page immediateive. We will cover page immediateives and tracing under 'immediateives' and 'workionuallyt handling'.

The page life cycle phases are:

  • Initialization
  • Instantiation of the manages on the page
  • Restoration and maintenance of the state
  • Execution of the workionuallyt handler codes
  • Page rendering

Understanding the page cycle helps in writing codes for macalifornia king a few specific thing happen at any kind of stage of the page life cycle. It furthermore helps in writing custom manages and preliminaryizing all of them at proper time, populate their properlinks with watch-state data and operate manage behavior code.

Following are the various stages of an ASP.NET page:

  • Page request – When ASP.NET gets a page request, it chooses whether to parse and compile the page, or presently generally there would be a cached version of the page; accordingly the response is sent.

  • Starting of page life cycle – At this particular stage, the Request and Response objects are set. If the request is an old request or post back, the IsPostBack home of the page is set to true. The UICulture home of the page is furthermore set.

  • Page preliminaryization – At this particular stage, the manages on the page are assigned unique ID simply by setting the UniqueID home and the all of themes are applayd. For a brand new request, postback data is loaded and the manage properlinks are restoreddishdish to the watch-state values.

  • Page load – At this particular stage, manage properlinks are set uperform the watch state and manage state values.

  • Validation – Validate method of the validation manage is calintroduced and on it is successful execution, the IsValid home of the page is set to true.

  • Postback workionuallyt handling – If the request is a postback (old request), the related workionuallyt handler is withinvoked.

  • Page rendering – At this particular stage, watch state for the page and all manages are saved. The page calls the Render method for every manage and the out presently generally thereput of rendering is generated to the OutputStream course of the Response home of page.

  • Unload – The rendereddishdish page is sent to the claynt and page properlinks, such as Response and Request, are unloaded and all thoroughly cleanup done.

ASP.NET Page Life Cycle Events

At every stage of the page life cycle, the page raises a few workionuallyts, which can be coded. An workionuallyt handler is fundamentalally a function or subrout presently generally thereine, bound to the workionuallyt, uperform declarative attributes such as Onclick or handle.

Following are the page life cycle workionuallyts:

  • PreInit – PreInit is the 1st workionuallyt in page life cycle. It checks the IsPostBack home and figure outs whether the page is a postback. It sets the all of themes and master pages, generates dynamic manages, and gets and sets profile home values. This workionuallyt can be handintroduced simply by overloading the OnPreInit method or creating a Page_PreInit handler.

  • Init – Init workionuallyt preliminaryizes the manage home and the manage tree is built. This workionuallyt can be handintroduced simply by overloading the OnInit method or creating a Page_Init handler.

  • InitCompallowe – InitCompallowe workionuallyt enables traccalifornia king of watch state. All the manages turn on watch-state traccalifornia king.

  • LoadViewState – LoadViewState workionuallyt enables loading watch state information into the manages.

  • LoadPostData – During this particular phase, the contents of all the input fields are degreatd with the <form> tag are processed.

  • PreLoad – PreLoad occurs before the post back data is loaded in the manages. This workionuallyt can be handintroduced simply by overloading the OnPreLoad method or creating a Page_PreLoad handler.

  • Load – The Load workionuallyt is raised for the page 1st and then recursively for all child manages. The manages in the manage tree are generated. This workionuallyt can be handintroduced simply by overloading the OnLoad method or creating a Page_Load handler.

  • LoadCompallowe – The loading process is compallowed, manage workionuallyt handlers are operate, and page validation conaspectrs place. This workionuallyt can be handintroduced simply by overloading the OnLoadCompallowe method or creating a Page_LoadCompallowe handler

  • PreRender – The PreRender workionuallyt occurs simply before the out presently generally thereput is rendereddishdish. By handling this particular workionuallyt, pages and manages can perform any kind of updates before the out presently generally thereput is rendereddishdish.

  • PreRenderCompallowe – As the PreRender workionuallyt is recursively fireddishdish for all child manages, this particular workionuallyt ensures the compallowion of the pre-rendering phase.

  • SaveStateCompallowe – State of manage on the page is saved. Personalization, manage state and watch state information is saved. The HTML markup is generated. This stage can be handintroduced simply by overriding the Render method or creating a Page_Render handler.

  • UnLoad – The UnLoad phase is the final phase of the page life cycle. It raises the UnLoad workionuallyt for all manages recursively and finally for the page it iself. Final thoroughly cleanup is done and all resources and references, such as database interinterconnections, are freed. This workionuallyt can be handintroduced simply by modifying the OnUnLoad method or creating a Page_UnLoad handler.

ASP.NET – First Example

An ASP.NET page is made up of lots of server manages adurationy with HTML manages, text, and images. Sensitive data from the page and the states of various manages on the page are storeddishdish in hidden fields thead put on form the context of thead put on page request.

ASP.NET operatetime manages the association between a page instance and it is state. An ASP.NET page is an object of the Page or inherited from it.

All the manages on the pages are furthermore objects of the related manage course inherited from a parent Control course. When a page is operate, an instance of the object page is generated adurationy with all it is content manages.

An ASP.NET page is furthermore a server aspect file saved with the .aspx extension. It is modular in charworker and can be divided into the following core sections:

  • Page Directives
  • Code Section
  • Page Layout presently generally there

Page Directives

The page immediateives set up the environment for the page to operate. The @Page immediateive degreats page-specific attributes used simply by ASP.NET page parser and compiler. Page immediateives specify how the page need to be processed, and which assumptions need to be conaspectrn about presently generally there the page.

It enables iminterfaceing namespaces, loading assemblays, and registering brand new manages with custom tag names and namespace prefixes.

Code Section

The code section provides the handlers for the page and manage workionuallyts adurationy with other functions requireddishdish. We mentioned thead put on, ASP.NET follows an object model. Now, these objects raise workionuallyts when a few workionuallyts conaspectr place on the user interface, like a user clicks a button or moves the cursor. The kind of response these workionuallyts need to reciprocate is coded in the workionuallyt handler functions. The workionuallyt handlers are absolutely absolutely nothing but functions bound to the manages.

The code section or the code at the rear of file provides all these workionuallyt handler rout presently generally thereines, and other functions used simply by the generateer. The page code can be precompiintroduced and deployed in the form of a binary assembly.

Page Layout presently generally there

The page layout presently generally there provides the interface of the page. It contains the server manages, text, incollection JavaScript, and HTML tags.

The following code snippet provides a sample ASP.NET page exordinarying Page immediateives, code section and page layout presently generally there generated in C#:

<!-- immediateives -->
<% @Page Language="C#" %>

<!-- code section -->
<script operateat="server">
   private void convertoupper(object sender, EventArgs e)
   {
      string str = mytext.Value;
      changed_text.InnerHtml = str.ToUpper();
   }
</script>

<!-- Layout presently generally there -->
<html>
   <head> <title> Change to Upper Case </title> 
   </head>
   <body>
      <h3> Conversion to Upper Case </h3>
      <form operateat="server">
         <input operateat="server" id="mytext" type="text" />
         <input operateat="server" id="button1" type="submit" 
            value="Enter..." OnServerClick="convertoupper"/>
         <hr />
         <h3> Results: </h3>
         <span operateat="server" id="changed_text" />
      </form>
   </body>
</html>

Copy this particular file to the web server main immediateory. Generally it is c:iNETputwwwmain. Open the file from the bcollectionser to execute it and it generates following result:

ASP.NET First Example
ASP.NET First Example

Uperform Visual Studio IDE

Let us generate the same example uperform Visual Studio IDE. Instead of typing the code, you can simply drag the manages into the design watch:

ASP.NET First Example 2

The content file is automatically generateed. All you need to add is the Button1_Click rout presently generally thereine, which is as follows:

protected void Button1_Click(object sender, EventArgs e)
{
   string buf = TextBox1.Text;
   changed_text.InnerHtml = buf.ToUpper();
}

The content file code is as given:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
   Inherit is="1stexample._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head operateat="server">
      <title>
         Untitintroduced Page
      </title>
   </head>
   <body>
      <form id="form1" operateat="server">
         <div>
            <asp:TextBox ID="TextBox1" operateat="server" style="width:224px">
            </asp:TextBox>
            <br />
            <br />
            <asp:Button ID="Button1" operateat="server" Text="Enter..." 
               style="width:85px" onclick="Button1_Click" />
            <hr />
            <h3> Results: </h3>
            <span operateat="server" id="changed_text" />
         </div>
      </form>
   </body>
</html>

Execute the example simply by proper cliccalifornia king on the design watch and chooperform 'View in Bcollectionser' from the popup menu. This generates the following result:

ASP.NET First Example 3

ASP.NET – Event Handling

Whead put on is an Event?

An workionuallyt is an workionion or occurrence such as a mouse click, a key press, mouse movements, or any kind of system-generated notification. A process communicates through workionuallyts. For example, interrupts are system-generated workionuallyts. When workionuallyts occur, the application need to be able to respond to it and manage it.

Events in ASP.NET raised at the claynt machine, and handintroduced at the server machine. For example, a user clicks a button displayed in the bcollectionser. A Click workionuallyt is raised. The bcollectionser handles this particular claynt-aspect workionuallyt simply by posting it to the server.

The server has a subrout presently generally thereine describing whead put on to do when the workionuallyt is raised; it is calintroduced the workionuallyt-handler. Therefore, when the workionuallyt message is transmitted to the server, it checks whether the Click workionuallyt has an associated workionuallyt handler. If it has, the workionuallyt handler is executed.

Event Arguments

ASP.NET workionuallyt handlers generally conaspectr 2 parameters and return void. The 1st parameter represents the object raiperform the workionuallyt and the 2nd parameter is workionuallyt argument.

The general syntax of an workionuallyt is:

private void EventName (object sender, EventArgs e);

Application and Session Events

The many kind of iminterfaceant application workionuallyts are:

  • Application_Start – It is raised when the application/website is started.

  • Application_End – It is raised when the application/website is ceaseped.

Similarly, the many kind of used Session workionuallyts are:

  • Session_Start – It is raised when a user 1st requests a page from the application.

  • Session_End – It is raised when the session ends.

Page and Control Events

Common page and manage workionuallyts are:

  • DataBinding – It is raised when a manage binds to a data source.

  • Disposed – It is raised when the page or the manage is relrelayved.

  • Error – It is a page workionuallyt, occurs when an unhandintroduced exception is thcollectionn.

  • Init – It is raised when the page or the manage is preliminaryized.

  • Load – It is raised when the page or a manage is loaded.

  • PreRender – It is raised when the page or the manage is to be rendereddishdish.

  • Unload – It is raised when the page or manage is unloaded from memory.

Event Handling Uperform Controls

All ASP.NET manages are implemented as coursees, and they have workionuallyts which are fireddishdish when a user performs a specific workionion on all of them. For example, when a user clicks a button the 'Click' workionuallyt is generated. For handling workionuallyts, presently generally there are in-built attributes and workionuallyt handlers. Event handler is coded to respond to an workionuallyt, and conaspectr appropriate workionion on it.

By default, Visual Studio generates an workionuallyt handler simply by including a Handles clause on the Sub procedure. This clause names the manage and workionuallyt thead put on the procedure handles.

The ASP tag for a button manage:

<asp:Button ID="btnCancel" operateat="server" Text="Cancel" />

The workionuallyt handler for the Click workionuallyt:

Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) 
Handles btnCancel.Click
End Sub

An workionuallyt can furthermore be coded without presently generally there Handles clause. Then, the handler must be named according to the appropriate workionuallyt attribute of the manage.

The ASP tag for a button manage:

<asp:Button ID="btnCancel" operateat="server" Text="Cancel"
   Onclick="btnCancel_Click" />

The workionuallyt handler for the Click workionuallyt:

Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs)
End Sub

The common manage workionuallyts are:

Event Attribute Controls
Click OnClick Button, image button, link button, image chart
Command OnCommand Button, image button, link button
TextChanged OnTextChanged Text container
SelectedIndexChanged OnSelectedIndexChanged Drop-down list, list container, radio stations stations button list, check container list.
CheckedChanged OnCheckedChanged Check container, radio stations stations button

Some workionuallyts cause the form to be posted back to the server immediately, these are calintroduced the postback workionuallyts. For example, the click workionuallyt such as, Button.Click.

Some workionuallyts are not posted back to the server immediately, these are calintroduced non-postback workionuallyts.

For example, the change workionuallyts or selection workionuallyts such as TextBox.TextChanged or CheckBox.CheckedChanged. The nonpostback workionuallyts can be made to post back immediately simply by setting their AutoPostBack home to true.

Default Events

The default workionuallyt for the Page object is Load workionuallyt. Similarly, every manage has a default workionuallyt. For example, default workionuallyt for the button manage is the Click workionuallyt.

The default workionuallyt handler can be generated in Visual Studio, simply simply by double cliccalifornia king the manage in design watch. The following table shows a few of the default workionuallyts for common manages:

Control Default Event
AdRotator AdCreated
BulallowedList Click
Button Click
Calender SelectionChanged
CheckBox CheckedChanged
CheckBoxList SelectedIndexChanged
DataGrid SelectedIndexChanged
DataList SelectedIndexChanged
DropDownList SelectedIndexChanged
HyperLink Click
ImageButton Click
ImageMap Click
LinkButton Click
ListBox SelectedIndexChanged
Menu MenuItemClick
RadioButton CheckedChanged
RadioButtonList SelectedIndexChanged

Example

This example includes a easy page with a label manage and a button manage on it. As the page workionuallyts such as Page_Load, Page_Init, Page_PreRender etc. conaspectr place, it sends a message, which is displayed simply by the label manage. When the button is clicked, the Button_Click workionuallyt is raised and thead put on furthermore sends a message to be displayed on the label.

Create a brand new website and drag a label manage and a button manage on it from the manage tool container. Uperform the properlinks window, set the IDs of the manages as .lblmessage. and .btnclick. respectively. Set the Text home of the Button manage as 'Click'.

The markup file (.aspx):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
   Inherit is="workionuallytdemo._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head operateat="server">
      <title>Untitintroduced Page</title>
   </head>
   <body>
      <form id="form1" operateat="server">
         <div>
            <asp:Label ID="lblmessage" operateat="server" >
            </asp:Label>
            <br />
            <br />
            <br />
            <asp:Button ID="btnclick" operateat="server" Text="Click" 
               onclick="btnclick_Click" />
         </div>
      </form>
   </body>
</html>

Double click on the design watch to move to the code at the rear of file. The Page_Load workionuallyt is automatically generated without presently generally there any kind of code in it. Write down the following self-explanatory code collections:

uperform System;
uperform System.Collections;
uperform System.Configuration;
uperform System.Data;
uperform System.Linq;
uperform System.Web;
uperform System.Web.Security;
uperform System.Web.UI;
uperform System.Web.UI.HtmlControls;
uperform System.Web.UI.WebControls;
uperform System.Web.UI.WebControls.WebParts;
uperform System.Xml.Linq;

namespace workionuallytdemo
{
   public partial course _Default : System.Web.UI.Page{
      protected void Page_Load(object sender, EventArgs e)
      {
         lblmessage.Text += "Page load workionuallyt handintroduced. <br />";
         if (Page.IsPostBack)
         {
            lblmessage.Text += "Page post back workionuallyt handintroduced.<br/>";
         }
      }
      protected void Page_Init(object sender, EventArgs e){
         lblmessage.Text += "Page preliminaryization workionuallyt handintroduced.<br/>";
      }
      protected void Page_PreRender(object sender, EventArgs e)
      {
         lblmessage.Text += "Page prerender workionuallyt handintroduced. <br/>";
      }
      protected void btnclick_Click(object sender, EventArgs e)
      {
         lblmessage.Text += "Button click workionuallyt handintroduced. <br/>";
      }
   }
}

Execute the page. The label shows page load, page preliminaryization and, the page pre-render workionuallyts. Click the button to see effect:

ASP.NET Event Example

ASP.NET – Server Side

We have stupass awayd the page life cycle and how a page contains various manages. The page it iself is fastiated as a manage object. All web forms are fundamentalally instances of the ASP.NET Page course. The page course has the following extremely helpful properlinks thead put on correspond to intrinsic objects:

  • Session
  • Application
  • Cache
  • Request
  • Response
  • Server
  • User
  • Trace

We will speak about every of these objects in because of time. In this particular tutorial we will explore the Server object, the Request object, and the Response object.

Server Object

The Server object in Asp.NET is an instance of the System.Web.HttpServerUtility course. The HttpServerUtility course provides many kind of properlinks and methods to perform various jobs.

Properlinks and Methods of the Server object

The methods and properlinks of the HttpServerUtility course are exposed through the intrinsic Server object provided simply by ASP.NET.

The following table provides a list of the properlinks:

Property Description
MachineName Name of server computer
ScriptTimeOut Gets and sets the request time-out presently generally there value in 2nds.

The following table provides a list of a few iminterfaceant methods:

Method Description
CreateObject(String) Creates an instance of the COM object identified simply by it is ProgID (Programmatic ID).
CreateObject(Type) Creates an instance of the COM object identified simply by it is Type.
Equals(Object) Determines whether the specified Object is equal to the current Object.
Execute(String) Executes the handler for the specified virtual route in the context of the current request.
Execute(String, Boolean) Executes the handler for the specified virtual route in the context of the current request and specifies whether to clear the QueryString and Form collections.
GetLastError Returns the previous exception.
GetType Gets the Type of the current instance.
HtmlEncode Changes an common string into a string with legal HTML charworkioners.
HtmlDecode Converts an Html string into an common string.
ToString Returns a String thead put on represents the current Object.
Transfer(String) For the current request, terminates execution of the current page and starts execution of a brand new page simply by uperform the specified URL route of the page.
UrlDecode Converts an URL string into an common string.
UrlEncodeToken Works same as UrlEncode, but on a simply byte array thead put on contains Base64-encoded data.
UrlDecodeToken Works same as UrlDecode, but on a simply byte array thead put on contains Base64-encoded data.
MapPath Return the physical route thead put on corresponds to a specified virtual file route on the server.
Transfer Transfers execution to one more web page in the current application.

Request Object

The request object is an instance of the System.Web.HttpRequest course. It represents the values and properlinks of the HTTP request thead put on creates the page loading into the bcollectionser.

The information presented simply by this particular object is wrapped simply by the higher level abstrworkionions (the web manage model). However, this particular object helps in checcalifornia king a few information such as the claynt bcollectionser and cookies.

Properlinks and Methods of the Request Object

The following table provides a few noteworthy properlinks of the Request object:

Property Description
AcceptTypes Gets a string array of claynt-supinterfaceed MIME accept types.
ApplicationPath Gets the ASP.NET application's virtual application main route on the server.
Bcollectionser Gets or sets information about presently generally there the requesting claynt's bcollectionser capabililinks.
ContentEncoding Gets or sets the charworkioner set of the entity-body.
ContentLength Specifies the duration, in simply bytes, of content sent simply by the claynt.
ContentType Gets or sets the MIME content type of the incoming request.
Cookies Gets a collection of cookies sent simply by the claynt.
FilePath Gets the virtual route of the current request.
Files Gets the collection of files uploaded simply by the claynt, in multipart MIME format.
Form Gets a collection of form variables.
Headers Gets a collection of HTTP headers.
HttpMethod Gets the HTTP data transfer method (such as GET, POST, or HEAD) used simply by the claynt.
InputStream Gets the contents of the incoming HTTP entity body.
IsSecureConnection Gets a value indicating whether the HTTP interinterconnection uses secure sockets (thead put on is, HTTPS).
QueryString Gets the collection of HTTP query string variables.
RawUrl Gets the raw URL of the current request.
RequestType Gets or sets the HTTP data transfer method (GET or POST) used simply by the claynt.
ServerVariables Gets a collection of Web server variables.
TotalBytes Gets the number of simply bytes in the current input stream.
Url Gets information about presently generally there the URL of the current request.
UrlReferrer Gets information about presently generally there the URL of the claynt's previous request thead put on is linked to the current URL.
UserAgent Gets the raw user agent string of the claynt bcollectionser.
UserHostAdgown Gets the IP host adgown of the remote claynt.
UserHostName Gets the DNS name of the remote claynt.
UserLanguages Gets a sorted string array of claynt language preferences.

The following table provides a list of a few iminterfaceant methods:

Method Description
BinaryRead Performs a binary read of a specified number of simply bytes from the current input stream.
Equals(Object) Determines whether the specified object is equal to the current object. (Inherited from object.)
GetType Gets the Type of the current instance.
MapImageCoordinates Maps an incoming image-field form parameter to appropriate x-coordinate and y-coordinate values.
MapPath(String) Maps the specified virtual route to a physical route.
SaveAs Saves an HTTP request to disk.
ToString Returns a String thead put on represents the current object.
ValidateInput Causes validation to occur for the collections accessed through the Cookies, Form, and QueryString properlinks.

Response Object

The Response object represents the server's response to the claynt request. It is an instance of the System.Web.HttpResponse course.

In ASP.NET, the response object does not play any kind of vital role in sending HTML text to the claynt, because the server-aspect manages have nested, object oriented methods for rendering all of themselves.

However, the HttpResponse object still provides a few iminterfaceant functionalilinks, like the cookie feature and the Reimmediate() method. The Response.Reimmediate() method enables transferring the user to one more page, inaspect as well as out presently generally thereaspect the application. It requires a round trip.

Properlinks and Methods of the Response Object

The following table provides a few noteworthy properlinks of the Response object:

Property Description
Buffer Gets or sets a value indicating whether to buffer the out presently generally thereput and send it after the compallowe response is compalloweed procesperform.
BufferOutput Gets or sets a value indicating whether to buffer the out presently generally thereput and send it after the compallowe page is compalloweed procesperform.
Charset Gets or sets the HTTP charworkioner set of the out presently generally thereput stream.
ContentEncoding Gets or sets the HTTP charworkioner set of the out presently generally thereput stream.
ContentType Gets or sets the HTTP MIME type of the out presently generally thereput stream.
Cookies Gets the response cookie collection.
Expires Gets or sets the number of minutes before a page cached on a bcollectionser expires.
ExpiresAbsolute Gets or sets the absolute date and time at which to remove cached information from the cache.
HeaderEncoding Gets or sets an encoding object thead put on represents the encoding for the current header out presently generally thereput stream.
Headers Gets the collection of response headers.
IsClayntConnected Gets a value indicating whether the claynt is still connected to the server.
Output Enables out presently generally thereput of text to the out presently generally theregoing HTTP response stream.
OutputStream Enables binary out presently generally thereput to the out presently generally theregoing HTTP content body.
ReimmediateLocation Gets or sets the value of the Http Location header.
Status Sets the status collection thead put on is returned to the claynt.
StatusCode Gets or sets the HTTP status code of the out presently generally thereput returned to the claynt.
StatusDescription Gets or sets the HTTP status string of the out presently generally thereput returned to the claynt.
SubStatusCode Gets or sets a value qualifying the status code of the response.
SuppressContent Gets or sets a value indicating whether to send HTTP content to the claynt.

The following table provides a list of a few iminterfaceant methods:

Method Description
AddHeader Adds an HTTP header to the out presently generally thereput stream. AddHeader is provided for compatibility with earlayr versions of ASP.
AppendCookie Infrastructure adds an HTTP cookie to the intrinsic cookie collection.
AppendHeader Adds an HTTP header to the out presently generally thereput stream.
AppendToLog Adds custom log information to the InterNET Information Services (IIS) log file.
BinaryWrite Writes a string of binary charworkioners to the HTTP out presently generally thereput stream.
ClearContent Clears all content out presently generally thereput from the buffer stream.
Close Closes the socket interinterconnection to a claynt.
End Sends all currently buffereddishdish out presently generally thereput to the claynt, ceases execution of the page, and raises the EndRequest workionuallyt.
Equals(Object) Determines whether the specified object is equal to the current object.
Flush Sends all currently buffereddishdish out presently generally thereput to the claynt.
GetType Gets the Type of the current instance.
Pics Appends a HTTP PICS-Label header to the out presently generally thereput stream.
Reimmediate(String) Reimmediates a request to a brand new URL and specifies the brand new URL.
Reimmediate(String, Boolean) Reimmediates a claynt to a brand new URL. Specifies the brand new URL and whether execution of the current page need to terminate.
SetCookie Updates an existing cookie in the cookie collection.
ToString Returns a String thead put on represents the current Object.
TransmitFile(String) Writes the specified file immediately to an HTTP response out presently generally thereput stream, without presently generally there buffering it in memory.
Write(Char) Writes a charworkioner to an HTTP response out presently generally thereput stream.
Write(Object) Writes an object to an HTTP response stream.
Write(String) Writes a string to an HTTP response out presently generally thereput stream.
WriteFile(String) Writes the contents of the specified file immediately to an HTTP response out presently generally thereput stream as a file block.
WriteFile(String, Boolean) Writes the contents of the specified file immediately to an HTTP response out presently generally thereput stream as a memory block.

Example

The following easy example has a text container manage where the user can enter name, a button to send the information to the server, and a label manage to display the URL of the claynt computer.

The content file:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
   Inherit is="server_aspect._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head operateat="server">
      <title>Untitintroduced Page</title>
   </head>
   <body>
      <form id="form1" operateat="server">
         <div>
            Enter your own own name:<br />
            <asp:TextBox ID="TextBox1" operateat="server"></asp:TextBox>
            <asp:Button ID="Button1" operateat="server" 
               OnClick="Button1_Click" Text="Submit" />
            <br />
            <asp:Label ID="Label1" operateat="server"/>

         </div>
      </form>
   </body>
</html>

The code at the rear of Button1_Click:

protected void Button1_Click(object sender, EventArgs e)
{
   if (!String.IsNullOrEmpty(TextBox1.Text))
   {
      // Access the HttpServerUtility methods through
      // the intrinsic Server object.
      Label1.Text = "Welcome, " + Server.HtmlEncode(TextBox1.Text) +
         ".<br/> The url is " + Server.UrlEncode(Request.Url.ToString())
   }
}

Run the page to see the following result:

ASP.NET Server Side

ASP.NET – Server Controls

Controls are small constructing blocks of the graphical user interface, which include text containeres, buttons, check containeres, list containeres, labels, and many kind of other tools. Uperform these tools, the users can enter data, create selections and indicate their preferences.

Controls are furthermore used for structural jobs, like validation, data access, security, creating master pages, and data manipulation.

ASP.NET uses five types of web manages, which are:

  • HTML manages
  • HTML Server manages
  • ASP.NET Server manages
  • ASP.NET Ajax Server manages
  • User manages and custom manages

ASP.NET server manages are the primary manages used in ASP.NET. These manages can be grouped into the following categories:

  • Validation manages – These are used to validate user input and they work simply by operatening claynt-aspect script.

  • Data source manages – These manages provides data binding to various data sources.

  • Data watch manages – These are various lists and tables, which can bind to data from data sources for displaying.

  • Personalization manages – These are used for privateization of a page according to the user preferences, based on user information.

  • Login and security manages – These manages provide user authentication.

  • Master pages – These manages provide consistent layout presently generally there and interface throughout presently generally there the application.

  • Navigation manages – These manages help in navigation. For example, menus, tree watch etc.

  • Rich manages – These manages implement special features. For example, AdRotator, FileUpload, and Calendar manage.

The syntax for uperform server manages is:

<asp:manageType  ID ="ControlID" operateat="server" 
   Property1=value1  [Property2=value2] />

In addition, visual studio has the following features, to help produce in error-free coding:

  • Dragging and dropping of manages in design watch
  • IntelliSense feature thead put on displays and auto-compallowes the properlinks
  • The properlinks window to set the home values immediately

Properlinks of the Server Controls

ASP.NET server manages with a visual aspect are derived from the WebControl course and inherit all the properlinks, workionuallyts, and methods of this particular course.

The WebControl course it iself and a few other server manages thead put on are not visually rendereddishdish are derived from the System.Web.UI.Control course. For example, PlaceHolder manage or XML manage.

ASP.Net server manages inherit all properlinks, workionuallyts, and methods of the WebControl and System.Web.UI.Control course.

The following table shows the inherited properlinks, common to all server manages:

Property Description
AccessKey Presperform this particular key with the Alt key moves focus to the manage.
Attributes It is the collection of arbitrary attributes (for rendering only) thead put on do not correspond to properlinks on the manage.
BackColor Background colour.
BindingContainer The manage thead put on contains this particular manage's data binding.
BorderColor Border colour.
BorderStyle Border style.
BorderWidth Border width.
CausesValidation Indicates if it causes validation.
ChildControlCreated It indicates whether the server manage's child manages have been generated.
ClayntID Control ID for HTML markup.
Context The HttpContext object associated with the server manage.
Controls Collection of all manages contained within the manage.
ControlStyle The style of the Web server manage.
CssClass CSS course
DataItemContainer Gets a reference to the naming container if the naming container implements IDataItemContainer.
DataKeysContainer Gets a reference to the naming container if the naming container implements IDataKeysControl.
DesignMode It indicates whether the manage is being used on a design surface.
DisabintroducedCssClass Gets or sets the CSS course to apply to the rendereddishdish HTML element when the manage is disabintroduced.
Enabintroduced Indicates whether the manage is greyed out presently generally there.
EnableTheming Indicates whether all of theming applays to the manage.
EnableViewState Indicates whether the watch state of the manage is maintained.
Events Gets a list of workionuallyt handler delegates for the manage.
Font Font.
Forecolour Foreground colour.
HasAttributes Indicates whether the manage has attributes set.
HasChildViewState Indicates whether the current server manage's child manages have any kind of saved watch-state settings.
Height Height in pixels or %.
ID Identifier for the manage.
IsChildControlStateCleareddishdish Indicates whether manages contained within this particular manage have manage state.
IsEnabintroduced Gets a value indicating whether the manage is enabintroduced.
IsTraccalifornia kingViewState It indicates whether the server manage is saving changes to it is watch state.
IsViewStateEnabintroduced It indicates whether watch state is enabintroduced for this particular manage.
LoadViewStateById It indicates whether the manage participates in loading it is watch state simply by ID instead of index.
Page Page containing the manage.
Parent Parent manage.
RenderingCompatibility It specifies the ASP.NET version thead put on the rendereddishdish HTML will be compatible with.
Site The container thead put on hosts the current manage when rendereddishdish on a design surface.
SkinID Gets or sets the skin to apply to the manage.
Style Gets a collection of text attributes thead put on will be rendereddishdish as a style attribute on the out presently generally thereer tag of the Web server manage.
TabIndex Gets or sets the tab index of the Web server manage.
TagKey Gets the HtmlTextWriterTag value thead put on corresponds to this particular Web server manage.
TagName Gets the name of the manage tag.
TemplateControl The template thead put on contains this particular manage.
TemplateSourceDirectory Gets the virtual immediateory of the page or manage containing this particular manage.
ToolTip Gets or sets the text displayed when the mouse stageer hovers over the web server manage.
UniqueID Unique identifier.
ViewState Gets a book of state information thead put on saves and restores the watch state of a server manage acombination multiple requests for the same page.
ViewStateIgnoreCase It indicates whether the StateBag object is case-insensitive.
ViewStateMode Gets or sets the watch-state mode of this particular manage.
Visible It indicates whether a server manage is noticeable.
Width Gets or sets the width of the Web server manage.

Methods of the Server Controls

The following table provides the methods of the server manages:

Method Description
AddAttributesToRender Adds HTML attributes and styles thead put on need to be rendereddishdish to the specified HtmlTextWriterTag.
AddedControl Calintroduced after a child manage is added to the Controls collection of the manage object.
AddParsedSubObject Notifies the server manage thead put on an element, either XML or HTML, was parsed, and adds the element to the server manage's manage collection.
ApplyStyleSheetSkin Applays the style properlinks degreatd in the page style sheet to the manage.
ClearCachedClayntID Infrastructure. Sets the cached ClayntID value to null.
ClearChildControlState Deallowes the manage-state information for the server manage's child manages.
ClearChildState Deallowes the watch-state and manage-state information for all the server manage's child manages.
ClearChildViewState Deallowes the watch-state information for all the server manage's child manages.
CreateChildControls Used in creating child manages.
CreateControlCollection Creates a brand new ControlCollection object to hold the child manages.
CreateControlStyle Creates the style object thead put on is used to implement all style related properlinks.
DataBind Binds a data source to the server manage and all it is child manages.
DataBind(Boolean) Binds a data source to the server manage and all it is child manages with an option to raise the DataBinding workionuallyt.
DataBindChildren Binds a data source to the server manage's child manages.
Dispose Enables a server manage to perform final thoroughly clean up before it is relrelayved from memory.
EnsureChildControls Determines whether the server manage contains child manages. If it does not, it generates child manages.
EnsureID Creates an identifier for manages thead put on do not have an identifier.
Equals(Object) Determines whether the specified object is equal to the current object.
Finalize Allows an object to attempt to free resources and perform other thoroughly cleanup operations before the object is reclaimed simply by garbage collection.
FindControl(String) Searches the current naming container for a server manage with the specified id parameter.
FindControl(String, Int32) Searches the current naming container for a server manage with the specified id and an integer.
Focus Sets input focus to a manage.
GetDesignModeState Gets design-time data for a manage.
GetType Gets the type of the current instance.
GetUniqueIDRelativeTo Returns the prefixed interfaceion of the UniqueID home of the specified manage.
HasControls Determines if the server manage contains any kind of child manages.
HasEvents Indicates whether workionuallyts are registereddishdish for the manage or any kind of child manages.
IsLiteralContent Determines if the server manage holds only literal content.
LoadControlState Restores manage-state information.
LoadViewState Restores watch-state information.
MapPathSecure Retrieves the physical route thead put on a virtual route, either absolute or relative, charts to.
MemberwiseCsingle Creates a shenable duplicate of the current object.
MergeStyle Copies any kind of nonblank elements of the specified style to the web manage, but does not overwrite any kind of existing style elements of the manage.
OnBubbleEvent Determines whether the workionuallyt for the server manage is passed up the page's UI server manage hierarchy.
OnDataBinding Raises the data binding workionuallyt.
OnInit Raises the Init workionuallyt.
OnLoad Raises the Load workionuallyt.
OnPreRender Raises the PreRender workionuallyt.
OnUnload Raises the Unload workionuallyt.
OpenFile Gets a Stream used to read a file.
RemovedControl Calintroduced after a child manage is removed from the manages collection of the manage object.
Render Renders the manage to the specified HTML writer.
RenderBeginTag Renders the HTML open uping tag of the manage to the specified writer.
RenderChildren Outputs the contents of a server manage's children to a provided HtmlTextWriter object, which writes the contents to be rendereddishdish on the claynt.
RenderContents Renders the contents of the manage to the specified writer.
RenderControl(HtmlTextWriter) Outputs server manage content to a provided HtmlTextWriter object and stores tracing information about presently generally there the manage if tracing is enabintroduced.
RenderEndTag Renders the HTML cloperform tag of the manage into the specified writer.
ResolveAdapter Gets the manage adapter responsible for rendering the specified manage.
SaveControlState Saves any kind of server manage state changes thead put on have occurreddishdish since the time the page was posted back to the server.
SaveViewState Saves any kind of state thead put on was modified after the TrackViewState method was invoked.
SetDesignModeState Sets design-time data for a manage.
ToString Returns a string thead put on represents the current object.
TrackViewState Causes the manage to track changes to it is watch state so thead put on they can be storeddishdish in the object's watch state home.

Example

Let us look at a particular server manage – a tree watch manage. A Tree watch manage comes under navigation manages. Other Navigation manages are: Menu manage and SiteMapPath manage.

Add a tree watch manage on the page. Select Edit Nodes… from the tasks. Edit every of the nodes uperform the Tree watch node editor as shown:

ASP.NET Edit Nodes

Once you have generated the nodes, it looks like the following in design watch:

ASP.NET Edit Nodes2

The AutoFormat… task enables you to format the tree watch as shown:

ASP.NET AutoFormat

Add a label manage and a text container manage on the page and name all of them lblmessage and txtmessage respectively.

Write a few collections of code to ensure thead put on when a particular node is selected, the label manage displays the node text and the text container displays all child nodes under it, if any kind of. The code at the rear of the file need to look like this particular:

uperform System;
uperform System.Collections;
uperform System.Configuration;
uperform System.Data;
uperform System.Linq;
uperform System.Web;
uperform System.Web.Security;
uperform System.Web.UI;
uperform System.Web.UI.HtmlControls;
uperform System.Web.UI.WebControls;
uperform System.Web.UI.WebControls.WebParts;
uperform System.Xml.Linq;
 
namespace workionuallytdemo
{
   public partial course treewatchdemo : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      { 
         txtmessage.Text = " "; 
      }
      protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
      {
         txtmessage.Text = " "; 
         lblmessage.Text = "Selected node changed to: " + 
            TreeView1.SelectedNode.Text;
         TreeNodeCollection childnodes = TreeView1.SelectedNode.ChildNodes;
         if(childnodes != null)
         {
            txtmessage.Text = " ";
            forevery (TreeNode t in childnodes)
            {
               txtmessage.Text += t.Value;
            }
         }
      }
   }
}

Execute the page to see the effects. You will be able to expand and collapse the nodes.

ASP.NET Control Nodes

ASP.NET – HTML Server

The HTML server manages are fundamentalally the standard HTML manages enhanced to enable server aspect procesperform. The HTML manages such as the header tags, anchor tags, and input elements are not processed simply by the server but are sent to the bcollectionser for display.

They are specifically converted to a server manage simply by adding the attribute operateat="server" and adding an id attribute to create all of them available for server-aspect procesperform.

For example, conaspectr the HTML input manage:

<input type="text" size="40">

It can be converted to a server manage, simply by adding the operateat and id attribute:

<input type="text" id="checktext" size="40" operateat="server">

Advantages of uperform HTML Server Controls

Although ASP.NET server manages can perform every job accomplished simply by the HTML server manages, the later manages are helpful in the following cases:

  • Uperform static tables for layout presently generally there purposes.
  • Converting a HTML page to operate under ASP.NET

The following table describes the HTML server manages:

Control Name HTML tag
HtmlHead <head>element
HtmlInputButton <input type=button|submit|reset>
HtmlInputCheckcontainer <input type=checkcontainer>
HtmlInputFile <input type = file>
HtmlInputHidden <input type = hidden>
HtmlInputImage <input type = image>
HtmlInputPassword <input type = password>
HtmlInputRadioButton <input type = radio stations stations>
HtmlInputReset <input type = reset>
HtmlText <input type = text|password>
HtmlImage <img> element
HtmlLink <link> element
HtmlAnchor <a> element
HtmlButton <button> element
HtmlButton <button> element
HtmlForm <form> element
HtmlTable <table> element
HtmlTableCell <td> and <th>
HtmlTableRow <tr> element
HtmlTitle <title> element
HtmlSelect <select&t; element
HtmlGenericControl All HTML manages not listed

Example

The following example uses a fundamental HTML table for layout presently generally there. It uses a few containeres for getting input from the users such as name, adgown, city, state etc. It furthermore has a button manage, which is clicked to get the user data displayed in the final collection of the table.

The page need to look like this particular within the design watch:

ASP.NET Server Controls

The code for the content page shows the use of the HTML table element for layout presently generally there.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
   Inherit is="htmlserver._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head operateat="server">
      <title>Untitintroduced Page</title>
      <style type="text/css">
         .style1
         {  
            width: 156px;
         }
         .style2
         {
            width: 332px;
         }
      </style>
   </head>
   <body>
      <form id="form1" operateat="server">
         <div>
            <table style="width: 54%;">
               <tr>
                  <td course="style1">Name:</td>
                  <td course="style2">
                     <asp:TextBox ID="txtname" operateat="server"  style="width:230px">
                     </asp:TextBox>
                  </td>
               </tr>
				
               <tr>
                  <td course="style1">Street</td>
                  <td course="style2">
                     <asp:TextBox ID="txtstreet" operateat="server"  style="width:230px">
                     </asp:TextBox>
                  </td>
               </tr>
				
               <tr>
                  <td course="style1">City</td>
                  <td course="style2">
                     <asp:TextBox ID="txtcity" operateat="server"  style="width:230px">
                     </asp:TextBox>
                  </td>
               </tr>
				
               <tr>
                  <td course="style1">State</td>
                  <td course="style2">
                     <asp:TextBox ID="txtstate" operateat="server" style="width:230px">
                     </asp:TextBox>
                  </td>
               </tr>
				
               <tr>
                  <td course="style1"> </td>
                  <td course="style2"></td>
               </tr>
				
               <tr>
                  <td course="style1"></td>
                  <td ID="displaycollection" operateat ="server" course="style2">
                  </td>
               </tr>
            </table>
         </div>
         <asp:Button ID="Button1" operateat="server" onclick="Button1_Click" Text="Click" />
      </form>
   </body>
</html>

The code at the rear of the button manage:

protected void Button1_Click(object sender, EventArgs e)
{
   string str = "";
   str += txtname.Text + "<br />";
   str += txtstreet.Text + "<br />";
   str += txtcity.Text + "<br />";
   str += txtstate.Text + "<br />";
   displaycollection.InnerHtml = str;
}

Observe the following:

  • The standard HTML tags have been used for the page layout presently generally there.

  • The final collection of the HTML table is used for data display. It needed server aspect procesperform, so an ID attribute and the operateat attribute has been added to it.

ASP.NET – Claynt Side

ASP.NET claynt aspect coding has 2 aspects:

  • Claynt aspect scripts : It operates on the bcollectionser and in turn speeds up the execution of page. For example, claynt aspect data validation which can capture invalid data and battlen the user accordingly without presently generally there macalifornia king a round trip to the server.

  • Claynt aspect source code : ASP.NET pages generate this particular. For example, the HTML source code of an ASP.NET page contains lots of hidden fields and automatically injected blocks of JavaScript code, which maintains information like watch state or does other jobs to create the page work.

Claynt Side Scripts

All ASP.NET server manages enable calling claynt aspect code generated uperform JavaScript or VBScript. Some ASP.NET server manages use claynt aspect scripting to provide response to the users without presently generally there posting back to the server. For example, the validation manages.

Apart from these scripts, the Button manage has a home OnClayntClick, which enables executing claynt-aspect script, when the button is clicked.

The traditional and server HTML manages have the following workionuallyts thead put on can execute a script when they are raised:

Event Description
onblur When the manage loses focus
onfocus When the manage receives focus
onclick When the manage is clicked
onchange When the value of the manage changes
onkeydown When the user presses a key
onkeypress When the user presses an alphanumeric key
onkeyup When the user relrelayves a key
onmouseover When the user moves the mouse stageer over the manage
onserverclick It raises the ServerClick workionuallyt of the manage, when the manage is clicked

Claynt Side Source Code

We have already speak abouted thead put on, ASP.NET pages are generally generated in 2 files:

  • The content file or the markup file ( .aspx)
  • The code-at the rear of file

The content file contains the HTML or ASP.NET manage tags and literals to form the structure of the page. The code at the rear of file contains the course definition. At operate-time, the content file is parsed and transformed into a page course.

This course, adurationy with the course definition in the code file, and system generated code, collectively create the executable code (assembly) thead put on processes all posted data, generates response, and sends it back to the claynt.

Conaspectr the easy page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
   Inherit is="clayntaspect._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head operateat="server">
      <title>
         Untitintroduced Page
      </title>
   </head>
   <body>
      <form id="form1" operateat="server">
         <div>
            <asp:TextBox ID="TextBox1" operateat="server"></asp:TextBox>  
            <asp:Button ID="Button1" operateat="server" OnClick="Button1_Click"   Text="Click" />
         </div>
         <hr />
         <h3><asp:Label ID="Msg" operateat="server" Text=""></asp:Label>
         </h3>
      </form>
   </body>
</html>

When this particular page is operate on the bcollectionser, the View Source option shows the HTML page sent to the bcollectionser simply by the ASP.Net operatetime:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
   <head>
      <title>
         Untitintroduced Page
      </title>
   </head>
   <body>
      <form name="form1" method="post" workionion="Default.aspx" id="form1">
         <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" 
               value="/wEPDwUKMTU5MTA2ODYwOWRk31NudGDgvhhA7joJum9Qn5RxU2M=" />
         </div>
 
         <div>
            <input type="hidden" name="__EVENTVALIDATION"  id="__EVENTVALIDATION" 
               value="/wEWAwKpjZj0DALs0bLrBgKM54rGBhHsyM61rraxE+KnBTCS8cd1QDJ/"/>
         </div>

         <div>
            <input name="TextBox1" type="text" id="TextBox1" />  
            <input type="submit" name="Button1" value="Click" id="Button1" />
         </div>

         <hr />
         <h3><span id="Msg"></span></h3>
      </form>
   </body>
</html>

If you go through the code properly, you can see thead put on 1st 2 <div> tags contain the hidden fields which store the watch state and validation information.

ASP.NET – Basic Controls

In this particular chapter, we will speak about the fundamental manages available in ASP.NET.

Button Controls

ASP.NET provides 3 types of button manage:

  • Button : It displays text within a rectangular area.

  • Link Button : It displays text thead put on looks like a hyperlink.

  • Image Button : It displays an image.

When a user clicks a button, 2 workionuallyts are raised: Click and Command.

Basic syntax of button manage:

<asp:Button ID="Button1" operateat="server" onclick="Button1_Click" Text="Click" / >

Common properlinks of the button manage:

Property Description
Text The text displayed on the button. This is for button and link button manages only.
ImageUrl For image button manage only. The image to be displayed for the button.
AlternateText For image button manage only. The text to be displayed if the bcollectionser cannot display the image.
CausesValidation Determines whether page validation occurs when a user clicks the button. The default is true.
CommandName A string value thead put on is passed to the command workionuallyt when a user clicks the button.
CommandArgument A string value thead put on is passed to the command workionuallyt when a user clicks the button.
PostBackUrl The URL of the page thead put on is requested when the user clicks the button.

Text Boxes and Labels

Text container manages are typically used to accept input from the user. A text container manage can accept one or more collections of text depending upon the settings of the TextMode attribute.

Label manages provide an easy way to display text which can be changed from one execution of a page to the next. If you want to display text thead put on does not change, you use the literal text.

Basic syntax of text manage:

<asp:TextBox ID="txtstate" operateat="server" ></asp:TextBox>

Common Properlinks of the Text Box and Labels:

Property Description
TextMode Specifies the type of text container. SingleLine generates a standard text container, MultiLIne generates a text container thead put on accepts more than one collection of text and the Password causes the charworkioners thead put on are entereddishdish to be masked. The default is SingleLine.
Text The text content of the text container.
MaxLength The maximum number of charworkioners thead put on can be entereddishdish into the text container.
Wrap It figure outs whether or not text wraps automatically for multi-collection text container; default is true.
ReadOnly Determines whether the user can change the text in the container; default is false, i.e., the user can change the text.
Columns The width of the text container in charworkioners. The workionual width is figure outd based on the font thead put on is used for the text encheck.
Rows The height of a multi-collection text container in collections. The default value is 0, means a performle collection text container.

The many kind ofly used attribute for a label manage is 'Text', which implays the text displayed on the label.

Check Boxes and Radio Buttons

A check container displays a performle option thead put on the user can either check or uncheck and radio stations stations buttons present a group of options from which the user can select simply one option.

To generate a group of radio stations stations buttons, you specify the same name for the GroupName attribute of every radio stations stations button in the group. If more than one group is requireddishdish in a performle form, then specify a various group name for every group.

If you want check container or radio stations stations button to be selected when the form is preliminaryly displayed, set it is Checked attribute to true. If the Checked attribute is set to true for multiple radio stations stations buttons in a group, then only the final one is conaspectreddishdish as true.

Basic syntax of check container:

<asp:CheckBox ID= "chkoption" operateat= "Server"> 
</asp:CheckBox>

Basic syntax of radio stations stations button:

<asp:RadioButton ID= "rdboption" operateat= "Server"> 
</asp: RadioButton>

Common properlinks of check containeres and radio stations stations buttons:

Property Description
Text The text displayed next to the check container or radio stations stations button.
Checked Specifies whether it is selected or not, default is false.
GroupName Name of the group the manage bedurationys to.

List Controls

ASP.NET provides the following manages

  • Drop-down list,
  • List container,
  • Radio button list,
  • Check container list,
  • Bulallowed list.

These manage allow a user choose from one or more items from the list. List containeres and drop-down lists contain one or more list items. These lists can be loaded either simply by code or simply by the ListItemCollection editor.

Basic syntax of list container manage:

<asp:ListBox ID="ListBox1" operateat="server" AutoPostBack="True"    OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
</asp:ListBox>

Basic syntax of drop-down list manage:

<asp:DropDownList ID="DropDownList1" operateat="server" AutoPostBack="True"   OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>

Common properlinks of list container and drop-down Lists:

Property Description
Items The collection of ListItem objects thead put on represents the items in the manage. This home returns an object of type ListItemCollection.
Rows Specifies the number of items displayed in the container. If workionual list contains more collections than displayed then a scroll bar is added.
SelectedIndex The index of the currently selected item. If more than one item is selected, then the index of the 1st selected item. If no item is selected, the value of this particular home is -1.
SelectedValue The value of the currently selected item. If more than one item is selected, then the value of the 1st selected item. If no item is selected, the value of this particular home is an empty string ("").
SelectionMode Indicates whether a list container enables performle selections or multiple selections.

Common properlinks of every list item objects:

Property Description
Text The text displayed for the item.
Selected Indicates whether the item is selected.
Value A string value associated with the item.

It is iminterfaceant to notes thead put on:

  • To work with the items in a drop-down list or list container, you use the Items home of the manage. This home returns a ListItemCollection object which contains all the items of the list.

  • The SelectedIndexChanged workionuallyt is raised when the user selects a various item from a drop-down list or list container.

The ListItemCollection

The ListItemCollection object is a collection of ListItem objects. Each ListItem object represents one item in the list. Items in a ListItemCollection are numbereddishdish from 0.

When the items into a list container are loaded uperform strings like: lstcolour.Items.Add("Blue"), then both the Text and Value properlinks of the list item are set to the string value you specify. To set it variously you must generate a list item object and then add thead put on item to the collection.

The ListItemCollection Editor is used to add item to a drop-down list or list container. This is used to generate a static list of items. To display the collection editor, select edit item from the smart tag menu, or select the manage and then click the ellipsis button from the Item home in the properlinks window.

Common properlinks of ListItemCollection:

Property Description
Item(integer) A ListItem object thead put on represents the item at the specified index.
Count The number of items in the collection.

Common methods of ListItemCollection:

Methods Description
Add(string) Adds a brand new item at the end of the collection and assigns the string parameter to the Text home of the item.
Add(ListItem) Adds a brand new item at the end of the collection.
Insert(integer, string) Inserts an item at the specified index location in the collection, and assigns string parameter to the text home of the item.
Insert(integer, ListItem) Inserts the item at the specified index location in the collection.
Remove(string) Removes the item with the text value same as the string.
Remove(ListItem) Removes the specified item.
RemoveAt(integer) Removes the item at the specified index as the integer.
Clear Removes all the items of the collection.
FindByValue(string) Returns the item in whose value is same as the string.
FindByValue(Text) Returns the item in whose text is same as the string.

Radio Button list and Check Box list

A radio stations stations button list presents a list of mutually exclusive options. A check container list presents a list of independent options. These manages contain a collection of ListItem objects thead put on can be referreddishdish to through the Items home of the manage.

Basic syntax of radio stations stations button list:

<asp:RadioButtonList ID="RadioButtonList1" operateat="server" AutoPostBack="True" 
   OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>

Basic syntax of check container list:

<asp:CheckBoxList ID="CheckBoxList1" operateat="server" AutoPostBack="True" 
   OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList>

Common properlinks of check container and radio stations stations button lists:

Property Description
RepeatLayout presently generally there This attribute specifies whether the table tags or the normal html flow to use while formatting the list when it is rendereddishdish. The default is Table.
RepeatDirection It specifies the immediateion in which the manages to be repeated. The values available are Horizontal and Vertical. Default is Vertical.
RepeatColumns It specifies the number of columns to use when repeating the manages; default is 0.

Bulallowed lists and Numbereddishdish lists

The bulallowed list manage generates bulallowed lists or numbereddishdish lists. These manages contain a collection of ListItem objects thead put on can be referreddishdish to through the Items home of the manage.

Basic syntax of a bulallowed list:

<asp:BulallowedList ID="BulallowedList1" operateat="server">
</asp:BulallowedList>

Common properlinks of the bulallowed list:

Property Description
BulallowStyle This home specifies the style and looks of the bulallows, or numbers.
RepeatDirection It specifies the immediateion in which the manages to be repeated. The values available are Horizontal and Vertical. Default is Vertical.
RepeatColumns It specifies the number of columns to use when repeating the manages; default is 0.

HyperLink Control

The HyperLink manage is like the HTML <a> element.

Basic syntax for a hyperlink manage:

<asp:HyperLink ID="HyperLink1" operateat="server">
   HyperLink
</asp:HyperLink>

It has the following iminterfaceant properlinks:

Property Description
ImageUrl Path of the image to be displayed simply by the manage.
NavigateUrl Target link URL.
Text The text to be displayed as the link.
Target The window or frame which loads the linked page.

Image Control

The image manage is used for displaying images on the web page, or a few alternative text, if the image is not available.

Basic syntax for an image manage:

<asp:Image ID="Image1" operateat="server">

It has the following iminterfaceant properlinks:

Property Description
AlternateText Alternate text to be displayed in absence of the image.
ImageAlign Alignment options for the manage.
ImageUrl Path of the image to be displayed simply by the manage.

ASP.NET – Directives

ASP.NET immediateives are instructions to specify optional settings, such as registering a custom manage and page language. These settings describe how the web forms (.aspx) or user manages (.ascx) pages are processed simply by the .Net framework.

The syntax for declaring a immediateive is:

<%@  immediateive_name attribute=value  [attribute=value]  %>

In this particular section, we will simply introduce the ASP.NET immediateives and we will use many kind of of these immediateives throughout presently generally there the tutorials.

The Application Directive

The Application immediateive degreats application-specific attributes. It is provided at the top of the global.aspx file.

The fundamental syntax of Application immediateive is:

<%@ Application Language="C#" %>

The attributes of the Application immediateive are:

Attributes Description
Inherit is The name of the course from which to inherit.
Description The text description of the application. Parsers and compilers ignore this particular.
Language The language used in code blocks.

The Assembly Directive

The Assembly immediateive links an assembly to the page or the application at parse time. This could appear either in the global.asax file for application-wide lincalifornia king, in the page file, a user manage file for lincalifornia king to a page or user manage.

The fundamental syntax of Assembly immediateive is:

<%@ Assembly Name ="myassembly" %>

The attributes of the Assembly immediateive are:

Attributes Description
Name The name of the assembly to be linked.
Src The route to the source file to be linked and compiintroduced dynamically.

The Control Directive

The manage immediateive is used with the user manages and appears in the user manage (.ascx) files.

The fundamental syntax of Control immediateive is:

<%@ Control Language="C#"  EnableViewState="false" %>

The attributes of the Control immediateive are:

Attributes Description
AutoEventWireup The Boolean value thead put on enables or disables automatic association of workionuallyts to handlers.
ClassName The file name for the manage.
Debug The Boolean value thead put on enables or disables compiling with debug symbols.
Description The text description of the manage page, ignoreddishdish simply by compiler.
EnableViewState The Boolean value thead put on indicates whether watch state is maintained acombination page requests.
Explicit For VB language, tells the compiler to use option explicit mode.
Inherit is The course from which the manage page inherit is.
Language The language for code and script.
Src The filename for the code-at the rear of course.
Strict For VB language, tells the compiler to use the option rerigoroused mode.

The Implements Directive

The Implement immediateive indicates thead put on the web page, master page or user manage page must implement the specified .Net framework interface.

The fundamental syntax for implements immediateive is:

<%@ Implements  Interface="interface_name" %>

The Iminterface Directive

The Iminterface immediateive iminterfaces a namespace into a web page, user manage page of application. If the Iminterface immediateive is specified in the global.asax file, then it is applayd to the entire application. If it is within a page of user manage page, then it is applayd to thead put on page or manage.

The fundamental syntax for iminterface immediateive is:

<%@ namespace="System.Drawing" %>

The Master Directive

The Master immediateive specifies a page file as being the mater page.

The fundamental syntax of sample MasterPage immediateive is:

<%@ MasterPage Language="C#"  AutoEventWireup="true"  CodeFile="SiteMater.master.cs" Inherit is="SiteMaster"  %>

The MasterType Directive

The MasterType immediateive assigns a course name to the Master home of a page, to create it strongly typed.

The fundamental syntax of MasterType immediateive is:

<%@ MasterType attribute="value"[attribute="value" ...]  %>

The OutputCache Directive

The OutputCache immediateive manages the out presently generally thereput caching policies of a web page or a user manage.

The fundamental syntax of OutputCache immediateive is:

<%@ OutputCache Duration="15" VaryByParam="None"  %>

The Page Directive

The Page immediateive degreats the attributes specific to the page file for the page parser and the compiler.

The fundamental syntax of Page immediateive is:

<%@ Page Language="C#"  AutoEventWireup="true" CodeFile="Default.aspx.cs"  Inherit is="_Default"  Trace="true" %>

The attributes of the Page immediateive are:

Attributes Description
AutoEventWireup The Boolean value thead put on enables or disables page workionuallyts thead put on are being automatically bound to methods; for example, Page_Load.
Buffer The Boolean value thead put on enables or disables HTTP response buffering.
ClassName The course name for the page.
ClayntTarget The bcollectionser for which the server manages need to render content.
CodeFile The name of the code at the rear of file.
Debug The Boolean value thead put on enables or disables compilation with debug symbols.
Description The text description of the page, ignoreddishdish simply by the parser.
EnableSessionState It enables, disables, or creates session state read-only.
EnableViewState The Boolean value thead put on enables or disables watch state acombination page requests.
ErrorPage URL for reddishdishirection if an unhandintroduced page exception occurs.
Inherit is The name of the code at the rear of or other course.
Language The programming language for code.
Src The file name of the code at the rear of course.
Trace It enables or disables tracing.
TraceMode It indicates how trace messages are displayed, and sorted simply by time or category.
Transworkionion It indicates if transworkionions are supinterfaceed.
ValidateRequest The Boolean value thead put on indicates whether all input data is validated against a hardcoded list of values.

The PreviousPageType Directive

The PreviousPageType immediateive assigns a course to a page, so thead put on the page is strongly typed.

The fundamental syntax for a sample PreviousPagetype immediateive is:

<%@ PreviousPageType attribute="value"[attribute="value" ...]   %>

The Reference Directive

The Reference immediateive indicates thead put on one more page or user manage need to be compiintroduced and linked to the current page.

The fundamental syntax of Reference immediateive is:

<%@ Reference Page ="a fewpage.aspx" %>

The Register Directive

The Register derivative is used for registering the custom server manages and user manages.

The fundamental syntax of Register immediateive is:

<%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter" %>

ASP.NET – Managing State

Hyper Text Transfer Protocol (HTTP) is a stateless protocol. When the claynt disconnects from the server, the ASP.NET engine discards the page objects. This way, every web application can level up to serve many kind of requests simultaneously without presently generally there operatening out presently generally there of server memory.

However, presently generally there needs to be a few technique to store the information between requests and to retrieve it when requireddishdish. This withinformation i.e., the current value of all the manages and variables for the current user in the current session is calintroduced the State.

ASP.NET manages four types of states:

  • View State
  • Control State
  • Session State
  • Application State

View State

The watch state is the state of the page and all it is manages. It is automatically maintained acombination posts simply by the ASP.NET framework.

When a page is sent back to the claynt, the changes in the properlinks of the page and it is manages are figure outd, and storeddishdish in the value of a hidden input field named _VIEWSTATE. When the page is again posted back, the _VIEWSTATE field is sent to the server with the HTTP request.

The watch state can be enabintroduced or disabintroduced for:

  • The entire application simply by setting the EnableViewState home in the <pages> section of web.config file.

  • A page simply by setting the EnableViewState attribute of the Page immediateive, as <%@ Page Language="C#" EnableViewState="false" %>

  • A manage simply by setting the Control.EnableViewState home.

It is implemented uperform a watch state object degreatd simply by the StateBag course which degreats a collection of watch state items. The state bag is a data structure containing attribute value pairs, storeddishdish as strings associated with objects.

The StateBag course has the following properlinks:

Properlinks Description
Item(name) The value of the watch state item with the specified name. This is the default home of the StateBag course.
Count The number of items in the watch state collection.
Keys Collection of keys for all the items in the collection.
Values Collection of values for all the items in the collection.

The StateBag course has the following methods:

Methods Description
Add(name, value) Adds an item to the watch state collection and existing item is updated.
Clear Removes all the items from the collection.
Equals(Object) Determines whether the specified object is equal to the current object.
Finalize Allows it to free resources and perform other thoroughly cleanup operations.
GetEnumerator Returns an enumerator thead put on iterates over all the key/value pairs of the StateItem objects storeddishdish in the StateBag object.
GetType Gets the type of the current instance.
IsItemDirty Checks a StateItem object storeddishdish in the StateBag object to evaluate whether it has been modified.
Remove(name) Removes the specified item.
SetDirty Sets the state of the StateBag object as well as the Dirty home of every of the StateItem objects contained simply by it.
SetItemDirty Sets the Dirty home for the specified StateItem object in the StateBag object.
ToString Returns a string representing the state bag object.

Example

The following example demonstrates the concept of storing watch state. Let us maintain a counter, which is withincremented every time the page is posted back simply by cliccalifornia king a button on the page. A label manage shows the value in the counter.

The markup file code is as follows:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
   Inherit is="statedemo._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head operateat="server">
      <title>
         Untitintroduced Page
      </title>
   </head>
   <body>
      <form id="form1" operateat="server">
         <div>
            <h3>View State demo</h3>
         
            Page Counter:
            <asp:Label ID="lblCounter" operateat="server" />
            <asp:Button ID="btnIncrement" operateat="server" Text="Add Count" 
               onclick="btnIncrement_Click" />
         </div>
      </form>
   </body>
</html>

The code at the rear of file for the example is shown here:

public partial course _Default : System.Web.UI.Page
{
   public int counter
   {
      get
      {
         if (ViewState["pcounter"] != null)
         {
            return ((int)ViewState["pcounter"]);
         }
         else
         {
            return 0;
         }
      }
      set
      {
         ViewState["pcounter"] = value;
      }
   }
        
   protected void Page_Load(object sender, EventArgs e)
   {
      lblCounter.Text = counter.ToString();
      counter++;
   }
}

It would produce the following result:

View State Demo

Control State

Control state cannot be modified, accessed immediately, or disabintroduced.

Session State

When a user connects to an ASP.NET website, a brand new session object is generated. When session state is turned on, a brand new session state object is generated for every brand new request. This session state object becomes part of the context and it is available through the page.

Session state is generally used for storing application data such as inventory, supplayr list, customer record, or shopping cart. It can furthermore maintain information about presently generally there the user and his preferences, and maintain the track of pending operations.

Sessions are identified and tracked with a 120-bit SessionID, which is passed from claynt to server and back as cookie or a modified URL. The SessionID is globally unique and random.

The session state object is generated from the HttpSessionState course, which degreats a collection of session state items.

The HttpSessionState course has the following properlinks:

Properlinks Description
SessionID The unique session identifier.
Item(name) The value of the session state item with the specified name. This is the default home of the HttpSessionState course.
Count The number of items in the session state collection.
TimeOut Gets and sets the amount of time, in minutes, enableed between requests before the session-state provider terminates the session.

The HttpSessionState course has the following methods:

Methods Description
Add(name, value) Adds an item to the session state collection.
Clear Removes all the items from session state collection.
Remove(name) Removes the specified item from the session state collection.
RemoveAll Removes all keys and values from the session-state collection.
RemoveAt Deallowes an item at a specified index from the session-state collection.

The session state object is a name-value pair to store and retrieve a few information from the session state object. You could use the following code for the same:

void StoreSessionInfo()
{
   String fromuser = TextBox1.Text;
   Session["fromuser"] = fromuser;
}
void RetrieveSessionInfo()
{
   String fromuser = Session["fromuser"];
   Label1.Text = fromuser;
}

The above code stores only strings in the Session book object, however, it can store all the primitive data types and arrays composed of primitive data types, as well as the DataSet, DataTable, HashTable, and Image objects, as well as any kind of user-degreatd course thead put on inherit is from the ISerializable object.

Example

The following example demonstrates the concept of storing session state. There are 2 buttons on the page, a text container to enter string and a label to display the text storeddishdish from final session.

The mark up file code is as follows:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" 
   Inherit is="_Default"  %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head operateat="server">
      <title>
         Untitintroduced Page
      </title>
   </head>
   <body>
      <form id="form1" operateat="server">
         <div>
            &nbsp; &nbsp; &nbsp;
            <table style="width: 568px; height: 103px">
               <tr>
                  <td style="width: 209px">
                     <asp:Label ID="lblstr" operateat="server" Text="Enter a String"  style="width:94px">
                     </asp:Label>
                  </td>
					
                  <td style="width: 317px">
                     <asp:TextBox ID="txtstr" operateat="server" style="width:227px">
                     </asp:TextBox>
                  </td>
               </tr>
	
               <tr>
                  <td style="width: 209px"></td>
                  <td style="width: 317px"></td>
               </tr>
	
               <tr>
                  <td style="width: 209px">
                     <asp:Button ID="btnnrm" operateat="server" 
                        Text="No workionion button" style="width:128px" />
                  </td>
	
                  <td style="width: 317px">
                     <asp:Button ID="btnstr" operateat="server" 
                        OnClick="btnstr_Click" Text="Submit the String" />
                  </td> 
               </tr>
	
               <tr>
                  <td style="width: 209px">
                  </td>
	
                  <td style="width: 317px">
                  </td>  
               </tr>
	
               <tr>
                  <td style="width: 209px">
                     <asp:Label ID="lblsession" operateat="server"  style="width:231px"  >
                     </asp:Label>
                  </td>
	
                  <td style="width: 317px">
                  </td>
               </tr>
	
               <tr>
                  <td style="width: 209px">
                     <asp:Label ID="lblshstr" operateat="server">
                     </asp:Label>
                  </td>
	
                  <td style="width: 317px">
                  </td>
               </tr>
            </table>
         </div>
      </form>
   </body>
</html>

It need to look like the following in design watch:

session design watch

The code at the rear of file is given here:

public partial course _Default : System.Web.UI.Page 
{
   String mystr;
   protected void Page_Load(object sender, EventArgs e)
   {
      this particular.lblshstr.Text = this particular.mystr;
      this particular.lblsession.Text = (String)this particular.Session["str"];
   }
   protected void btnstr_Click(object sender, EventArgs e)
   {
      this particular.mystr = this particular.txtstr.Text;
      this particular.Session["str"] = this particular.txtstr.Text;
      this particular.lblshstr.Text = this particular.mystr;
      this particular.lblsession.Text = (String)this particular.Session["str"];
   }
}

Execute the file and observe how it works:

session operate watch

Application State

The ASP.NET application is the collection of all web pages, code and other files within a performle virtual immediateory on a web server. When information is storeddishdish in application state, it is available to all the users.

To provide for the use of application state, ASP.NET generates an application state object for every application from the HTTPApplicationState course and stores this particular object in server memory. This object is represented simply by course file global.asax.

Application State is many kind ofly used to store hit counters and other statistical data, global application data like tax rate, discount rate etc. and to maintain the track of users visiting the site.

The HttpApplicationState course has the following properlinks:

Properlinks Description
Item(name) The value of the application state item with the specified name. This is the default home of the HttpApplicationState course.
Count The number of items in the application state collection.

The HttpApplicationState course has the following methods:

Methods Description
Add(name, value) Adds an item to the application state collection.
Clear Removes all the items from the application state collection.
Remove(name) Removes the specified item from the application state collection.
RemoveAll Removes all objects from an HttpApplicationState collection.
RemoveAt Removes an HttpApplicationState object from a collection simply by index.
Lock() Locks the application state collection so only the current user can access it.
Unlock() Unlocks the application state collection so all the users can access it.

Application state data is generally maintained simply by writing handlers for the workionuallyts:

  • Application_Start
  • Application_End
  • Application_Error
  • Session_Start
  • Session_End

The following code snippet shows the fundamental syntax for storing application state information:

Void Application_Start(object sender, EventArgs e)
{
   Application["startMessage"] = "The application has started.";
}
Void Application_End(object sender, EventArgs e)
{
   Application["endtMessage"] = "The application has ended.";
}

ASP.NET – Validators

ASP.NET validation manages validate the user input data to ensure thead put on useless, unauthenticated, or contradictory data don't get storeddishdish.

ASP.NET provides the following validation manages:

  • RequireddishdishFieldValidator
  • RangeValidator
  • CompareValidator
  • RegularExpressionValidator
  • CustomValidator
  • ValidationSummary

BaseValidator Class

The validation manage coursees are inherited from the BaseValidator course hence they inherit it is properlinks and methods. Therefore, it would help to conaspectr a look at the properlinks and the methods of this particular base course, which are common for all the validation manages:

Members Description
ControlToValidate Indicates the input manage to validate.
Display Indicates how the error message is shown.
EnableClayntScript Indicates whether claynt aspect validation will conaspectr.
Enabintroduced Enables or disables the validator.
ErrorMessage Indicates error string.
Text Error text to be shown if validation fails.
IsValid Indicates whether the value of the manage is valid.
SetFocusOnError It indicates whether in case of an invalid manage, the focus need to switch to the related input manage.
ValidationGroup The logical group of multiple validators, where this particular manage bedurationys.
Validate() This method revalidates the manage and updates the IsValid home.

RequireddishdishFieldValidator Control

The RequireddishdishFieldValidator manage ensures thead put on the requireddishdish field is not empty. It is generally linkd to a text container to force input into the text container.

The syntax of the manage is as given:

<asp:RequireddishdishFieldValidator ID="rfvcandidate" 
   operateat="server" ControlToValidate ="ddlcandidate"
   ErrorMessage="Plrelayve choose a candidate" 
   InitialValue="Plrelayve choose a candidate">
</asp:RequireddishdishFieldValidator>

RangeValidator Control

The RangeValidator manage verifies thead put on the input value falls within a preddishdishetermined range.

It has 3 specific properlinks:

Properlinks Description
Type It degreats the type of the data. The available values are: Currency, Date, Double, Integer, and String.
MinimumValue It specifies the minimum value of the range.
MaximumValue It specifies the maximum value of the range.

The syntax of the manage is as given:

<asp:RangeValidator ID="rvcourse" operateat="server" ControlToValidate="txtcourse" 
   ErrorMessage="Enter your own own course (6 - 12)" MaximumValue="12" 
   MinimumValue="6" Type="Integer">
</asp:RangeValidator>

CompareValidator Control

The CompareValidator manage compares a value in one manage with a fixed value or a value in one more manage.

It has the following specific properlinks:

Properlinks Description
Type It specifies the data type.
ControlToCompare It specifies the value of the input manage to compare with.
ValueToCompare It specifies the constant value to compare with.
Operator It specifies the comparison operator, the available values are: Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and DataTypeCheck.

The fundamental syntax of the manage is as follows:

<asp:CompareValidator ID="CompareValidator1" operateat="server" 
   ErrorMessage="CompareValidator">
</asp:CompareValidator>

RegularExpressionValidator

The RegularExpressionValidator enables validating the input text simply by complementing against a pattern of a regular expression. The regular expression is set in the ValidationExpression home.

The following table summarizes the commonly used syntax constructs for regular expressions:

Charworkioner Escapes Description
b Matches a backspace.
t Matches a tab.
r Matches a carriage return.
v Matches a vertical tab.
f Matches a form give food to.
n Matches a brand new collection.
Escape charworkioner.

Apart from performle charworkioner complement, a course of charworkioners can be specified thead put on can be complemented, calintroduced the metacharworkioners.

Metacharworkioners Description
. Matches any kind of charworkioner except n.
[abcd] Matches any kind of charworkioner in the set.
[^abcd] Excludes any kind of charworkioner in the set.
[2-7a-mA-M] Matches any kind of charworkioner specified in the range.
w Matches any kind of alphanumeric charworkioner and underscore.
W Matches any kind of non-word charworkioner.
s Matches whitespace charworkioners like, space, tab, brand new collection etc.
S Matches any kind of non-whitespace charworkioner.
d Matches any kind of decimal charworkioner.
D Matches any kind of non-decimal charworkioner.

Quantifiers can be added to specify number of times a charworkioner could appear.

Quantifier Description
* Zero or more complementes.
+ One or more complementes.
? Zero or one complementes.
{N} N complementes.
{N,} N or more complementes.
{N,M} Between N and M complementes.

The syntax of the manage is as given:

<asp:RegularExpressionValidator ID="string" operateat="server" ErrorMessage="string"
   ValidationExpression="string" ValidationGroup="string">
</asp:RegularExpressionValidator>

CustomValidator

The CustomValidator manage enables writing application specific custom validation rout presently generally thereines for both the claynt aspect and the server aspect validation.

The claynt aspect validation is accomplished through the ClayntValidationFunction home. The claynt aspect validation rout presently generally thereine need to be generated in a scripting language, such as JavaScript or VBScript, which the bcollectionser can understand.

The server aspect validation rout presently generally thereine must be calintroduced from the manage's ServerValidate workionuallyt handler. The server aspect validation rout presently generally thereine need to be generated in any kind of .Net language, like C# or VB.Net.

The fundamental syntax for the manage is as given:

<asp:CustomValidator ID="CustomValidator1" operateat="server" 
   ClayntValidationFunction=.cvf_func. ErrorMessage="CustomValidator">
</asp:CustomValidator>

ValidationSummary

The ValidationSummary manage does not perform any kind of validation but shows a summary of all errors in the page. The summary displays the values of the ErrorMessage home of all validation manages thead put on faiintroduced validation.

The following 2 mutually inclusive properlinks list out presently generally there the error message:

  • ShowSummary : shows the error messages in specified format.

  • ShowMessageBox : shows the error messages in a separate window.

The syntax for the manage is as given:

<asp:ValidationSummary ID="ValidationSummary1" operateat="server" 
   DisplayMode = "BulallowList" ShowSummary = "true" HeaderText="Errors:" />

Validation Groups

Complex pages have various groups of information provided in various panels. In such situation, a need may arise for performing validation separately for separate group. This kind of situation is handintroduced uperform validation groups.

To generate a validation group, you need to put the input manages and the validation manages into the same logical group simply by setting their ValidationGroup home.

Example

The following example describes a form to be filintroduced up simply by all the college college students of a college, divided into four houses, for electing the college preaspectnt. Here, we use the validation manages to validate the user input.

This is the form in design watch:

form in Design watch

The content file code is as given:

<form id="form1" operateat="server">
   <table style="width: 66%;">
      <tr>
         <td course="style1" colspan="3" align="centre">
         <asp:Label ID="lblmsg" 
            Text="Preaspectnt Election Form : Choose your own own preaspectnt" 
            operateat="server" />
         </td>
      </tr>

      <tr>
         <td course="style3">
            Candidate:
         </td>

         <td course="style2">
            <asp:DropDownList ID="ddlcandidate" operateat="server"  style="width:239px">
               <asp:ListItem>Plrelayve Choose a Candidate</asp:ListItem>
               <asp:ListItem>M H Kabir</asp:ListItem>
               <asp:ListItem>Steve Taylor</asp:ListItem>
               <asp:ListItem>John Abraham</asp:ListItem>
               <asp:ListItem>Venus Williams</asp:ListItem>
            </asp:DropDownList>
         </td>

         <td>
            <asp:RequireddishdishFieldValidator ID="rfvcandidate" 
               operateat="server" ControlToValidate ="ddlcandidate"
               ErrorMessage="Plrelayve choose a candidate" 
               InitialValue="Plrelayve choose a candidate">
            </asp:RequireddishdishFieldValidator>
         </td>
      </tr>

      <tr>
         <td course="style3">
            House:
         </td>

         <td course="style2">
            <asp:RadioButtonList ID="rblhouse" operateat="server" RepeatLayout presently generally there="Flow">
               <asp:ListItem>Red</asp:ListItem>
               <asp:ListItem>Blue</asp:ListItem>
               <asp:ListItem>Yellow</asp:ListItem>
               <asp:ListItem>Green</asp:ListItem>
            </asp:RadioButtonList>
         </td>

         <td>
            <asp:RequireddishdishFieldValidator ID="rfvhouse" operateat="server" 
               ControlToValidate="rblhouse" ErrorMessage="Enter your own own house name" >
            </asp:RequireddishdishFieldValidator>
            <br />
         </td>
      </tr>

      <tr>
         <td course="style3">
            Class:
         </td>

         <td course="style2">
            <asp:TextBox ID="txtcourse" operateat="server"></asp:TextBox>
         </td>

         <td>
            <asp:RangeValidator ID="rvcourse" 
               operateat="server" ControlToValidate="txtcourse" 
               ErrorMessage="Enter your own own course (6 - 12)" MaximumValue="12" 
               MinimumValue="6" Type="Integer">
            </asp:RangeValidator>
         </td>
      </tr>

      <tr>
         <td course="style3">
            Email:
         </td>

         <td course="style2">
            <asp:TextBox ID="txtemail" operateat="server" style="width:250px">
            </asp:TextBox>
         </td>

         <td>
            <asp:RegularExpressionValidator ID="remail" operateat="server" 
               ControlToValidate="txtemail" ErrorMessage="Enter your own own email" 
               ValidationExpression="w+([-+.']w+)[email protected]+([-.]w+)*.w+([-.]w+)*">
            </asp:RegularExpressionValidator>
         </td>
      </tr>

      <tr>
         <td course="style3" align="centre" colspan="3">
            <asp:Button ID="btnsubmit" operateat="server" onclick="btnsubmit_Click" 
               style="text-align: centre" Text="Submit" style="width:140px" />
         </td>
      </tr>
   </table>
   <asp:ValidationSummary ID="ValidationSummary1" operateat="server" 
      DisplayMode ="BulallowList" ShowSummary ="true" HeaderText="Errors:" />
</form>

The code at the rear of the submit button:

protected void btnsubmit_Click(object sender, EventArgs e)
{
   if (Page.IsValid)
   {
      lblmsg.Text = "Thank You";
   }
   else
   {
      lblmsg.Text = "Fill up all the fields";
   }
}

ASP.NET – Database Access

ASP.NET enables the following sources of data to be accessed and used:

  • Databases (e.g., Access, SQL Server, Oracle, MySQL)
  • XML documents
  • Business Objects
  • Flat files

ASP.NET hides the complex processes of data access and provides a lot higher level of coursees and objects through which data is accessed easily. These coursees hide all complex coding for interinterconnection, data retrieving, data querying, and data manipulation.

ADO.NET is the technology thead put on provides the bridge between various ASP.NET manage objects and the backend data source. In this particular tutorial, we will look at data access and functioning with the data in brief.

Retrieve and display data

It conaspectrs 2 types of data manages to retrieve and display data in ASP.NET:

  • A data source manage – It manages the interinterconnection to the data, selection of data, and other jobs such as paging and caching of data etc.

  • A data watch manage – It binds and displays the data and enables data manipulation.

We will speak about the data binding and data source manages in detail later. In this particular section, we will use a SqlDataSource manage to access data and a GridView manage to display and manipulate data in this particular chapter.

We will furthermore use an Access database, which contains the details about presently generally there .Net books available in the market. Name of our database is ASPDotNetStepByStep.mdb and we will use the data table DotNetReferences.

The table has the following columns: ID, Title, AuthorFirstName, AuthorLastName, Topic, and Publisher.

Here is a snapshot of the data table:

Data Table

Let us immediately move to workionion, conaspectr the following steps:

(1) Create a web site and add a SqlDataSourceControl on the web form.

SqlDataSourceControl

(2) Click on the Configure Data Source option.

Configure Data Source

(3) Click on the New Connection button to establish interinterconnection with a database.

Connection with a database

(4) Once the interinterconnection is set up, you may save it for further use. At the next step, you are asked to configure the select statement:

Select statement

(5) Select the columns and click next to compallowe the steps. Observe the WHERE, ORDER BY, and the Advanced buttons. These buttons enable you to provide the where clause, order simply by clause, and specify the insert, update, and deallowe commands of SQL respectively. This way, you can manipulate the data.

(6) Add a GridView manage on the form. Choose the data source and format the manage uperform AutoFormat option.

AutoFormat

(7) After this particular the formatted GridView manage displays the column headings, and the application is ready to execute.

GridView manage

(8) Finally execute the application.

Database Result

The content file code is as given:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="dataaccess.aspx.cs" 
   Inherit is="datacaching.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head operateat="server">
      <title>
         Untitintroduced Page
      </title>
   </head>
   <body>
      <form id="form1" operateat="server">
         <div>
            <asp:SqlDataSource ID="SqlDataSource1" operateat="server" 
               ConnectionString= "<%$   ConnectionStrings:ASPDotNetStepByStepConnectionString%>" 
               ProviderName= "<%$ ConnectionStrings:
                  ASPDotNetStepByStepConnectionString.ProviderName %>" 
               SelectCommand="SELECT [Title], [AuthorLastName], 
                  [AuthorFirstName], [Topic] FROM [DotNetReferences]">
            </asp:SqlDataSource>
            <asp:GridView ID="GridView1" operateat="server" 
               AutoGenerateColumns="False" CellPadding="4" 
               DataSourceID="SqlDataSource1" ForeColor="#333333" 
               GridLines="None">
               <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            
               <Columns>
                  <asp:BoundField DataField="Title" HeaderText="Title" 
                     SortExpression="Title" />
                  <asp:BoundField DataField="AuthorLastName" 
                     HeaderText="AuthorLastName" SortExpression="AuthorLastName" />
                  <asp:BoundField DataField="AuthorFirstName" 
                     HeaderText="AuthorFirstName" SortExpression="AuthorFirstName" />
                  <asp:BoundField DataField="Topic" 
                     HeaderText="Topic" SortExpression="Topic" />
               </Columns>
               <FooterStyle BackColor="#5D7B9D" 
                  Font-Bold="True" ForeColor="White" />
               <PagerStyle BackColor="#284775" 
                  ForeColor="White" HorizontalAlign="Center" />
               <SelectedRowStyle BackColor="#E2DED6" 
                  Font-Bold="True" ForeColor="#333333" />
               <HeaderStyle BackColor="#5D7B9D" Font-Bold="True"  
                  ForeColor="White" />
               <EditRowStyle BackColor="#999999" />
               <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            </asp:GridView>
         </div>
      </form>
   </body>
</html>

ADO.NET

ADO.NET provides a bridge between the front aspect end manages and the back end database. The ADO.NET objects encapsulate all the data access operations and the manages interworkion with these objects to display data, thus hiding the details of movement of data.

The following figure shows the ADO.NET objects at a glance:

ADO.Net objects

The DataSet Class

The dataset represents a subset of the database. It does not have a continuous interinterconnection to the database. To update the database a reinterinterconnection is requireddishdish. The DataSet contains DataTable objects and DataRelation objects. The DataRelation objects represent the relationship between 2 tables.

Following table shows a few iminterfaceant properlinks of the DataSet course:

Properlinks Description
CaseSensitive Indicates whether string comparisons within the data tables are case-sensitive.
Container Gets the container for the component.
DataSetName Gets or sets the name of the current data set.
DefaultViewManager Returns a watch of data in the data set.
DesignMode Indicates whether the component is currently in design mode.
EnforceConstraints Indicates whether constraint rules are followed when attempting any kind of update operation.
Events Gets the list of workionuallyt handlers thead put on are attached to this particular component.
ExtendedProperlinks Gets the collection of customised user information associated with the DataSet.
HasErrors Indicates if presently generally there are any kind of errors.
IsInitialized Indicates whether the DataSet is preliminaryized.
Locale Gets or sets the locale information used to compare strings within the table.
Namespace Gets or sets the namespace of the DataSet.
Prefix Gets or sets an XML prefix thead put on aliases the namespace of the DataSet.
Relations Returns the collection of DataRelation objects.
Tables Returns the collection of DataTable objects.

The following table shows a few iminterfaceant methods of the DataSet course:

Methods Description
AcceptChanges Accepts all changes made since the DataSet was loaded or this particular method was calintroduced.
BeginInit Begins the preliminaryization of the DataSet. The preliminaryization occurs at operate time.
Clear Clears data.
Csingle Copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not duplicate any kind of data.
Copy Copies both structure and data.
CreateDataReader() Returns a DataTableReader with one result set per DataTable, in the same sequence as the tables appear in the Tables collection.
CreateDataReader(DataTable[]) Returns a DataTableReader with one result set per DataTable.
EndInit Ends the preliminaryization of the data set.
Equals(Object) Determines whether the specified Object is equal to the current Object.
Finalize Free resources and perform other thoroughly cleanups.
GetChanges Returns a duplicate of the DataSet with all changes made since it was loaded or the AcceptChanges method was calintroduced.
GetChanges(DataRowState) Gets a duplicate of DataSet with all changes made since it was loaded or the AcceptChanges method was calintroduced, filtereddishdish simply by DataRowState.
GetDataSetSchema Gets a duplicate of XmlSchemaSet for the DataSet.
GetObjectData Populates a serialization information object with the data needed to serialize the DataSet.
GetType Gets the type of the current instance.
GetXML Returns the XML representation of the data.
GetXMLSchema Returns the XSD schema for the XML representation of the data.
HasChanges() Gets a value indicating whether the DataSet has changes, including brand new, deallowed, or modified collections.
HasChanges(DataRowState) Gets a value indicating whether the DataSet has changes, including brand new, deallowed, or modified collections, filtereddishdish simply by DataRowState.
IsBinarySerialized Inspects the format of the serialized representation of the DataSet.
Load(IDataReader, LoadOption, DataTable[]) Fills a DataSet with values from a data source uperform the supplayd IDataReader, uperform an array of DataTable instances to supply the schema and namespace information.
Load(IDataReader, LoadOption, String[]) Fills a DataSet with values from a data source uperform the supplayd IDataReader, uperform an array of strings to supply the names for the tables within the DataSet.
Merge() Merges the data with data from one more DataSet. This method has various overloaded forms.
ReadXML() Reads an XML schema and data into the DataSet. This method has various overloaded forms.
ReadXMLSchema(0) Reads an XML schema into the DataSet. This method has various overloaded forms.
RejectChanges Rolls back all changes made since the final call to AcceptChanges.
WriteXML() Writes an XML schema and data from the DataSet. This method has various overloaded forms.
WriteXMLSchema() Writes the structure of the DataSet as an XML schema. This method has various overloaded forms.

The DataTable Class

The DataTable course represents the tables in the database. It has the following iminterfaceant properlinks; many kind of of these properlinks are read only properlinks except the PrimaryKey home:

Properlinks Description
ChildRelations Returns the collection of child relationship.
Columns Returns the Columns collection.
Constraints Returns the Constraints collection.
DataSet Returns the parent DataSet.
DefaultView Returns a watch of the table.
ParentRelations Returns the ParentRelations collection.
PrimaryKey Gets or sets an array of columns as the primary key for the table.
Rows Returns the Rows collection.

The following table shows a few iminterfaceant methods of the DataTable course:

Methods Description
AcceptChanges Commit is all changes since the final AcceptChanges.
Clear Clears all data from the table.
GetChanges Returns a duplicate of the DataTable with all changes made since the AcceptChanges method was calintroduced.
GetErrors Returns an array of collections with errors.
IminterfaceRows Copies a brand new collection into the table.
LoadDataRow Finds and updates a specific collection, or generates a brand new one, if not found any kind of.
Merge Merges the table with one more DataTable.
NewRow Creates a brand new DataRow.
RejectChanges Rolls back all changes made since the final call to AcceptChanges.
Reset Resets the table to it is authentic state.
Select Returns an array of DataRow objects.

The DataRow Class

The DataRow object represents a collection in a table. It has the following iminterfaceant properlinks:

Properlinks Description
HasErrors Indicates if presently generally there are any kind of errors.
Items Gets or sets the data storeddishdish in a specific column.
ItemArrays Gets or sets all the values for the collection.
Table Returns the parent table.

The following table shows a few iminterfaceant methods of the DataRow course:

Methods Description
AcceptChanges Accepts all changes made since this particular method was calintroduced.
BeginEdit Begins edit operation.
CancelEdit Cancels edit operation.
Deallowe Deallowes the DataRow.
EndEdit Ends the edit operation.
GetChildRows Gets the child collections of this particular collection.
GetParentRow Gets the parent collection.
GetParentRows Gets parent collections of DataRow object.
RejectChanges Rolls back all changes made since the final call to AcceptChanges.

The DataAdapter Object

The DataAdapter object workions as a mediator between the DataSet object and the database. This helps the Dataset to contain data from multiple databases or other data source.

The DataReader Object

The DataReader object is an alternative to the DataSet and DataAdapter combination. This object provides a interinterconnection oriented access to the data records in the database. These objects are suitable for read-only access, such as populating a list and then breacalifornia king the interinterconnection.

DbCommand and DbConnection Objects

The DbConnection object represents a interinterconnection to the data source. The interinterconnection can be shareddishdish among various command objects.

The DbCommand object represents the command or a storeddishdish procedure sent to the database from retrieving or manipulating data.

Example

So far, we have used tables and databases already existing in our computer. In this particular example, we will generate a table, add column, collections and data into it and display the table uperform a GridView object.

The source file code is as given:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
   Inherit is="generatedatabase._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head operateat="server">
      <title>
         Untitintroduced Page
      </title>
   </head>
   <body>
      <form id="form1" operateat="server">
         <div>
            <asp:GridView ID="GridView1" operateat="server">
            </asp:GridView>
         </div>
      </form>
   </body>
</html>

The code at the rear of file is as given:

namespace generatedatabase
{
   public partial course _Default : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
         if (!IsPostBack)
         {
            DataSet ds = CreateDataSet();
            GridView1.DataSource = ds.Tables["Student"];
            GridView1.DataBind();
         }
      }
      private DataSet CreateDataSet()
      {
         //creating a DataSet object for tables
         DataSet dataset = brand new DataSet();

         // creating the college college student table
         DataTable Students = CreateStudentTable();
         dataset.Tables.Add(Students);
         return dataset;
      }
      private DataTable CreateStudentTable()
      {
         DataTable Students = brand new DataTable("Student");

         // adding columns
         AddNewColumn(Students, "System.Int32", "StudentID");
         AddNewColumn(Students, "System.String", "StudentName");
         AddNewColumn(Students, "System.String", "StudentCity");

         // adding collections
         AddNewRow(Students, 1, "M H Kabir", "Kolkata");
         AddNewRow(Students, 1, "Shreya Shprovidea", "Delhi");
         AddNewRow(Students, 1, "Rini MUKherjee", "Hyderabad");
         AddNewRow(Students, 1, "Sunil Dubey", "Bikaner");
         AddNewRow(Students, 1, "Rajat Mishra", "Patna");

         return Students;
      }

      private void AddNewColumn(DataTable table, string columnType, string  columnName)
      {
         DataColumn column = table.Columns.Add(columnName,  Type.GetType(columnType));
      }

      //adding data into the table
      private void AddNewRow(DataTable table, int id, string name, string city)
      {
         DataRow brand newcollection = table.NewRow();
         brand newcollection["StudentID"] = id;
         brand newcollection["StudentName"] = name;
         brand newcollection["StudentCity"] = city;
         table.Rows.Add(brand newcollection);
      }
   }
}

When you execute the program, observe the following:

  • The application 1st generates a data set and binds it with the grid watch manage uperform the DataBind() method of the GridView manage.

  • The Createdataset() method is a user degreatd function, which generates a brand new DataSet object and then calls one more user degreatd method CreateStudentTable() to generate the table and add it to the Tables collection of the data set.

  • The CreateStudentTable() method calls the user degreatd methods AddNewColumn() and AddNewRow() to generate the columns and collections of the table as well as to add data to the collections.

When the page is executed, it returns the collections of the table as shown:

ADO.Net Result

ASP.NET – File Uploading

ASP.NET has 2 manages thead put on enable users to upload files to the web server. Once the server receives the posted file data, the application can save it, check it, or ignore it. The following manages enable the file uploading:

  • HtmlInputFile – an HTML server manage

  • FileUpload – and ASP.NET web manage

Both manages enable file uploading, but the FileUpload manage automatically sets the encoding of the form, whereas the HtmlInputFile does not do so.

In this particular tutorial, we use the FileUpload manage. The FileUpload manage enables the user to bcollectionse for and select the file to be uploaded, providing a bcollectionse button and a text container for entering the filename.

Once, the user has entereddishdish the filename in the text container simply by typing the name or bcollectionperform, the SaveAs method of the FileUpload manage can be calintroduced to save the file to the disk.

The fundamental syntax of FileUpload is:

<asp:FileUpload ID= "Uploader" operateat = "server" />

The FileUpload course is derived from the WebControl course, and inherit is all it is members. Apart from those, the FileUpload course has the following read-only properlinks:

Properlinks Description
FileBytes Returns an array of the simply bytes in a file to be uploaded.
FileContent Returns the stream object stageing to the file to be uploaded.
FileName Returns the name of the file to be uploaded.
HasFile Specifies whether the manage has a file to upload.
PostedFile Returns a reference to the uploaded file.

The posted file is encapsulated in an object of type HttpPostedFile, which can be accessed through the PostedFile home of the FileUpload course.

The HttpPostedFile course has the following regularly used properlinks:

Properlinks Description
ContentLength Returns the size of the uploaded file in simply bytes.
ContentType Returns the MIME type of the uploaded file.
FileName Returns the compallowe filename.
InputStream Returns a stream object stageing to the uploaded file.

Example

The following example demonstrates the FileUpload manage and it is properlinks. The form has a FileUpload manage adurationy with a save button and a label manage for displaying the file name, file type, and file duration.

In the design watch, the form looks as follows:

File Upload

The content file code is as given:

<body>
   <form id="form1" operateat="server">
      <div>
         <h3> File Upload:</h3>
         <br />
         <asp:FileUpload ID="FileUpload1" operateat="server" />
         <br /><br />
         <asp:Button ID="btnsave" operateat="server" onclick="btnsave_Click"  Text="Save" style="width:85px" />
         <br /><br />
         <asp:Label ID="lblmessage" operateat="server" />
      </div>
   </form>
</body>

The code at the rear of the save button is as given:

protected void btnsave_Click(object sender, EventArgs e)
{
   StringBuilder sb = brand new StringBuilder();
   if (FileUpload1.HasFile)
   {
      check
      {
         sb.AppendFormat(" Uploading file: {0}", FileUpload1.FileName);
         
         //saving the file
         FileUpload1.SaveAs("<c:\SaveDirectory>" + FileUpload1.FileName);
      
         //Showing the file information
         sb.AppendFormat("<br/> Save As: {0}",  FileUpload1.PostedFile.FileName);
         sb.AppendFormat("<br/> File type: {0}",    FileUpload1.PostedFile.ContentType);
         sb.AppendFormat("<br/> File duration: {0}",  FileUpload1.PostedFile.ContentLength);
         sb.AppendFormat("<br/> File name: {0}",  FileUpload1.PostedFile.FileName);
      }
      capture (Exception ex)
      {
         sb.Append("<br/> Error <br/>");
         sb.AppendFormat("Unable to save file <br/> {0}", ex.Message);
      }
   }
   else
   {
      lblmessage.Text = sb.ToString();
   }
}

Note the following:

  • The StringBuilder course is derived from System.IO namespace, so it needs to be included.

  • The check and capture blocks are used for captureing errors, and display the error message.

ASP.NET – Ad Rotator

The AdRotator manage randomly selects banner graphics from a list, which is specified in an external XML schedule file. This external XML schedule file is calintroduced the advertisement file.

The AdRotator manage enables you to specify the advertisement file and the type of window thead put on the link need to follow in the AdvertisementFile and the Target home respectively.

The fundamental syntax of adding an AdRotator is as follows:

<asp:AdRotator  operateat = "server" AdvertisementFile = "adfile.xml"  Target =  "_blank" />

Before going into the details of the AdRotator manage and it is properlinks, allow us look into the construction of the advertisement file.

The Advertisement File

The advertisement file is an XML file, which contains the information about presently generally there the advertisements to be displayed.

Extensible Markup Language (XML) is a W3C standard for text document markup. It is a text-based markup language thead put on enables you to store data in a structureddishdish format simply by uperform meaningful tags. The term 'extensible' implays thead put on you can extend your own own capcapability to describe a document simply by defining meaningful tags for the application.

XML is not a language in it iself, like HTML, but a set of rules for creating brand new markup languages. It is a meta-markup language. It enables generateers to generate custom tag sets for special uses. It structures, stores, and transinterfaces the information.

Following is an example of XML file:

<BOOK>
   <NAME> Learn XML </NAME>
   <AUTHOR> Samuel Peterson </AUTHOR>
   <PUBLISHER> NSS Publications </PUBLISHER>
   <PRICE> $30.00</PRICE>
</BOOK>

Like all XML files, the advertisement file needs to be a structureddishdish text file with well-degreatd tags decollectionating the data. There are the following standard XML elements thead put on are commonly used in the advertisement file:

Element Description
Advertisements Enshuts the advertisement file.
Ad Decollectionates separate ad.
ImageUrl The route of image thead put on will be displayed.
NavigateUrl The link thead put on will be followed when the user clicks the ad.
AlternateText The text thead put on will be displayed instead of the picture if it cannot be displayed.
Keyword Keyword identifying a group of advertisements. This is used for filtering.
Impressions The number indicating how regularly an advertisement will appear.
Height Height of the image to be displayed.
Width Width of the image to be displayed.

Apart from these tags, customs tags with custom attributes could furthermore be included. The following code illustrates an advertisement file ads.xml:

<Advertisements>
   <Ad>
      <ImageUrl>went up1.jpg</ImageUrl>
      <NavigateUrl>http://www.1800flowers.com</NavigateUrl>
      <AlternateText>
         Order flowers, went ups, gifts and more
      </AlternateText>
      <Impressions>20</Impressions>
      <Keyword>flowers</Keyword>
   </Ad>

   <Ad>
      <ImageUrl>went up2.jpg</ImageUrl>
      <NavigateUrl>http://www.basimply bybouquets.com.au</NavigateUrl>
      <AlternateText>Order went ups and flowers</AlternateText>
      <Impressions>20</Impressions>
      <Keyword>gifts</Keyword>
   </Ad>

   <Ad>
      <ImageUrl>went up3.jpg</ImageUrl>
      <NavigateUrl>http://www.flowers2moscow.com</NavigateUrl>
      <AlternateText>Send flowers to Russia</AlternateText>
      <Impressions>20</Impressions>
      <Keyword>russia</Keyword>
   </Ad>

   <Ad>
      <ImageUrl>went up4.jpg</ImageUrl>
      <NavigateUrl>http://www.edibleblooms.com</NavigateUrl>
      <AlternateText>Edible Blooms</AlternateText>
      <Impressions>20</Impressions>
      <Keyword>gifts</Keyword>
   </Ad>
</Advertisements>

Properlinks and Events of the AdRotator Class

The AdRotator course is derived from the WebControl course and inherit is it is properlinks. Apart from those, the AdRotator course has the following properlinks:

Properlinks Description
AdvertisementFile The route to the advertisement file.
AlternateTextFeild The element name of the field where alternate text is provided. The default value is AlternateText.
DataMember The name of the specific list of data to be bound when advertisement file is not used.
DataSource Control from where it would retrieve data.
DataSourceID Id of the manage from where it would retrieve data.
Font Specifies the font properlinks associated with the advertisement banner manage.
ImageUrlField The element name of the field where the URL for the image is provided. The default value is ImageUrl.
KeywordFilter For displaying the keyword based ads only.
NavigateUrlField The element name of the field where the URL to navigate to is provided. The default value is NavigateUrl.
Target The bcollectionser window or frame thead put on displays the content of the page linked.
UniqueID Obtains the unique, hierarchically qualified identifier for the AdRotator manage.

Following are the iminterfaceant workionuallyts of the AdRotator course:

Events Description
AdCreated It is raised once per round trip to the server after creation of the manage, but before the page is rendereddishdish
DataBinding Occurs when the server manage binds to a data source.
DataBound Occurs after the server manage binds to a data source.
Disposed Occurs when a server manage is relrelayved from memory, which is the final stage of the server manage lifecycle when an ASP.NET page is requested
Init Occurs when the server manage is preliminaryized, which is the 1st step in it is lifecycle.
Load Occurs when the server manage is loaded into the Page object.
PreRender Occurs after the Control object is loaded but prior to rendering.
Unload Occurs when the server manage is unloaded from memory.

Worcalifornia king with AdRotator Control

Create a brand new web page and place an AdRotator manage on it.

<form id="form1" operateat="server">
   <div>
      <asp:AdRotator ID="AdRotator1" operateat="server" AdvertisementFile  ="~/ads.xml" onadgenerated="AdRotator1_AdCreated" />
   </div>
</form>

The ads.xml file and the image files need to be located in the main immediateory of the web site.

Try to execute the above application and observe thead put on every time the page is reloaded, the ad is changed.

ASP.NET – Calendars

The calendar manage is a functionally wealthy web manage, which provides the following capabililinks:

  • Displaying one month at a time
  • Selecting a day, a week or a month
  • Selecting a range of days
  • Moving from month to month
  • Controlling the display of the days programmatically

The fundamental syntax of a calendar manage is:

<asp:Calender ID = "Calendar1" operateat = "server">
</asp:Calender>

Properlinks and Events of the Calendar Control

The calendar manage has many kind of properlinks and workionuallyts, uperform which you can customise the workionions and display of the manage. The following table provides a few iminterfaceant properlinks of the Calendar manage:

Properlinks Description
Caption Gets or sets the caption for the calendar manage.
CaptionAlign Gets or sets the alignment for the caption.
CellPadding Gets or sets the number of spaces between the data and the cell border.
CellSpacing Gets or sets the space between cells.
DayHeaderStyle Gets the style properlinks for the section thead put on displays the day of the week.
DayNameFormat Gets or sets format of days of the week.
DayStyle Gets the style properlinks for the days in the displayed month.
FirstDayOfWeek Gets or sets the day of week to display in the 1st column.
NextMonthText Gets or sets the text for next month navigation manage. The default value is >.
NextPrevFormat Gets or sets the format of the next and previous month navigation manage.
OtherMonthDayStyle Gets the style properlinks for the days on the Calendar manage thead put on are not in the displayed month.
PrevMonthText Gets or sets the text for previous month navigation manage. The default value is <.
SelectedDate Gets or sets the selected date.
SelectedDates Gets a collection of DateTime objects representing the selected dates.
SelectedDayStyle Gets the style properlinks for the selected dates.
SelectionMode Gets or sets the selection mode thead put on specifies whether the user can select a performle day, a week or an entire month.
SelectMonthText Gets or sets the text for the month selection element in the selector column.
SelectorStyle Gets the style properlinks for the week and month selector column.
SelectWeekText Gets or sets the text displayed for the week selection element in the selector column.
ShowDayHeader Gets or sets the value indicating whether the heading for the days of the week is displayed.
ShowGridLines Gets or sets the value indicating whether the gridcollections would be shown.
ShowNextPrevMonth Gets or sets a value indicating whether next and previous month navigation elements are shown in the title section.
ShowTitle Gets or sets a value indicating whether the title section is displayed.
TitleFormat Gets or sets the format for the title section.
Titlestyle Get the style properlinks of the title heading for the Calendar manage.
TodayDayStyle Gets the style properlinks for today's date on the Calendar manage.
TodaysDate Gets or sets the value for today's date.
UseAccessibleHeader Gets or sets a value thead put on indicates whether to render the table header <th> HTML element for the day headers instead of the table data <td> HTML element.
VisibleDate Gets or sets the date thead put on specifies the month to display.
WeekendDayStyle Gets the style properlinks for the weekend dates on the Calendar manage.

The Calendar manage has the following 3 many kind of iminterfaceant workionuallyts thead put on enable the generateers to program the calendar manage. They are:

Events Description
SelectionChanged It is raised when a day, a week or an entire month is selected.
DayRender It is raised when every data cell of the calendar manage is rendereddishdish.
VisibleMonthChanged It is raised when user changes a month.

Worcalifornia king with the Calendar Control

Putting a bare-bone tissue calendar manage without presently generally there any kind of code at the rear of file provides a workable calendar to a site, which shows the months and days of the calendar year. It furthermore enables navigation to next and previous months.

Calendar

Calendar manages enable the users to select a performle day, a week, or an entire month. This is done simply by uperform the SelectionMode home. This home has the following values:

Properlinks Description
Day To select a performle day.
DayWeek To select a performle day or an entire week.
DayWeekMonth To select a performle day, a week, or an entire month.
None Nothing can be selected.

The syntax for selecting days:

<asp:Calender ID = "Calendar1" operateat = "server" SelectionMode="DayWeekMonth">
</asp:Calender>

When the selection mode is set to the value DayWeekMonth, an extra column with the > symbol appears for selecting the week, and a >> symbol appears to the left of the days name for selecting the month.

Calendar2

Example

The following example demonstrates selecting a date and displays the date in a label:

The content file code is as follows:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
   Inherit is="calendardemo._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head operateat="server">
      <title>
         Untitintroduced Page
      </title>
   </head>
   <body>
      <form id="form1" operateat="server">
         <div>
            <h3> Your Birthday:</h3>
            <asp:Calendar ID="Calendar1" operateat="server  SelectionMode="DayWeekMonth"  onselectionchanged="Calendar1_SelectionChanged">
            </asp:Calendar>
         </div>
         <p>Todays date is: 
            <asp:Label ID="lblday" operateat="server"></asp:Label>
         </p>
         
         <p>Your Birday is: 
            <asp:Label ID="lblbday" operateat="server"></asp:Label>
         </p>
      </form>
   </body>
</html>

The workionuallyt handler for the workionuallyt SelectionChanged:

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
   lblday.Text = Calendar1.TodaysDate.ToShortDateString();
   lblbday.Text = Calendar1.SelectedDate.ToShortDateString();
}

When the file is operate, it need to produce the following out presently generally thereput:

Calendar3

ASP.NET – Multi Views

MultiView and View manages enable you to divide the content of a page into various groups, displaying only one group at a time. Each View manage manages one group of content and all the View manages are held collectively in a MultiView manage.

The MultiView manage is responsible for displaying one View manage at a time. The View displayed is calintroduced the workionive watch.

The syntax of MultiView manage is:

<asp:MultView ID= "MultiView1" operateat= "server">
</asp:MultiView>

The syntax of View manage is:

<asp:View ID= "View1" operateat= "server">
</asp:View>

However, the View manage cannot exist on it is own. It would render error if you check to use it stand-asingle. It is always used with a Multiwatch manage as:

<asp:MultView ID= "MultiView1" operateat= "server">
   <asp:View ID= "View1" operateat= "server"> </asp:View>
</asp:MultiView>

Properlinks of View and MultiView Controls

Both View and MultiView manages are derived from Control course and inherit all it is properlinks, methods, and workionuallyts. The many kind of iminterfaceant home of the View manage is Visible home of type Boolean, which sets the visibility of a watch.

The MultiView manage has the following iminterfaceant properlinks:

Properlinks Description
Views Collection of View manages within the MultiView.
ActiveViewIndex A zero based index thead put on denotes the workionive watch. If no watch is workionive, then the index is -1.

The CommandName attribute of the button manage associated with the navigation of the MultiView manage are associated with a few related field of the MultiView manage.

For example, if a button manage with CommandName value as NextView is associated with the navigation of the multiwatch, it automatically navigates to the next watch when the button is clicked.

The following table shows the default command names of the above properlinks:

Properlinks Description
NextViewCommandName NextView
PreviousViewCommandName PrevView
SwitchViewByIDCommandName SwitchViewByID
SwitchViewByIndexCommandName SwitchViewByIndex

The iminterfaceant methods of the multiwatch manage are:

Methods Description
SetActivewatch Sets the workionive watch
GetActivewatch Retrieves the workionive watch

Every time a watch is changed, the page is posted back to the server and lots of workionuallyts are raised. Some iminterfaceant workionuallyts are:

Events Description
ActiveViewChanged Raised when a watch is changed
Activate Raised simply by the workionive watch
Deworkionivate Raised simply by the inworkionive watch

Apart from the above mentioned properlinks, methods and workionuallyts, multiwatch manage inherit is the members of the manage and object course.

Example

The example page has 3 watchs. Each watch has 2 button for navigating through the watchs.

The content file code is as follows:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
   Inherit is="multiwatchdemo._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head operateat="server">
      <title>
         Untitintroduced Page
      </title>
   </head>
   <body>
      <form id="form1" operateat="server">
         <div>
            <h2>MultiView and View Controls</h2>
            <asp:DropDownList ID="DropDownList1" operateat="server" 
               onselectedindexchanged="DropDownList1_SelectedIndexChanged">
            </asp:DropDownList>
            <hr />
            <asp:MultiView ID="MultiView1" operateat="server" ActiveViewIndex="2"
               onworkionivewatchchanged="MultiView1_ActiveViewChanged" >
               <asp:View ID="View1" operateat="server">
                  <h3>This is watch 1</h3>
                  <br />
                  <asp:Button CommandName="NextView" ID="btnnext1" 
                     operateat="server" Text = "Go To Next" />
                  <asp:Button CommandArgument="View3" 
                     CommandName="SwitchViewByID" ID="btnfinal" operateat="server" Text  ="Go To Last" />
               </asp:View> 
					
               <asp:View ID="View2" operateat="server">
                  <h3>This is watch 2</h3>
                  <asp:Button CommandName="NextView" ID="btnnext2" 
                     operateat="server" Text = "Go To Next" />
                  <asp:Button CommandName="PrevView" ID="btnprevious2" 
                     operateat="server" Text = "Go To Previous View" />
               </asp:View> 

               <asp:View ID="View3" operateat="server">
                  <h3> This is watch 3</h3>
                  <br />
                  <asp:Calendar ID="Calender1" operateat="server"></asp:Calendar>
                  <br />
                  <asp:Button  CommandArgument="0" 
                     CommandName="SwitchViewByIndex" ID="btn1st"   operateat="server" Text = "Go To Next" />
                  <asp:Button CommandName="PrevView" ID="btnprevious" 
                     operateat="server" Text = "Go To Previous View" />
               </asp:View> 
            </asp:MultiView>
         </div>
      </form>
   </body>
</html>

Observe the following:

The MultiView.ActiveViewIndex figure outs which watch will be shown. This is the only watch rendereddishdish on the page. The default value for the ActiveViewIndex is -1, when no watch is shown. Since the ActiveViewIndex is degreatd as 2 in the example, it shows the third watch, when executed.

MultiView

ASP.NET – Panel Controls

The Panel manage works as a container for other manages on the page. It manages the appearance and visibility of the manages it contains. It furthermore enables generating manages programmatically.

The fundamental syntax of panel manage is as follows:

<asp:Panel ID= "Panel1"  operateat = "server">
</asp:Panel>

The Panel manage is derived from the WebControl course. Hence it inherit is all the properlinks, methods and workionuallyts of the same. It does not have any kind of method or workionuallyt of it is own. However it has the following properlinks of it is own:

Properlinks Description
BackImageUrl URL of the background image of the panel.
DefaultButton Gets or sets the identifier for the default button thead put on is contained in the Panel manage.
Direction Text immediateion in the panel.
GroupingText Allows grouping of text as a field.
HorizontalAlign Horizontal alignment of the content in the panel.
ScrollBars Specifies visibility and location of scrollbars within the panel.
Wrap Allows text wrapping.

Worcalifornia king with the Panel Control

Let us start with a easy scrollable panel of specific height and width and a border style. The ScrollBars home is set to both the scrollbars, hence both the scrollbars are rendereddishdish.

The source file has the following code for the panel tag:

<asp:Panel ID="Panel1" operateat="server" BorderColor="#990000" BorderStyle="Solid" 
   Borderstyle="width:1px" Height="116px" ScrollBars="Both" style="width:278px">
   
   This is a scrollable panel.
   <br />
   <br />

   <asp:Button ID="btnpanel" operateat="server" Text="Button" style="width:82px" />
</asp:Panel>

The panel is rendereddishdish as follows:

Panel

Example

The following example demonstrates dynamic content generation. The user provides the number of label manages and textcontaineres to be generated on the panel. The manages are generated programmatically.

Change the properlinks of the panel uperform the properlinks window. When you select a manage on the design watch, the properlinks window displays the properlinks of thead put on particular manage and enables you to create changes without presently generally there typing.

Panel2

The source file for the example is as follows:

<form id="form1" operateat="server">
   <div>
      <asp:Panel ID="pnldynamic" operateat="server" BorderColor="#990000" 
         BorderStyle="Solid" Borderstyle="width:1px" Height="150px"  ScrollBars="Auto" style="width:60%" BackColor="#CCCCFF"  Font-Names="Courier" HorizontalAlign="Center">
     
         This panel shows dynamic manage generation:
         <br />
         <br />
      </asp:Panel>
   </div>

   <table style="width: 51%;">
      <tr>
         <td course="style2">No of Labels:</td>
         <td course="style1">
            <asp:DropDownList ID="ddllabels" operateat="server">
               <asp:ListItem>0</asp:ListItem>
               <asp:ListItem>1</asp:ListItem>
               <asp:ListItem>2</asp:ListItem>
               <asp:ListItem>3</asp:ListItem>
               <asp:ListItem>4</asp:ListItem>
            </asp:DropDownList>
         </td>
      </tr>

      <tr>
         <td course="style2"> </td>
         <td course="style1"> </td>
      </tr>

      <tr>
         <td course="style2">No of Text Boxes :</td>
         <td course="style1">
            <asp:DropDownList ID="ddltextcontainer" operateat="server">
               <asp:ListItem>0</asp:ListItem>
               <asp:ListItem Value="1"></asp:ListItem>
               <asp:ListItem>2</asp:ListItem>
               <asp:ListItem>3</asp:ListItem>
               <asp:ListItem Value="4"></asp:ListItem>
            </asp:DropDownList>
         </td>
      </tr>

      <tr>
         <td course="style2"> </td>
         <td course="style1"> </td>
      </tr>

      <tr>
         <td course="style2">
            <asp:CheckBox ID="chknoticeable" operateat="server" 
               Text="Make the Panel Visible" />
         </td>

         <td course="style1">
            <asp:Button ID="btnrefresh" operateat="server" Text="Refresh Panel" 
               style="width:129px" />
         </td>
      </tr>
   </table>
</form>

The code at the rear of the Page_Load workionuallyt is responsible for generating the manages dynamically:

public partial course _Default : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      //create the panel noticeable
      pnldynamic.Visible = chknoticeable.Checked;

      //generating the lable manages:
      int n = Int32.Parse(ddllabels.SelectedItem.Value);
      for (int i = 1; i <= n; i++)
      {
         Label lbl = brand new Label();
         lbl.Text = "Label" + (i).ToString();
         pnldynamic.Controls.Add(lbl);
         pnldynamic.Controls.Add(brand new LiteralControl("<br />"));
      }
      
      //generating the text container manages:

      int m = Int32.Parse(ddltextcontainer.SelectedItem.Value);
      for (int i = 1; i <= m; i++)
      {
         TextBox txt = brand new TextBox();
         txt.Text = "Text Box" + (i).ToString();
         pnldynamic.Controls.Add(txt);
         pnldynamic.Controls.Add(brand new LiteralControl("<br />"));
      }
   }
}

When executed, the panel is rendereddishdish as:

Panel3

ASP.NET – Ajax Control

AJAX stands for Asynchronous JavaScript and XML. This is a combination platform technology which speeds up response time. The AJAX server manages add script to the page which is executed and processed simply by the bcollectionser.

However like other ASP.NET server manages, these AJAX server manages furthermore can have methods and workionuallyt handlers associated with all of them, which are processed on the server aspect.

The manage toolcontainer in the Visual Studio IDE contains a group of manages calintroduced the 'AJAX Extensions'

AJAX Extensions

The ScriptManager Control

The ScriptManager manage is the many kind of iminterfaceant manage and must be present on the page for other manages to work.

It has the fundamental syntax:

<asp:ScriptManager ID="ScriptManager1" operateat="server">
</asp:ScriptManager>

If you generate an 'Ajax Enabintroduced site' or add an 'AJAX Web Form' from the 'Add Item' dialog container, the web form automatically contains the script manager manage. The ScriptManager manage conaspectrs care of the claynt-aspect script for all the server aspect manages.

The UpdatePanel Control

The UpdatePanel manage is a container manage and derives from the Control course. It workions as a container for the child manages within it and does not have it is own interface. When a manage inaspect it triggers a post back, the UpdatePanel intervenes to initiate the post asynchronously and update simply thead put on interfaceion of the page.

For example, if a button manage is withinaspect the update panel and it is clicked, only the manages within the update panel will be affected, the manages on the other parts of the page will not be affected. This is calintroduced the partial post back or the asynchronous post back.

Example

Add an AJAX web form in your own own application. It contains the script manager manage simply by default. Insert an update panel. Place a button manage adurationy with a label manage within the update panel manage. Place one more set of button and label out presently generally thereaspect the panel.

The design watch looks as follows:

ScriptManager

The source file is as follows:

<form id="form1" operateat="server">
   <div>
      <asp:ScriptManager ID="ScriptManager1" operateat="server" />
   </div>
   <asp:UpdatePanel ID="UpdatePanel1" operateat="server">
      <ContentTemplate>
         <asp:Button ID="btnpartial" operateat="server" 
            onclick="btnpartial_Click" Text="Partial PostBack"/>
         <br />
         <br />
         <asp:Label ID="lblpartial" operateat="server"></asp:Label>
      </ContentTemplate>
   </asp:UpdatePanel>
   <p> </p>
   <p>Outaspect the Update Panel</p>
   <p>
      <asp:Button ID="btntotal" operateat="server" 
         onclick="btntotal_Click" Text="Total PostBack" />
   </p>
   <asp:Label ID="lbltotal" operateat="server"></asp:Label>
</form>

Both the button manages have same code for the workionuallyt handler:

string time = DateTime.Now.ToLongTimeString();
lblpartial.Text = "Showing time from panel" + time;
lbltotal.Text = "Showing time from out presently generally thereaspect" + time;

Observe thead put on when the page is executed, if the total post back button is clicked, it updates time in both the labels but if the partial post back button is clicked, it only updates the label within the update panel.

update panel

A page can contain multiple update panels with every panel containing other manages like a grid and displaying various part of data.

When a total post back occurs, the update panel content is updated simply by default. This default mode can be changed simply by changing the UpdateMode home of the manage. Let us look at other properlinks of the update panel.

Properlinks of the UpdatePanel Control

The following table shows the properlinks of the update panel manage:

Properlinks Description
ChildrenAsTriggers This home indicates whether the post backs are coming from the child manages, which cause the update panel to refresh.
ContentTemplate It is the content template and degreats whead put on appears in the update panel when it is rendereddishdish.
ContentTemplateContainer Retrieves the dynamically generated template container object and used for adding child manages programmatically.
IsInPartialRendering Indicates whether the panel is being updated as part of the partial post back.
RenderMode Shows the render modes. The available modes are Block and Incollection.
UpdateMode Gets or sets the rendering mode simply by determining a few conditions.
Triggers Degreats the collection trigger objects every corresponding to an workionuallyt cauperform the panel to refresh automatically.

Methods of the UpdatePanel Control

The following table shows the methods of the update panel manage:

Methods Description
CreateContentTemplateContainer Creates a Control object thead put on workions as a container for child manages thead put on degreat the UpdatePanel manage's content.
CreateControlCollection Returns the collection of all manages thead put on are contained in the UpdatePanel manage.
Initialize Initializes the UpdatePanel manage trigger collection if partial-page rendering is enabintroduced.
Update Causes an update of the content of an UpdatePanel manage.

The behavior of the update panel depends upon the values of the UpdateMode home and ChildrenAsTriggers home.

UpdateMode ChildrenAsTriggers Effect
Always False Illegal parameters.
Always True UpdatePanel refreshes if whole page refreshes or a child manage on it posts back.
Conditional False UpdatePanel refreshes if whole page refreshes or a triggering manage out presently generally thereaspect it initiates a refresh.
Conditional True UpdatePanel refreshes if whole page refreshes or a child manage on it posts back or a triggering manage out presently generally thereaspect it initiates a refresh.

The UpdateProgress Control

The UpdateProgress manage provides a sort of give food toback on the bcollectionser while one or more update panel manages are being updated. For example, while a user logs in or wait around’s for server response while performing a few database oriented job.

It provides a visual acunderstandintroducadvantagement like "Loading page…", indicating the work is within progress.

The syntax for the UpdateProgress manage is:

<asp:UpdateProgress ID="UpdateProgress1" operateat="server" DynamicLayout presently generally there="true" 
   AssociatedUpdatePanelID="UpdatePanel1" >
   <ProgressTemplate>
      Loading...
   </ProgressTemplate>
</asp:UpdateProgress>

The above snippet shows a easy message within the ProgressTemplate tag. However, it can be an image or other relevant manages. The UpdateProgress manage displays for every asynchronous postback unless it is assigned to a performle update panel uperform the AssociatedUpdatePanelID home.

Properlinks of the UpdateProgress Control

The following table shows the properlinks of the update progress manage:

Properlinks Description
AssociatedUpdatePanelID Gets and sets the ID of the update panel with which this particular manage is associated.
Attributes Gets or sets the cascading style sheet (CSS) attributes of the UpdateProgress manage.
DisplayAfter Gets and sets the time in milli2nds after which the progress template is displayed. The default is 500.
DynamicLayout presently generally there Indicates whether the progress template is dynamically rendereddishdish.
ProgressTemplate Indicates the template displayed during an asynchronous post back which conaspectrs more time than the DisplayAfter time.

Methods of the UpdateProgress Control

The following table shows the methods of the update progress manage:

Methods Description
GetScriptDescriptors Returns a list of components, behaviors, and claynt manages thead put on are requireddishdish for the UpdateProgress manage's claynt functionality.
GetScriptReferences Returns a list of claynt script library dependencies for the UpdateProgress manage.

The Timer Control

The timer manage is used to initiate the post back automatically. This can be done in 2 ways:

(1) Setting the Triggers home of the UpdatePanel manage:

<Triggers> 
   <asp:AsyncPostBackTrigger ControlID="btnpanel2" EventName="Click" />
</Triggers>

(2) Placing a timer manage immediately inaspect the UpdatePanel to workion as a child manage trigger. A performle timer can be the trigger for multiple UpdatePanels.

<asp:UpdatePanel ID="UpdatePanel1" operateat="server" UpdateMode="Always">
   <ContentTemplate>
      <asp:Timer ID="Timer1" operateat="server" Interval="1000">
      </asp:Timer>
      <asp:Label ID="Label1" operateat="server" Height="101px" style="width:304px" >
      </asp:Label>
   </ContentTemplate>
</asp:UpdatePanel>

ASP.NET – Data Sources

A data source manage interworkions with the data-bound manages and hides the complex data binding processes. These are the tools thead put on provide data to the data bound manages and supinterface execution of operations like insertions, deallowions, sorting, and updates.

Each data source manage wraps a particular data provider-relational databases, XML documents, or custom coursees and helps in:

  • Managing interinterconnection
  • Selecting data
  • Managing presentation aspects like paging, caching, etc.
  • Manipulating data

There are many kind of data source manages available in ASP.NET for accesperform data from SQL Server, from ODBC or OLE DB servers, from XML files, and from business objects.

Based on type of data, these manages can be divided into 2 categories:

  • Hierarchical data source manages
  • Table-based data source manages

The data source manages used for hierarchical data are:

  • XMLDataSource – It enables binding to XML files and strings with or without presently generally there schema information.

  • SiteMapDataSource – It enables binding to a provider thead put on supplays site chart information.

The data source manages used for tabular data are:

Data source manages Description
SqlDataSource It represents a interinterconnection to an ADO.NET data provider thead put on returns SQL data, including data sources accessible via OLEDB and QDBC.
ObjectDataSource It enables binding to a custom .Net business object thead put on returns data.
LinqdataSource It enables binding to the results of a Linq-to-SQL query (supinterfaceed simply by ASP.NET 3.5 only).
AccessDataSource It represents interinterconnection to a Microsoft Access database.

Data Source Views

Data source watchs are objects of the DataSourceView course. Which represent a customised watch of data for various data operations such as sorting, filtering, etc.

The DataSourceView course serves as the base course for all data source watch coursees, which degreat the capabililinks of data source manages.

The following table provides the properlinks of the DataSourceView course:

Properlinks Description
CanDeallowe Indicates whether deallowion is enableed on the underlying data source.
CanInsert Indicates whether insertion is enableed on the underlying data source.
CanPage Indicates whether paging is enableed on the underlying data source.
CanRetrieveTotalRowCount Indicates whether total collection count information is available.
CanSort Indicates whether the data can be sorted.
CanUpdate Indicates whether updates are enableed on the underlying data source.
Events Gets a list of workionuallyt-handler delegates for the data source watch.
Name Name of the watch.

The following table provides the methods of the DataSourceView course:

Methods Description
CanExecute Determines whether the specified command can be executed.
ExecuteCommand Executes the specific command.
ExecuteDeallowe Performs a deallowe operation on the list of data thead put on the DataSourceView object represents.
ExecuteInsert Performs an insert operation on the list of data thead put on the DataSourceView object represents.
ExecuteSelect Gets a list of data from the underlying data storage.
ExecuteUpdate Performs an update operation on the list of data thead put on the DataSourceView object represents.
Deallowe Performs a deallowe operation on the data associated with the watch.
Insert Performs an insert operation on the data associated with the watch.
Select Returns the queried data.
Update Performs an update operation on the data associated with the watch.
OnDataSourceViewChanged Raises the DataSourceViewChanged workionuallyt.
RaiseUnsupinterfaceedCapabililinksError Calintroduced simply by the RaiseUnsupinterfaceedCapabililinksError method to compare the capabililinks requested for an ExecuteSelect operation against those thead put on the watch supinterfaces.

The SqlDataSource Control

The SqlDataSource manage represents a interinterconnection to a relational database such as SQL Server or Oracle database, or data accessible through OLEDB or Open Database Connectivity (ODBC). Connection to data is made through 2 iminterfaceant properlinks ConnectionString and ProviderName.

The following code snippet provides the fundamental syntax of the manage:

<asp:SqlDataSource operateat="server" ID="MySqlSource"
   ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName  %>'
   ConnectionString='<%$ ConnectionStrings:LocalNWind %>'
   SelectionCommand= "SELECT * FROM EMPLOYEES" />

<asp:GridView ID="GridView1" operateat="server" DataSourceID="MySqlSource" />

Configuring various data operations on the underlying data depends upon the various properlinks (home groups) of the data source manage.

The following table provides the related sets of properlinks of the SqlDataSource manage, which provides the programming interface of the manage:

Property Group Description

DealloweCommand,

DealloweParameters,

DealloweCommandType

Gets or sets the SQL statement, parameters, and type for deallowing collections in the underlying data.

FilterExpression,

FilterParameters

Gets or sets the data filtering string and parameters.

InsertCommand,

InsertParameters,

InsertCommandType

Gets or sets the SQL statement, parameters, and type for inserting collections in the underlying database.

SelectCommand,

SelectParameters,

SelectCommandType

Gets or sets the SQL statement, parameters, and type for retrieving collections from the underlying database.
SortParameterName Gets or sets the name of an input parameter thead put on the command's storeddishdish procedure will use to sort data.

UpdateCommand,

UpdateParameters,

UpdateCommandType

Gets or sets the SQL statement, parameters, and type for updating collections in the underlying data store.

The following code snippet shows a data source manage enabintroduced for data manipulation:

<asp:SqlDataSource operateat="server" ID= "MySqlSource"
   ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName  %>'
   ConnectionString=' <%$ ConnectionStrings:LocalNWind %>'
   SelectCommand= "SELECT * FROM EMPLOYEES"
   UpdateCommand= "UPDATE EMPLOYEES SET [email protected]"
   DealloweCommand= "DELETE FROM EMPLOYEES WHERE [email protected]"
   FilterExpression= "EMPLOYEEID > 10">
   .....
   .....
</asp:SqlDataSource>

The ObjectDataSource Control

The ObjectDataSource Control enables user-degreatd coursees to associate the out presently generally thereput of their methods to data bound manages. The programming interface of this particular course is almany kind of same as the SqlDataSource manage.

Following are 2 iminterfaceant aspects of binding business objects:

  • The bindable course need to have a default constructor, it need to be stateless, and have methods thead put on can be chartped to select, update, insert, and deallowe semantics.

  • The object must update one item at a time, batch operations are not supinterfaceed.

Let us go immediately to an example to work with this particular manage. The college college student course is the course to be used with an object data source. This course has 3 properlinks: a college college student id, name, and city. It has a default constructor and a GetStudents method for retrieving data.

The college college student course:

public course Student
{
   public int StudentID { get; set; }
   public string Name { get; set; }
   public string City { get; set; }
   public Student()
   { }
   public DataSet GetStudents()
   {
      DataSet ds = brand new DataSet();
      DataTable dt = brand new DataTable("Students");
      dt.Columns.Add("StudentID", typeof(System.Int32));
      dt.Columns.Add("StudentName", typeof(System.String));
      dt.Columns.Add("StudentCity", typeof(System.String));
      dt.Rows.Add(brand new object[] { 1, "M. H. Kabir", "Calcutta" });
      dt.Rows.Add(brand new object[] { 2, "Ayan J. Sarkar", "Calcutta" });
      ds.Tables.Add(dt);
      return ds;
   }
}

Take the following steps to bind the object with an object data source and retrieve data:

  • Create a brand new web site.

  • Add a course (Students.cs) to it simply by proper cliccalifornia king the project from the Solution Explorer, adding a course template, and placing the above code in it.

  • Build the solution so thead put on the application can use the reference to the course.

  • Place an object data source manage in the web form.

  • Configure the data source simply by selecting the object.

selecting the object

  • Select a data method(s) for various operations on data. In this particular example, presently generally there is only one method.

Select a data method

  • Place a data bound manage such as grid watch on the page and select the object data source as it is underlying data source.

Data Bound Control

  • At this particular stage, the design watch need to look like the following:

Object Data Source

  • Run the project, it retrieves the hard coded tuples from the college college students course.

Object Data Result

The AccessDataSource Control

The AccessDataSource manage represents a interinterconnection to an Access database. It is based on the SqlDataSource manage and provides easyr programming interface. The following code snippet provides the fundamental syntax for the data source:

<asp:AccessDataSource ID="AccessDataSource1 operateat="server" 
   DataFile="~/App_Data/ASPDotNetStepByStep.mdb" SelectCommand="SELECT * FROM  [DotNetReferences]">
</asp:AccessDataSource>

The AccessDataSource manage open ups the database in read-only mode. However, it can furthermore be used for performing insert, update, or deallowe operations. This is done uperform the ADO.NET commands and parameter collection.

Updates are issueatic for Access databases from within an ASP.NET application because an Access database is a ordinary file and the default account of the ASP.NET application may not have the permission to write to the database file.

ASP.NET – Data Binding

Every ASP.NET web form manage inherit is the DataBind method from it is parent Control course, which gives it an inherent capcapcapability to bind data to at minimumern one of it is properlinks. This is understandn as easy data binding or incollection data binding.

Simple data binding involves attaching any kind of collection (item collection) which implements the IEnumerable interface, or the DataSet and DataTable coursees to the DataSource home of the manage.

On the other hand, a few manages can bind records, lists, or columns of data into their structure through a DataSource manage. These manages derive from the BaseDataBoundControl course. This is calintroduced declarative data binding.

The data source manages help the data-bound manages implement functionalilinks such as, sorting, paging, and editing data collections.

The BaseDataBoundControl is an abstrworkion course, which is withinherited simply by 2 more abstrworkion coursees:

  • DataBoundControl
  • HierarchicalDataBoundControl

The abstrworkion course DataBoundControl is again inherited simply by 2 more abstrworkion coursees:

  • ListControl
  • CompositeDataBoundControl

The manages capable of easy data binding are derived from the ListControl abstrworkion course and these manages are:

  • BulallowedList
  • CheckBoxList
  • DropDownList
  • ListBox
  • RadioButtonList

The manages capable of declarative data binding (a more complex data binding) are derived from the abstrworkion course CompositeDataBoundControl. These manages are:

  • DetailsView
  • FormView
  • GridView
  • RecordList

Simple Data Binding

Simple data binding involves the read-only selection lists. These manages can bind to an array list or fields from a database. Selection lists conaspectrs 2 values from the database or the data source; one value is displayed simply by the list and the other is conaspectreddishdish as the value corresponding to the display.

Let us conaspectr up a small example to understand the concept. Create a web site with a bulallowed list and a SqlDataSource manage on it. Configure the data source manage to retrieve 2 values from your own own database (we use the same DotNetReferences table as in the previous chapter).

Chooperform a data source for the bulallowed list manage involves:

  • Selecting the data source manage
  • Selecting a field to display, which is calintroduced the data field
  • Selecting a field for the value

Choose Data Source

When the application is executed, check thead put on the entire title column is bound to the bulallowed list and displayed.

Choose Data Source2

Declarative Data Binding

We have already used declarative data binding in the previous tutorial uperform GridView manage. The other composite data bound manages capable of displaying and manipulating data in a tabular manner are the DetailsView, FormView, and RecordList manage.

In the next tutorial, we will look into the technology for handling database, i.e, ADO.NET.

However, the data binding involves the following objects:

  • A dataset thead put on stores the data retrieved from the database.

  • The data provider, which retrieves data from the database simply by uperform a command over a interinterconnection.

  • The data adapter thead put on issues the select statement storeddishdish in the command object; it is furthermore capable of update the data in a database simply by issuing Insert, Deallowe, and Update statements.

Relation between the data binding objects:

Declarative Data Binding

Example

Let us conaspectr the following steps:

Step (1) : Create a brand new website. Add a course named booklist simply by proper cliccalifornia king on the solution name in the Solution Explorer and chooperform the item 'Class' from the 'Add Item' dialog container. Name it as booklist.cs.

uperform System;
uperform System.Data;
uperform System.Configuration;
uperform System.Linq;
uperform System.Web;
uperform System.Web.Security;
uperform System.Web.UI;
uperform System.Web.UI.HtmlControls;
uperform System.Web.UI.WebControls;
uperform System.Web.UI.WebControls.WebParts;
uperform System.Xml.Linq;

namespace databinding
{
   public course booklist
   {
      protected String bookname;
      protected String authorname;
      public booklist(String bname, String aname)
      {
         this particular.bookname = bname;
         this particular.authorname = aname;

      }
      public String Book
      {
         get
         {
            return this particular.bookname;
         }
         set
         {
            this particular.bookname = value;
         }
      }
      public String Author
      {
         get
         {
            return this particular.authorname;
         }
         set
         {
            this particular.authorname = value;
         }
      }
   }
}

Step (2) : Add four list manages on the page a list container manage, a radio stations stations button list, a check container list, and a drop down list and four labels adurationy with these list manages. The page need to look like this particular within design watch:

List container manage

The source file need to look as the following:

<form id="form1" operateat="server">
   <div>
      <table style="width: 559px">
         <tr>
            <td style="width: 228px; height: 157px;">
               <asp:ListBox ID="ListBox1" operateat="server" AutoPostBack="True" 
                  OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
               </asp:ListBox>
            </td>

            <td style="height: 157px">
               <asp:DropDownList ID="DropDownList1" operateat="server" 
                  AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
               </asp:DropDownList>
            </td>             
         </tr>

         <tr>
            <td style="width: 228px; height: 40px;">
               <asp:Label ID="lbllistcontainer" operateat="server"></asp:Label>
            </td>

            <td style="height: 40px">
               <asp:Label ID="lbldrpdown" operateat="server">
               </asp:Label>
            </td>
         </tr>

         <tr>
            <td style="width: 228px; height: 21px">
            </td>

            <td style="height: 21px">
            </td>              
         </tr>

         <tr>
            <td style="width: 228px; height: 21px">
               <asp:RadioButtonList ID="RadioButtonList1" operateat="server"
                  AutoPostBack="True"  OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
               </asp:RadioButtonList>
            </td>

            <td style="height: 21px">
               <asp:CheckBoxList ID="CheckBoxList1" operateat="server" 
                  AutoPostBack="True" OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
               </asp:CheckBoxList>
            </td>                
         </tr>

         <tr>
            <td style="width: 228px; height: 21px">
               <asp:Label ID="lblrdlist" operateat="server">
               </asp:Label>
            </td>

            <td style="height: 21px">
               <asp:Label ID="lblchklist" operateat="server">
               </asp:Label>
            </td>           
         </tr>
      </table>       
   </div>
</form>

Step (3) : Finally, write the following code at the rear of rout presently generally thereines of the application:

public partial course _Default : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      IList bklist = generatebooklist();
      if (!this particular.IsPostBack)
      {
         this particular.ListBox1.DataSource = bklist;
         this particular.ListBox1.DataTextField = "Book";
         this particular.ListBox1.DataValueField = "Author";
         this particular.DropDownList1.DataSource = bklist;
         this particular.DropDownList1.DataTextField = "Book";
         this particular.DropDownList1.DataValueField = "Author";
         this particular.RadioButtonList1.DataSource = bklist;
         this particular.RadioButtonList1.DataTextField = "Book";
         this particular.RadioButtonList1.DataValueField = "Author";
         this particular.CheckBoxList1.DataSource = bklist;
         this particular.CheckBoxList1.DataTextField = "Book";
         this particular.CheckBoxList1.DataValueField = "Author";
         this particular.DataBind();
      }
   }
   protected IList generatebooklist()
   {
      ArrayList allbooks = brand new ArrayList();
      booklist bl;
      bl = brand new booklist("UNIX CONCEPTS", "SUMITABHA DAS");
      allbooks.Add(bl);
      bl = brand new booklist("PROGRAMMING IN C", "RICHI KERNIGHAN");
      allbooks.Add(bl);
      bl = brand new booklist("DATA STRUCTURE", "TANENBAUM");
      allbooks.Add(bl);
      bl = brand new booklist("NETWORKING CONCEPTS", "FOROUZAN");
      allbooks.Add(bl);
      bl = brand new booklist("PROGRAMMING IN C++", "B. STROUSTROUP");
      allbooks.Add(bl);
      bl = brand new booklist("ADVANCED JAVA", "SUMITABHA DAS");
      allbooks.Add(bl);
      return allbooks;
   }
   protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
   {
      this particular.lbllistcontainer.Text = this particular.ListBox1.SelectedValue;
   }
   protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
   {
      this particular.lbldrpdown.Text = this particular.DropDownList1.SelectedValue;
   }
   protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
   {
      this particular.lblrdlist.Text = this particular.RadioButtonList1.SelectedValue;
   }
   protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
   {
      this particular.lblchklist.Text = this particular.CheckBoxList1.SelectedValue;
   }
}

Observe the following:

  • The booklist course has 2 properlinks: bookname and authorname.

  • The generatebooklist method is a user degreatd method thead put on generates an array of booklist objects named allbooks.

  • The Page_Load workionuallyt handler ensures thead put on a list of books is generated. The list is of IList type, which implements the IEnumerable interface and capable of being bound to the list manages. The page load workionuallyt handler binds the IList object 'bklist' with the list manages. The bookname home is to be displayed and the authorname home is conaspectreddishdish as the value.

  • When the page is operate, if the user selects a book, it is name is selected and displayed simply by the list manages whereas the corresponding labels display the author name, which is the corresponding value for the selected index of the list manage.

Data Binding Results

ASP.NET – Custom Controls

User Controls

User manages behaves like miniature ASP.NET pages or web forms, which can be used simply by many kind of other pages. These are derived from the System.Web.UI.UserControl course. These manages have the following charworkioneristics:

  • They have an .ascx extension.
  • They may not contain any kind of <html>, <body>, or <form> tags.
  • They have a Control immediateive instead of a Page immediateive.

To understand the concept, allow us generate a easy user manage, which will work as footer for the web pages. To generate and use the user manage, conaspectr the following steps:

  • Create a brand new web application.
  • Right click on the project folder on the Solution Explorer and choose Add New Item.
    Add New Item
  • Select Web User Control from the Add New Item dialog container and name it footer.ascx. Initially, the footer.ascx contains only a Control immediateive.

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="footer.ascx.cs" 
       Inherit is="custommanagedemo.footer" %>
    
  • Add the following code to the file:

    <table>
       <tr>
          <td align="centre"> Copyproper ©2010 TutorialPoints Ltd.</td>
       </tr>
    
       <tr>
          <td align="centre"> Location: Hyderabad, A.P </td>
       </tr>
    </table>
    

To add the user manage to your own own web page, you must add the Register immediateive and an instance of the user manage to the page. The following code shows the content file:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
   Inherit is="custommanagedemo._Default" %>
<%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head operateat="server">
      <title>
         Untitintroduced Page
      </title>
   </head>
   <body>
      <form id="form1" operateat="server">
         <div>
            <asp:Label ID="Label1" operateat="server" 
               Text="Welcome to ASP.Net Tutorials "></asp:Label>
            <br />
            <br />
            <asp:Button ID="Button1" operateat="server" 
               onclick="Button1_Click"  Text="Copyproper Info" />
         </div>
         <Tfooter:footer ID="footer1" operateat="server" />
      </form>
   </body>
</html>

When executed, the page shows the footer and this particular manage can be used in all the pages of your own own website.

Custom Result

Observe the following:

(1) The Register immediateive specifies a tag name as well as tag prefix for the manage.

<%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter" %>

(2) The following tag name and prefix need to be used while adding the user manage on the page:

<Tfooter:footer ID="footer1" operateat="server" />

Custom Controls

Custom manages are deployed as individual assemblays. They are compiintroduced into a Dynamic Link Library (DLL) and used as any kind of other ASP.NET server manage. They can be generated in either of the following way:

  • By deriving a custom manage from an existing manage
  • By compoperform a brand new custom manage combing 2 or more existing manages.
  • By deriving from the base manage course.

To understand the concept, allow us generate a custom manage, which will simply render a text message on the bcollectionser. To generate this particular manage, conaspectr the following steps:

Create a brand new website. Right click the solution (not the project) at the top of the tree in the Solution Explorer.

Solution Explorer

In the New Project dialog container, select ASP.NET Server Control from the project templates.

project templates

The above step adds a brand new project and generates a compallowe custom manage to the solution, calintroduced ServerControl1. In this particular example, allow us name the project CustomControls. To use this particular manage, this particular must be added as a reference to the web site before registering it on a page. To add a reference to the existing project, proper click on the project (not the solution), and click Add Reference.

Select the CustomControls project from the Projects tab of the Add Reference dialog container. The Solution Explorer need to show the reference.

Custom Controls

To use the manage on a page, add the Register immediateive simply below the @Page immediateive:

<%@ Register Assembly="CustomControls"  Namespace="CustomControls"  TagPrefix="ccs" %>

Further, you can use the manage, similar to any kind of other manages.

<form id="form1" operateat="server">
   <div>
      <ccs:ServerControl1 operateat="server" 
         Text = "I am a Custom Server Control" />
   </div> 
</form>

When executed, the Text home of the manage is rendereddishdish on the bcollectionser as shown:

Custom Server Controls

Worcalifornia king with Custom Controls

In the previous example, the value for the Text home of the custom manage was set. ASP.NET added this particular home simply by default, when the manage was generated. The following code at the rear of file of the manage reveals this particular.

uperform System;
uperform System.Collections.Generic;
uperform System.ComponentModel;
uperform System.Linq;
uperform System.Text;
uperform System.Web;
uperform System.Web.UI;
uperform System.Web.UI.WebControls;

namespace CustomControls
{
   [DefaultProperty("Text")]
   [ToolcontainerData("<{0}:ServerControl1 operateat=server></{0}:ServerControl1 >")]
   public course ServerControl1 : WebControl
   {
      [Bindable(true)]
      [Category("Appearance")]
      [DefaultValue("")]
      [Localizable(true)]
      public string Text
      {
         get
         {
            String s = (String)ViewState["Text"];
            return ((s == null) ? "[" + this particular.ID + "]" : s);
         }
         set
         {
            ViewState["Text"] = value;
         }
      }
      protected override void RenderContents(HtmlTextWriter out presently generally thereput)
      {
         out presently generally thereput.Write(Text);
      }
   }
}

The above code is automatically generated for a custom manage. Events and methods can be added to the custom manage course.

Example

Let us expand the previous custom manage named SeverControl1. Let us give it a method named checkpalindrome, which gives it a power to check for palindromes.

Palindromes are words/literals thead put on spell the same when reversed. For example, Malayalam, madam, saras, etc.

Extend the code for the custom manage, which need to look as:

uperform System;
uperform System.Collections.Generic;
uperform System.ComponentModel;
uperform System.Linq;
uperform System.Text;
uperform System.Web;
uperform System.Web.UI;
uperform System.Web.UI.WebControls;

namespace CustomControls
{
   [DefaultProperty("Text")]
   [ToolcontainerData("<{0}:ServerControl1 operateat=server></{0}:ServerControl1  >")]
   public course ServerControl1 : WebControl
   {
      [Bindable(true)]
      [Category("Appearance")]
      [DefaultValue("")]
      [Localizable(true)]
      public string Text
      {
         get
         {
            String s = (String)ViewState["Text"];
            return ((s == null) ? "[" + this particular.ID + "]" : s);
         }
         set
         {
            ViewState["Text"] = value;
         }
      }
      protected override void RenderContents(HtmlTextWriter out presently generally thereput)
      {
         if (this particular.checkpanlindrome())
         {
            out presently generally thereput.Write("This is a palindrome: <br />");
            out presently generally thereput.Write("<FONT size=5 colour=Blue>");
            out presently generally thereput.Write("<B>");
            out presently generally thereput.Write(Text);
            out presently generally thereput.Write("</B>");
            out presently generally thereput.Write("</FONT>");
         }
         else
         {
            out presently generally thereput.Write("This is not a palindrome: <br />");
            out presently generally thereput.Write("<FONT size=5 colour=reddishdish>");
            out presently generally thereput.Write("<B>");
            out presently generally thereput.Write(Text);
            out presently generally thereput.Write("</B>");
            out presently generally thereput.Write("</FONT>");
         }
      }
      protected bool checkpanlindrome()
      {
         if (this particular.Text != null)
         {
            String str = this particular.Text;
            String strtoupper = Text.ToUpper();
            char[] rev = strtoupper.ToCharArray();
            Array.Reverse(rev);
            String strrev = brand new String(rev);
            if (strtoupper == strrev)
            {
               return true;
            }
            else
            {
               return false;
            }
         }
         else
         {
            return false;
         }
      }
   }
}

When you change the code for the manage, you must construct the solution simply by cliccalifornia king Build –> Build Solution, so thead put on the changes are reflected in your own own project. Add a text container and a button manage to the page, so thead put on the user can provide a text, it is checked for palindrome, when the button is clicked.

<form id="form1" operateat="server">
   <div>
      Enter a word:
      <br />
      <asp:TextBox ID="TextBox1" operateat="server" style="width:198px">
      </asp:TextBox>
      <br />
      <br />
      <asp:Button ID="Button1" operateat="server onclick="Button1_Click" 
         Text="Check Palindrome" style="width:132px" />
      <br />
      <br />
      <ccs:ServerControl1 ID="ServerControl11" operateat="server" Text = "" />
   </div>
</form>

The Click workionuallyt handler for the button simply copies the text from the text container to the text home of the custom manage.

protected void Button1_Click(object sender, EventArgs e)
{
   this particular.ServerControl11.Text = this particular.TextBox1.Text;
}

When executed, the manage successcompallowey checks palindromes.

checks palindromes

Observe the following:

(1) When you add a reference to the custom manage, it is added to the toolcontainer and you can immediately use it from the toolcontainer similar to any kind of other manage.

custom manage reference

(2) The RenderContents method of the custom manage course is overridden here, as you can add your own own own methods and workionuallyts.

(3) The RenderContents method conaspectrs a parameter of HtmlTextWriter type, which is responsible for rendering on the bcollectionser.

ASP.NET – Personalization

Web sites are designed for repeated visit is from the users. Personalization enables a site to remember the user identity and other information details, and it presents an individualistic environment to every user.

ASP.NET provides services for privateizing a web site to suit a particular claynt's taste and preference.

Understanding Profiles

ASP.NET privateization service is based on user profile. User profile degreats the kind of information about presently generally there the user thead put on the site needs. For example, name, age, adgown, date of birth, and phone number.

This withinformation is degreatd in the web.config file of the application and ASP.NET operatetime reads and uses it. This job is done simply by the privateization providers.

The user profiles obtained from user data is storeddishdish in a default database generated simply by ASP.NET. You can generate your own own own database for storing profiles. The profile data definition is storeddishdish in the configuration file web.config.

Example

Let us generate a sample site, where we want our application to remember user details like name, adgown, date of birth etc. Add the profile details in the web.config file within the <system.web> element.

<configuration>
<system.web>
<profile>
   <properlinks>
      <add name="Name" type ="String"/>
      <add name="Birthday" type ="System.DateTime"/>
      <group name="Adgown">
         <add name="Street"/>
         <add name="City"/>
         <add name="State"/>
         <add name="Zipcode"/>
      </group>
   </properlinks>
</profile>
</system.web>
</configuration>

When the profile is degreatd in the web.config file, the profile can be used through the Profile home found in the current HttpContext and furthermore available via page.

Add the text containeres to conaspectr the user input as degreatd in the profile and add a button for submitting the data:

Personalization

Update Page_load to display profile information:

uperform System;
uperform System.Data;
uperform System.Configuration;
uperform System.Web;
uperform System.Web.Security;
uperform System.Web.UI;
uperform System.Web.UI.WebControls;
uperform System.Web.UI.WebControls.WebParts;
uperform System.Web.UI.HtmlControls;

public partial course _Default : System.Web.UI.Page 
{
   protected void Page_Load(object sender, EventArgs e)
   {
      if (!this particular.IsPostBack)
      {
         ProfileCommon pc=this particular.Profile.GetProfile(Profile.UserName);
         if (pc != null)
         {
            this particular.txtname.Text = pc.Name;
            this particular.txtaddr.Text = pc.Adgown.Street;
            this particular.txtcity.Text = pc.Adgown.City;
            this particular.txtstate.Text = pc.Adgown.State;
            this particular.txtzip.Text = pc.Adgown.Zipcode;
            this particular.Calendar1.SelectedDate = pc.Birthday;
         }
      }
   }
}

Write the following handler for the Submit button, for saving the user data into the profile:

protected void btnsubmit_Click(object sender, EventArgs e)
{
   ProfileCommon pc=this particular.Profile.GetProfile(Profile.UserName);
   if (pc != null)
   {
      pc.Name = this particular.txtname.Text;
      pc.Adgown.Street = this particular.txtaddr.Text;
      pc.Adgown.City = this particular.txtcity.Text;
      pc.Adgown.State = this particular.txtstate.Text;
      pc.Adgown.Zipcode = this particular.txtzip.Text;
      pc.Birthday = this particular.Calendar1.SelectedDate;
      pc.Save();
   }
}

When the page is executed for the 1st time, the user needs to enter the information. However, next time the user details would be automatically loaded.

Attributes for the <add> Element

Apart from the name and type attributes thead put on we have used, presently generally there are other attributes to the <add> element. Following table illustrates a few of these attributes:

Attributes Description
name The name of the home.
type By default the type is string but it enables any kind of compallowey qualified course name as data type.
serializeAs The format to use when serializing this particular value.
readOnly A read only profile value cannot be changed, simply by default this particular home is false.
defaultValue A default value thead put on is used if the profile does not exist or does not have information.
enableAnonymous A Boolean value indicating whether this particular home can be used with the anonymous profiles.
Provider The profiles provider thead put on need to be used to manage simply this particular home.

Anonymous Personalization

Anonymous privateization enables the user to privateise the site before identifying all of themselves. For example, Amazon.com enables the user to add items in the shopping cart before they log in. To enable this particular feature, the web.config file can be configureddishdish as:

<anonymousIdentification enabintroduced ="true" cookieName=".ASPXANONYMOUSUSER"
   cookieTimeout presently generally there="120000" cookiePath="/" cookieRequiresSSL="false"
   cookieSlidingExpiration="true" cookieprotection="Enweepption"
   greatayless="UseDeviceProfile"/>

ASP.NET – Error Handling

Error handling in ASP.NET has 3 aspects:

  • Tracing – tracing the program execution at page level or application level.

  • Error handling – handling standard errors or custom errors at page level or application level.

  • Debugging – stepping through the program, setting break stages to analyze the code

In this particular chapter, we will speak about tracing and error handling and in this particular chapter, we will speak about debugging.

To understand the concepts, generate the following sample application. It has a label manage, a dropdown list, and a link. The dropdown list loads an array list of famous quotes and the selected quote is shown in the label below. It furthermore has a hyperlink which has stages to a nonexistent link.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
   Inherit is="errorhandling._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head operateat="server">
      <title>
         Tracing, debugging and error handling
      </title>
   </head>
   <body>
      <form id="form1" operateat="server">
         <div>
            <asp:Label ID="lblheading" operateat="server" Text="Tracing, Debuggin  and Error Handling">
            </asp:Label>
            <br />
            <br />
            <asp:DropDownList ID="ddlquotes" operateat="server" AutoPostBack="True" 
               onselectedindexchanged="ddlquotes_SelectedIndexChanged">
            </asp:DropDownList>
            <br />
            <br />
            <asp:Label ID="lblquotes" operateat="server">
            </asp:Label>
            <br />
            <br />
            <asp:HyperLink ID="HyperLink1" operateat="server" 
               NavigateUrl="mylink.htm">Link to:</asp:HyperLink>
         </div>
      </form>
   </body>
</html>

The code at the rear of file:

public partial course _Default : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      if (!IsPostBack)
      {
         string[,] quotes = 
         {
            {"Imagination is more iminterfaceant than Knowintroducadvantage.", "Albert Einsten"},
            {"Assume a virtue, if you have it not" "Shakespeare"},
            {"A man cannot be comfortable without presently generally there his own approval", "Mark Twain"},
            {"Bebattlee the youngerer doctor and the old barber", "Benjamin Franklin"},
            {"Whead put onever begun in anger ends in shame", "Benjamin Franklin"}
         };
         for (int i=0; i<quotes.GetLength(0); i++)
            ddlquotes.Items.Add(brand new ListItem(quotes[i,0], quotes[i,1]));
      }
   }
   protected void ddlquotes_SelectedIndexChanged(object sender, EventArgs e)
   {
      if (ddlquotes.SelectedIndex != -1)
      {
         lblquotes.Text = String.Format("{0}, Quote: {1}", 
            ddlquotes.SelectedItem.Text, ddlquotes.SelectedValue);
      }
   }
}

Tracing

To enable page level tracing, you need to modify the Page immediateive and add a Trace attribute as shown:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
   Inherit is="errorhandling._Default" Trace ="true" %>

Now when you execute the file, you get the tracing information:

Tracing Info

It provides the following information at the top:

  • Session ID
  • Status Code
  • Time of Request
  • Type of Request
  • Request and Response Encoding

The status code sent from the server, every time the page is requested shows the name and time of error if any kind of. The following table shows the common HTTP status codes:

Number Description
Informational (100 – 199)
100 Continue
101 Switching protocols
Successful (200 – 299)
200 OK
204 No content
Reimmediateion (300 – 399)
301 Moved permanently
305 Use proxy
307 Temporary reddishdishirect
Claynt Errors (400 – 499)
400 Bad request
402 Payment requireddishdish
404 Not found
408 Request timeout presently generally there
417 Expectation faiintroduced
Server Errors (500 – 599)
500 Internal server error
503 Service unavailable
505 HTTP version not supinterfaceed

Under the top level information, presently generally there is Trace log, which provides details of page life cycle. It provides elapsed time in 2nds since the page was preliminaryized.

Tracing Info2

The next section is manage tree, which lists all manages on the page in a hierarchical manner:

Tracing Info3

Last in the Session and Application state summaries, cookies, and headers collections followed simply by list of all server variables.

The Trace object enables you to add custom information to the trace out presently generally thereput. It has 2 methods to accomplish this particular: the Write method and the Warn method.

Change the Page_Load workionuallyt handler to check the Write method:

protected void Page_Load(object sender, EventArgs e)
{
   Trace.Write("Page Load");
   if (!IsPostBack)
   {
      Trace.Write("Not Post Back, Page Load");
      string[,] quotes = 
      .......................
   }
}

Run to observe the effects:

Tracing Info4

To check the Warn method, allow us forcibly enter a few erroneous code in the selected index changed workionuallyt handler:

check
{
   int a = 0;
   int b = 9 / a;
}
capture (Exception e)
{
   Trace.Warn("UserAction", "procesperform 9/a", e);
}

Try-Catch is a C# programming construct. The check block holds any kind of code thead put on may or may not produce error and the capture block capturees the error. When the program is operate, it sends the battlening in the trace log.

Tracing Info5

Application level tracing applays to all the pages in the web site. It is implemented simply by putting the following code collections in the web.config file:

<system.web>
   <trace enabintroduced="true" />
</system.web>

Error Handling

Although ASP.NET can detect all operatetime errors, still a few subtle errors may still be presently generally there. Observing the errors simply by tracing is meant for the generateers, not for the users.

Hence, to intercept such occurrence, you can add error handing settings in the web.config file of the application. It is application-wide error handling. For example, you can add the following collections in the web.config file:

<configuration>
   <system.web>
      <customErrors mode="RemoteOnly" defaultReimmediate="GenericErrorPage.htm">
         <error statusCode="403" reddishdishirect="NoAccess.htm"	/>
         <error statusCode="404" reddishdishirect="FileNotFound.htm" />
      </customErrors>
   </system.web>
<configuration>

The <customErrors> section has the feasible attributes:

  • Mode : It enables or disables custom error pages. It has the 3 feasible values:

    • On : displays the custom pages.
    • Off : displays ASP.NET error pages (yellow pages)
    • remoteOnly : It displays custom errors to claynt, display ASP.NET errors locally.
  • defaultReimmediate : It contains the URL of the page to be displayed in case of unhandintroduced errors.

To put various custom error pages for various type of errors, the <error> sub tags are used, where various error pages are specified, based on the status code of the errors.

To implement page level error handling, the Page immediateive can be modified:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
   Inherit is="errorhandling._Default" Trace ="true" ErrorPage="PageError.htm" %>

Because ASP.NET Debugging is an iminterfaceant subject in it iself, so we would speak about it in the next chapter separately.

ASP.NET – Debugging

Debugging enables the generateers to see how the code works in a step-simply by-step manner, how the values of the variables change, how the objects are generated and destroyed, etc.

When the site is executed for the 1st time, Visual Studio displays a prompt ascalifornia king whether it need to be enabintroduced for debugging:

Debugging Info

When debugging is enabintroduced, the following collections of codes are shown in the web.config:

<system.web>
   <compilation debug="true">
      <assemblays>
      ..............
      </assemblays>
   </compilation>	
</system.web>

The Debug toolbar provides all the tools available for debugging:

Debugging toolbar

Breakstages

Breakstages specifies the operatetime to operate a specific collection of code and then cease execution so thead put on the code can be examined and perform various debugging jobs such as, changing the value of the variables, step through the codes, moving in and out presently generally there of functions and methods etc.

To set a breakstage, proper click on the code and choose insert break stage. A reddishdish dot appears on the left margin and the collection of code is highlighted as shown:

Breacalifornia king Highlighted

Next when you execute the code, you can observe it is behavior.

Breacalifornia king Highlighted2

At this particular stage, you can step through the code, observe the execution flow and examine the value of the variables, properlinks, objects, etc.

You can modify the properlinks of the breakstage from the Properlinks menu obtained simply by proper cliccalifornia king the breakstage glyph:

Breacalifornia king Dropdown

The location dialog container shows the location of the file, collection number and the charworkioner number of the selected code. The condition menu item enables you to enter a valid expression, which is evaluated when the program execution reveryes the breakstage:

Breacalifornia king Condition

The Hit Count menu item displays a dialog container thead put on shows the number of times the break stage has been executed.

Breacalifornia king Point

Cliccalifornia king on any kind of option presented simply by the drop down list open ups an edit field where a target hit count is entereddishdish. This is particularly helpful in analyzing loop constructs in code.

Breacalifornia king Point2

The Filter menu item enables setting a filter for specifying machines, processes, or threads or any kind of combination, for which the breakstage will be effective.

Breacalifornia king Filters

The When Hit menu item enables you to specify whead put on to do when the break stage is hit.

Breacalifornia king Point3

The Debug Windows

Visual Studio provides the following debug windows, every of which shows a few program information. The following table lists the windows:

Window Description
Immediate Displays variables and expressions.
Autos Displays all variables in the current and previous statements.
Locals Displays all variables in the current context.
Watch Displays up to four various sets of variables.
Call Stack Displays all methods in the call stack.
Threads Displays and manage threads.

ASP.NET – LINQ

Most applications are data-centric, however many kind of of the data repositories are relational databases. Over the calendar years, designers and generateers have designed applications based on object models.

The objects are responsible for connecting to the data access components – calintroduced the Data Access Layer (DAL). Here we have 3 stages to conaspectr:

  • All the data needed in an application are not storeddishdish in the same source. The source can be a relation database, a few business object, XML file, or a web service.

  • Accesperform in-memory object is easyr and less expensive than accesperform data from a database or XML file.

  • The data accessed are not used immediately, but needs to be sorted, ordereddishdish, grouped, altereddishdish etc.

Hence if presently generally there is one tool thead put on creates all kind of data access easy thead put on enables joining data from such disparate data sources and perform standard data procesperform operations, in few collections of codes, it would be of great help.

LINQ or Language-Integrated Query is such a tool. LINQ is set of extensions to the .Net Framework 3.5 and it is managed languages thead put on set the query as an object. It degreats a common syntax and a programming model to query various types of data uperform a common language.

The relational operators like Select, Project, Join, Group, Partition, Set operations etc., are implemented in LINQ and the C# and VB compilers in the .Net framework 3.5, which supinterface the LINQ syntax creates it feasible to work with a configureddishdish data store without presently generally there resorting to ADO.NET.

For example, querying the Customers table in the Northwind database, uperform LINQ query in C#, the code would be:

var data = from c in dataContext.Customers
where c.Councheck == "Spain"
select c;

Where:

  • The 'from' keyword logically loops through the contents of the collection.

  • The expression with the 'where' keyword is evaluated for every object in the collection.

  • The 'select' statement selects the evaluated object to add to the list being returned.

  • The 'var' keyword is for variable declaration. Since the exworkion type of the returned object is not understandn, it indicates thead put on the information will be inferreddishdish dynamically.

LINQ query can be applayd to any kind of data-bearing course thead put on inherit is from IEnumerable<T>, here T is any kind of data type, for example, List<Book>.

Let us look at an example to understand the concept. The example uses the following course: Books.cs

public course Books
{
   public string ID {get; set;}
   public string Title { get; set; }
   public decimal Price { get; set; }
   public DateTime DateOfRelrelayve { get; set; }

   public static List<Books> GetBooks()
   {
      List<Books> list = brand new List<Books>();
      list.Add(brand new Books { ID = "001", 
      Title = "Programming in C#", 
      Price = 634.76m, 
      DateOfRelrelayve = Convert.ToDateTime("2010-02-05") });
     
      list.Add(brand new Books { ID = "002", 
      Title = "Learn Java in 30 days", 
      Price = 250.76m, 
      DateOfRelrelayve = Convert.ToDateTime("2011-08-15") });
     
      list.Add(brand new Books { ID = "003", 
      Title = "Programming in ASP.Net 4.0", 
      Price = 700.00m, 
      DateOfRelrelayve = Convert.ToDateTime("2011-02-05") });
     
      list.Add(brand new Books { ID = "004", 
      Title = "VB.Net Made Easy", 
      Price = 500.99m, 
      DateOfRelrelayve = Convert.ToDateTime("2011-12-31") });
     
      list.Add(brand new Books { ID = "005", 
      Title = "Programming in C", 
      Price = 314.76m, 
      DateOfRelrelayve = Convert.ToDateTime("2010-02-05") });
     
      list.Add(brand new Books { ID = "006", 
      Title = "Programming in C++", 
      Price = 456.76m, 
      DateOfRelrelayve = Convert.ToDateTime("2010-02-05") });
     
      list.Add(brand new Books { ID = "007", 
      Title = "Datebase Developement", 
      Price = 1000.76m, 
      DateOfRelrelayve = Convert.ToDateTime("2010-02-05") });
      return list;
   }
}

The web page uperform this particular course has a easy label manage, which displays the titles of the books. The Page_Load workionuallyt generates a list of books and returns the titles simply by uperform LINQ query:

public partial course easyquery : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      List<Books> books = Books.GetBooks();
      var booktitles = from b in books select b.Title;

      forevery (var title in booktitles)
      lblbooks.Text += String.Format("{0} <br />", title);
   }
}

When the page is executed, the label displays the results of the query:

LINQ Result

The above LINQ expression:

var booktitles = 
from b in books 
select b.Title;

Is equivalent to the following SQL query:

SELECT Title from Books

LINQ Operators

Apart from the operators used so far, presently generally there are lots of other operators, which implement all query clauses. Let us look at a few of the operators and clauses.

The Join clause

The 'join clause' in SQL is used for joining 2 data tables and displays a data set containing columns from both the tables. LINQ is furthermore capable of thead put on. To check this particular, add one more course named Saintroducedetails.cs in the previous project:

public course Salesdetails
{
   public int sales { get; set; }
   public int pages { get; set; }
   public string ID {get; set;}

   public static IEnumerable<Salesdetails> getsalesdetails()
   { 
      Salesdetails[] sd = 
      {
         brand new Salesdetails { ID = "001", pages=678, sales = 110000},
         brand new Salesdetails { ID = "002", pages=789, sales = 60000},
         brand new Salesdetails { ID = "003", pages=456, sales = 40000},
         brand new Salesdetails { ID = "004", pages=900, sales = 80000},
         brand new Salesdetails { ID = "005", pages=456, sales = 90000},
         brand new Salesdetails { ID = "006", pages=870, sales = 50000},
         brand new Salesdetails { ID = "007", pages=675, sales = 40000},
      };
      return sd.OfType<Salesdetails>();
   }
}

Add the codes in the Page_Load workionuallyt handler to query on both the tables uperform the join clause:

protected void Page_Load(object sender, EventArgs e)
{
   IEnumerable<Books> books = Books.GetBooks();
   IEnumerable<Salesdetails> sales = Salesdetails.getsalesdetails();
   var booktitles = from b in books join s in sales on b.ID equals s.ID
      select brand new { Name = b.Title, Pages = s.pages };
   forevery (var title in booktitles)
      lblbooks.Text += String.Format("{0} <br />", title);
}

The resulting page is as shown:

LINQ Result2

The Where clause

The 'where clause' enables adding a few conditional filters to the query. For example, if you want to see the books, where the number of pages are more than 500, change the Page_Load workionuallyt handler to:

var booktitles = from b in books join s in sales on b.ID equals s.ID
   where s.pages > 500 select brand new { Name = b.Title, Pages = s.pages };

The query returns only those collections, where the number of pages is more than 500:

LINQ Result3

Ordersimply by and Ordersimply bydescending Clauses

These clauses enable sorting the query results. To query the titles, number of pages and price of the book, sorted simply by the price, write the following code in the Page_Load workionuallyt handler:

var booktitles = from b in books join s in sales on b.ID equals s.ID
   ordersimply by b.Price select brand new { Name = b.Title,  Pages = s.pages, Price = b.Price};

The returned tuples are:

LINQ Result4

The Let clause

The allow clause enables defining a variable and assigning it a value calculated from the data values. For example, to calculate the total sale from the above 2 sales, you need to calculate:

TotalSale = Price of the Book * Sales

To achieve this particular, add the following code snippets in the Page_Load workionuallyt handler:

The allow clause enables defining a variable and assigning it a value calculated from the data values. For example, to calculate the total sale from the above 2 sales, you need to calculate:

var booktitles = from b in book join s in sales on b.ID equals s.ID
   allow totalprofit = (b.Price * s.sales)
   select brand new { Name = b.Title, TotalSale = totalprofit};

The resulting query page is as shown:

LINQ Result5

ASP.NET – Security

Implementing security in a site has the following aspects:

  • Authentication : It is the process of ensuring the user's identity and authenticity. ASP.NET enables four types of authentications:

    • Windows Authentication
    • Forms Authentication
    • Passinterface Authentication
    • Custom Authentication
  • Authorization : It is the process of defining and allotting specific roles to specific users.

  • Confidentiality : It involves enweeppting the channel between the claynt bcollectionser and the web server.

  • Integrity : It involves maintaining the integrity of data. For example, implementing digital sigcharworker.

Forms-Based Authentication

Traditionally, forms-based authentication involves editing the web.config file and adding a login page with appropriate authentication code.

The web.config file can be edited and the following codes generated on it:

<configuration>
<system.web>
   <authentication mode="Forms">
      <forms loginUrl ="login.aspx"/>
   </authentication>
   <authorization>
      <deny users="?"/>
   </authorization>
</system.web>
...
...
</configuration>

The login.aspx page mentioned in the above code snippet could have the following code at the rear of file with the usernames and passwords for authentication hard coded into it.

protected bool authenticate(String uname, String pass)
{
   if(uname == "Tom")
   {
      if(pass == "tom123")
      return true;
   }
   if(uname == "Dick")
   {
      if(pass == "dick123")
      return true;
   }
   if(uname == "Harry")
   {
      if(pass == "har123")
      return true;
   }
   return false;
}
public void OnLogin(Object src, EventArgs e)
{
   if (authenticate(txtuser.Text, txtpwd.Text))
   {
      FormsAuthentication.ReimmediateFromLoginPage(txtuser.Text, chkrem.Checked);
   }
   else
   {
      Response.Write("Invalid user name or password");
   }
}

Observe thead put on the FormsAuthentication course is responsible for the process of authentication.

However, Visual Studio enables you to implement user creation, authentication, and authorization with oceanmless relayve without presently generally there writing any kind of code, through the Web Site Administration tool. This tool enables creating users and roles.

Apart from this particular, ASP.NET comes with readymade login manages set, which has manages performing all the jobs for you.

Implementing Forms-Based Security

To set up forms-based authentication, you need the following:

  • A database of users to supinterface the authentication process
  • A website thead put on uses the database
  • User accounts
  • Roles
  • Rererigorousedion of users and group workionivilinks
  • A default page, to display the login status of the users and other information.
  • A login page, to enable users to log in, retrieve password, or change password

To generate users, conaspectr the following steps:

Step (1) : Choose Website -> ASP.NET Configuration to open up the Web Application Administration Tool.

Step (2) : Click on the Security tab.

Security tab

Step (3) : Select the authentication type to 'Forms based authentication' simply by selecting the 'From the Internet' radio stations stations button.

Authentication Type

Step (4) : Click on 'Create Users' link to generate a few users. If you already had generated roles, you could assign roles to the user, proper at this particular stage.

Create Users link

Step (5) : Create a web site and add the following pages:

  • Welcome.aspx
  • Login.aspx
  • CreateAccount.aspx
  • PasswordRecovery.aspx
  • ChangePassword.aspx

Step (6) : Place a LoginStatus manage on the Welcome.aspx from the login section of the toolcontainer. It has 2 templates: LoggedIn and LoggedOut.

In LoggedOut template, presently generally there is a login link and in the LoggedIn template, presently generally there is a logout presently generally there link on the manage. You can change the login and logout presently generally there text properlinks of the manage from the Properlinks window.

Login Status manage

Step (7) : Place a LoginView manage from the toolcontainer below the LoginStatus manage. Here, you can put texts and other manages (hyperlinks, buttons etc.), which are displayed based on whether the user is logged in or not.

This manage has 2 watch templates: Anonymous template and LoggedIn template. Select every watch and write a few text for the users to be displayed for every template. The text need to be placed on the area marked reddishdish.

Login View manage

Step (8) : The users for the application are generated simply by the generateer. You may want to enable a visitor to generate a user account. For this particular, add a link beneath the LoginView manage, which need to link to the CreateAccount.aspx page.

Step (9) : Place a CreateUserWizard manage on the generate account page. Set the ContinueDestinationPageUrl home of this particular manage to Welcome.aspx.

CreateUserWizard manage

Step (10) : Create the Login page. Place a Login manage on the page. The LoginStatus manage automatically links to the Login.aspx. To change this particular default, create the following changes in the web.config file.

For example, if you want to name your own own log in page as signup.aspx, add the following collections to the <authentication> section of the web.config:

<configuration>
   <system.web>
      <authentication mode="Forms">
         <forms loginUrl ="signup.aspx" defaultUrl = “Welcome.aspx” />
      </authentication>
   </system.web>
</configuration>

Step (11) : Users regularly forget passwords. The PasswordRecovery manage helps the user gain access to the account. Select the Login manage. Open it is smart tag and click 'Convert to Template'.

Customize the UI of the manage to place a hyperlink manage under the login button, which need to link to the PassWordRecovery.aspx.

PasswordRecovery manage

Step (12) : Place a PasswordRecovery manage on the password recovery page. This manage needs an email server to send the passwords to the users.

PasswordRecovery manage2

Step (13) : Create a link to the ChangePassword.aspx page in the LoggedIn template of the LoginView manage in Welcome.aspx.

ChangePassword manage

Step (14) : Place a ChangePassword manage on the change password page. This manage furthermore has 2 watchs.

ChangePassword manage2

Now operate the application and observe various security operations.

To generate roles, go back to the Web Application Administration Tools and click on the Security tab. Click on 'Create Roles' and generate a few roles for the application.

Web Application Administration

Click on the 'Manage Users' link and assign roles to the users.

Manage Users

IIS Authentication: SSL

The Secure Socket Layer or SSL is the protocol used to ensure a secure interinterconnection. With SSL enabintroduced, the bcollectionser enweeppts all data sent to the server and deweeppts all data coming from the server. At the same time, the server enweeppts and deweeppts all data to and from bcollectionser.

The URL for a secure interinterconnection starts with HTTPS instead of HTTP. A small lock is displayed simply by a bcollectionser uperform a secure interinterconnection. When a bcollectionser creates an preliminary attempt to communicate with a server over a secure interinterconnection uperform SSL, the server authenticates it iself simply by sending it is digital certificate.

To use the SSL, you need to buy a digital secure certificate from a trusted Certification Authority (CA) and install it in the web server. Following are a few of the trusted and reputed certification authorilinks:

  • www.verisign.com
  • www.geotrust.com
  • www.thawte.com

SSL is built into all major bcollectionsers and servers. To enable SSL, you need to install the digital certificate. The strength of various digital certificates varies depending upon the duration of the key generated during enweepption. More the duration, more secure is the certificate, hence the interinterconnection.

Strength Description
40 bit Supinterfaceed simply by many kind of bcollectionsers but easy to break.
56 bit Stronger than 40-bit.
128 bit Extremely difficult to break but all the bcollectionsers do not supinterface it.

ASP.NET – Data Caching

Whead put on is Caching?

Caching is a technique of storing regularly used data/information in memory, so thead put on, when the same data/information is needed next time, it can be immediately retrieved from the memory instead of being generated simply by the application.

Caching is extremely iminterfaceant for performance boosting in ASP.NET, as the pages and manages are dynamically generated here. It is especially iminterfaceant for data related transworkionions, as these are expensive in terms of response time.

Caching places regularly used data in fastly accessed media such as the random access memory of the computer. The ASP.NET operatetime includes a key-value chart of CLR objects calintroduced cache. This reaspects with the application and is available via the HttpContext and System.Web.UI.Page.

In a few respect, caching is similar to storing the state objects. However, the storing information in state objects is deterministic, i.e., you can count on the data being storeddishdish presently generally there, and caching of data is nondeterministic.

The data will not be available in the following cases:

  • If it is lifetime expires,
  • If the application relrelayves it is memory,
  • If caching does not conaspectr place for a few reason.

You can access items in the cache uperform an indexer and may manage the lifetime of objects in the cache and set up links between the cached objects and their physical sources.

Caching in ASP.Net

ASP.NET provides the following various types of caching:

  • Output Caching : Output cache stores a duplicate of the finally rendereddishdish HTML pages or part of pages sent to the claynt. When the next claynt requests for this particular page, instead of regenerating the page, a cached duplicate of the page is sent, thus saving time.

  • Data Caching : Data caching means caching data from a data source. As durationy as the cache is not expireddishdish, a request for the data will be fulfilintroduced from the cache. When the cache is expireddishdish, fresh data is obtained simply by the data source and the cache is refilintroduced.

  • Object Caching : Object caching is caching the objects on a page, such as data-bound manages. The cached data is storeddishdish in server memory.

  • Class Caching : Web pages or web services are compiintroduced into a page course in the assembly, when operate for the 1st time. Then the assembly is cached in the server. Next time when a request is made for the page or service, the cached assembly is referreddishdish to. When the source code is changed, the CLR recompiles the assembly.

  • Configuration Caching : Application wide configuration information is storeddishdish in a configuration file. Configuration caching stores the configuration information in the server memory.

In this particular tutorial, we will conaspectr out presently generally thereput caching, data caching, and object caching.

Output Caching

Rendering a page may involve a few complex processes such as, database access, rendering complex manages etc. Output caching enables simply bypasperform the round trips to server simply by caching data in memory. Even the whole page can be cached.

The OutputCache immediateive is responsible of out presently generally thereput caching. It enables out presently generally thereput caching and provides specific manage over it is behaviour.

Syntax for OutputCache immediateive:

<%@ OutputCache Duration="15" VaryByParam="None" %>

Put this particular immediateive under the page immediateive. This tells the environment to cache the page for 15 2nds. The following workionuallyt handler for page load would help in checcalifornia king thead put on the page was very cached.

protected void Page_Load(object sender, EventArgs e)
{
   Thread.Sleep(10000);  
   Response.Write("This page was generated and cache at:" +
   DateTime.Now.ToString());
}

The Thread.Sleep() method ceases the process thread for the specified time. In this particular example, the thread is ceaseped for 10 2nds, so when the page is loaded for 1st time, it conaspectrs 10 2nds. However, next time you refresh the page it does not conaspectr any kind of time, as the page is retrieved from the cache without presently generally there being loaded.

The OutputCache immediateive has the following attributes, which helps in manageling the behaviour of the out presently generally thereput cache:

Attribute Values Description
DiskCacheable true/false Specifies thead put on out presently generally thereput can be generated to a disk based cache.
NoStore true/false Specifies thead put on the "no store" cache manage header is sent or not.
CacheProfile String name Name of a cache profile as to be storeddishdish in web.config.
VaryByParam

None

*

Param- name

Semicolon delimited list of string specifies query string values in a GET request or variable in a POST request.
VaryByHeader

*

Header names

Semicolon delimited list of strings specifies headers thead put on may be submitted simply by a claynt.
VaryByCustom

Bcollectionser

Custom string

Tells ASP.NET to vary the out presently generally thereput cache simply by bcollectionser name and version or simply by a custom string.
Location

Any

Claynt

Downstream

Server

None

Any: page may be cached any kind ofwhere.

Claynt: cached content remains at bcollectionser.

Downstream: cached content storeddishdish in downstream and server both.

Server: cached content saved only on server.

None: disables caching.

Duration Number Number of 2nds the page or manage is cached.

Let us add a text container and a button to the previous example and add this particular workionuallyt handler for the button.

protected void btnmagic_Click(object sender, EventArgs e)
{
   Response.Write("<br><br>");
   Response.Write("<h2> Hello, " + this particular.txtname.Text + "</h2>");
}

Change the OutputCache immediateive:

<%@ OutputCache Duration="60" VaryByParam="txtname" %>

When the program is executed, ASP.NET caches the page on the basis of the name in the text container.

Data Caching

The main aspect of data caching is caching the data source manages. We have already speak abouted thead put on the data source manages represent data in a data source, like a database or an XML file. These manages derive from the abstrworkion course DataSourceControl and have the following inherited properlinks for implementing caching:

  • CacheDuration – It sets the number of 2nds for which the data source will cache data.

  • CacheExpirationPolicy – It degreats the cache behavior when the data in cache has expireddishdish.

  • CacheKeyDependency – It identifies a key for the manages thead put on auto-expires the content of it is cache when removed.

  • EnableCaching – It specifies whether or not to cache the data.

Example

To demonstrate data caching, generate a brand new website and add a brand new web form on it. Add a SqlDataSource manage with the database interinterconnection already used in the data access tutorials.

For this particular example, add a label to the page, which would show the response time for the page.

<asp:Label ID="lbltime" operateat="server"></asp:Label>

Apart from the label, the content page is same as in the data access tutorial. Add an workionuallyt handler for the page load workionuallyt:

protected void Page_Load(object sender, EventArgs e)
{
   lbltime.Text = String.Format("Page posted at: {0}", DateTime.Now.ToLongTimeString());
}

The designed page need to look as shown:

Data Caching

When you execute the page for the 1st time, absolutely absolutely nothing various happens, the label shows thead put on, every time you refresh the page, the page is reloaded and the time shown on the label changes.

Next, set the EnableCaching attribute of the data source manage to be 'true' and set the Cacheduration attribute to '60'. It will implement caching and the cache will expire every 60 2nds.

The timestamp changes with every refresh, but if you change the data in the table within these 60 2nds, it is not shown before the cache expires.

<asp:SqlDataSource ID="SqlDataSource1" operateat="server" 
   ConnectionString="<%$ ConnectionStrings:
   ASPDotNetStepByStepConnectionString %>" 
   ProviderName="<%$ ConnectionStrings:
   ASPDotNetStepByStepConnectionString.ProviderName %>" 
   SelectCommand="SELECT * FROM [DotNetReferences]"
   EnableCaching="true" CacheDuration = "60">         
</asp:SqlDataSource>

Object Caching

Object caching provides more flexibility than other cache techniques. You can use object caching to place any kind of object in the cache. The object can be of any kind of type – a data type, a web manage, a course, a dataset object, etc. The item is added to the cache simply simply by assigning a brand new key name, shown as follows Like:

Cache["key"] = item;

ASP.NET furthermore provides the Insert() method for inserting an object to the cache. This method has four overloaded versions. Let us see all of them:

Overload Description
Cache.Insert((key, value); Inserts an item into the cache with the key name and value with default priority and expiration.
Cache.Insert(key, value, dependencies); Inserts an item into the cache with key, value, default priority, expiration and a CacheDependency name thead put on links to other files or items so thead put on when these change the cache item remains no durationyer valid.
Cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration); This withindicates an expiration policy adurationy with the above issues.
Cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback); This adurationy with the parameters furthermore enables you to set a priority for the cache item and a delegate thead put on, stages to a method to be invoked when the item is removed.

Sliding expiration is used to remove an item from the cache when it is not used for the specified time span. The following code snippet stores an item with a sliding expiration of 10 minutes with no dependencies.

Cache.Insert("my_item", obj, null, DateTime.MaxValue, TimeSpan.FromMinutes(10));

Example

Create a page with simply a button and a label. Write the following code in the page load workionuallyt:

protected void Page_Load(object sender, EventArgs e)
{
   if (this particular.IsPostBack)
   {
      lblinfo.Text += "Page Posted Back.<br/>";
   }
   else
   {
      lblinfo.Text += "page Created.<br/>";
   }
   if (Cache["checkitem"] == null)
   {
      lblinfo.Text += "Creating check item.<br/>";
      DateTime checkItem = DateTime.Now;
      lblinfo.Text += "Storing check item in cache ";
      lblinfo.Text += "for 30 2nds.<br/>";
      Cache.Insert("checkitem", checkItem, null, 
      DateTime.Now.AddSeconds(30), TimeSpan.Zero);
   }
   else
   {
      lblinfo.Text += "Retrieving check item.<br/>";
      DateTime checkItem = (DateTime)Cache["checkitem"];
      lblinfo.Text += "Test item is: " + checkItem.ToString();
      lblinfo.Text += "<br/>";
   }
   lblinfo.Text += "<br/>";
}

When the page is loaded for the 1st time, it says:

Page Created.
Creating check item.
Storing check item in cache for 30 2nds.

If you click on the button again within 30 2nds, the page is posted back but the label manage gets it is information from the cache as shown:

Page Posted Back.
Retrieving check item.
Test item is: 14-07-2010 01:25:04

ASP.NET – Web Services

A web service is a web-based functionality accessed uperform the protocols of the web to be used simply by the web applications. There are 3 aspects of web service generatement:

  • Creating the web service
  • Creating a proxy
  • Consuming the web service

Creating a Web Service

A web service is a web application which is fundamentalally a course consisting of methods thead put on can be used simply by other applications. It furthermore follows a code-at the rear of architecture such as the ASP.NET web pages, although it does not have a user interface.

To understand the concept allow us generate a web service to provide stock price information. The claynts can query about presently generally there the name and price of a stock based on the stock symbol. To maintain this particular example easy, the values are hardcoded in a 2-dimensional array. This web service has 3 methods:

  • A default HelloWorld method
  • A GetName Method
  • A GetPrice Method

Take the following steps to generate the web service:

Step (1) : Select File -> New -> Web Site in Visual Studio, and then select ASP.NET Web Service.

Step (2) : A web service file calintroduced Service.asmx and it is code at the rear of file, Service.cs is generated in the App_Code immediateory of the project.

Step (3) : Change the names of the files to StockService.asmx and StockService.cs.

Step (4) : The .asmx file has simply a WebService immediateive on it:

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

Step (5) : Open the StockService.cs file, the code generated in it is the fundamental Hello World service. The default web service code at the rear of file looks like the following:

uperform System;
uperform System.Collections;
uperform System.ComponentModel;
uperform System.Data;
uperform System.Linq;
uperform System.Web;
uperform System.Web.Services;
uperform System.Web.Services.Protocols;
uperform System.Xml.Linq;
namespace StockService
{
   // <summary>
   // Summary description for Service1
   // <summary>
   [WebService(Namespace = "http://tempuri.org/")]
   [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
   [ToolcontainerItem(false)]
   // To enable this particular Web Service to be calintroduced from script, 
   // uperform ASP.NET AJAX, uncomment the following collection. 
   // [System.Web.Script.Services.ScriptService]
   public course Service1 : System.Web.Services.WebService
   {
      [WebMethod]
      public string HelloWorld()
      {
         return "Hello World";
      }
   }
}

Step (6) : Change the code at the rear of file to add the 2 dimensional array of strings for stock symbol, name and price and 2 web methods for getting the stock information.

uperform System;
uperform System.Linq;
uperform System.Web;
uperform System.Web.Services;
uperform System.Web.Services.Protocols;
uperform System.Xml.Linq;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To enable this particular Web Service to be calintroduced from script, 
// uperform ASP.NET AJAX, uncomment the following collection. 
// [System.Web.Script.Services.ScriptService]
public course StockService : System.Web.Services.WebService
{
   public StockService () {
      //Uncomment the following if uperform designed components 
      //InitializeComponent(); 
   }
   string[,] stocks =
   {
      {"RELIND", "Reliance Industries", "1060.15"},
      {"ICICI", "ICICI Bank", "911.55"},
      {"JSW", "JSW Steel", "1201.25"},
      {"WIPRO", "Wipro Limited", "1194.65"},
      {"SATYAM", "Satyam Computers", "91.10"}
   };

   [WebMethod]
   public string HelloWorld() {
      return "Hello World";
   }
   [WebMethod]
   public double GetPrice(string symbol)
   { 
      //it conaspectrs the symbol as parameter and returns price
      for (int i = 0; i < stocks.GetLength(0); i++)
      {
         if (String.Compare(symbol, stocks[i, 0], true) == 0)
         return Convert.ToDouble(stocks[i, 2]);
      }
      return 0;
   }
   [WebMethod]
   public string GetName(string symbol)
   {
      // It conaspectrs the symbol as parameter and 
      // returns name of the stock
      for (int i = 0; i < stocks.GetLength(0); i++)
      {
         if (String.Compare(symbol, stocks[i, 0], true) == 0)
         return stocks[i, 1];
      }
      return "Stock Not Found";
   }
}

Step (7) : Running the web service application gives a web service check page, which enables checcalifornia king the service methods.

Stock Service

Step (8) : Click on a method name, and check whether it operates properly.

Get Name

Step (9) : For checcalifornia king the GetName method, provide one of the stock symbols, which are hard coded, it returns the name of the stock

the name of the stock

Consuming the Web Service

For uperform the web service, generate a web site under the same solution. This can be done simply by proper cliccalifornia king on the Solution name in the Solution Explorer. The web page calling the web service need to have a label manage to display the returned results and 2 button manages one for post back and one more for calling the service.

The content file for the web application is as follows:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
   Inherit is="wsclaynt._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head operateat="server">
      <title>
         Untitintroduced Page
      </title>
   </head>
   <body>
      <form id="form1" operateat="server">
         <div>
            <h3>Uperform the Stock Service</h3>
            <br />
            <br />
            <asp:Label ID="lblmessage" operateat="server"></asp:Label>
            <br />
            <br />
            <asp:Button ID="btnpostback" operateat="server" onclick="Button1_Click" 
               Text="Post Back" style="width:132px" />
               
            <asp:Button ID="btnservice" operateat="server
               onclick="btnservice_Click"  Text="Get Stock" style="width:99px" />
         </div>
      </form>
   </body>
</html>

The code at the rear of file for the web application is as follows:

uperform System;
uperform System.Collections;
uperform System.Configuration;
uperform System.Data;
uperform System.Linq;
uperform System.Web;
uperform System.Web.Security;
uperform System.Web.UI;
uperform System.Web.UI.HtmlControls;
uperform System.Web.UI.WebControls;
uperform System.Web.UI.WebControls.WebParts;
uperform System.Xml.Linq;

//this particular is the proxy
uperform localhost;

namespace wsclaynt
{
   public partial course _Default : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
         if (!IsPostBack)
         {
            lblmessage.Text = "First Loading Time: " +  DateTime.Now.ToLongTimeString
         }
         else
         {
            lblmessage.Text = "PostBack at: " + DateTime.Now.ToLongTimeString();
         }
      }
      protected void btnservice_Click(object sender, EventArgs e)
      {
         StockService proxy = brand new StockService();
         lblmessage.Text = String.Format("Current SATYAM Price:{0}",
         proxy.GetPrice("SATYAM").ToString());
      }
   }
}

Creating the Proxy

A proxy is a stand-in for the web service codes. Before uperform the web service, a proxy must be generated. The proxy is registereddishdish with the claynt application. Then the claynt application creates the calls to the web service as it were uperform a local method.

The proxy conaspectrs the calls, wraps it in proper format and sends it as a SOAP request to the server. SOAP stands for Simple Object Access Protocol. This protocol is used for exchanging web service data.

When the server returns the SOAP package to the claynt, the proxy decodes everything and presents it to the claynt application.

Before calling the web service uperform the btnservice_Click, a web reference need to be added to the application. This generates a proxy course transparently, which is used simply by the btnservice_Click workionuallyt.

protected void btnservice_Click(object sender, EventArgs e)
{
   StockService proxy = brand new StockService();
   lblmessage.Text = String.Format("Current SATYAM Price: {0}", 
   proxy.GetPrice("SATYAM").ToString());
}

Take the following steps for creating the proxy:

Step (1) : Right click on the web application encheck in the Solution Explorer and click on 'Add Web Reference'.

Add Web Reference

Step (2) : Select 'Web Services in this particular solution'. It returns the StockService reference.

Select Web Services

Step (3) : Cliccalifornia king on the service open ups the check web page. By default the proxy generated is calintroduced 'localhost', you can rename it. Click on 'Add Reference' to add the proxy to the claynt application.

Stock Service 2

Include the proxy in the code at the rear of file simply by adding:

 uperform localhost;

ASP.NET – Multi Threading

A thread is degreatd as the execution route of a program. Each thread degreats a unique flow of manage. If your own own application involves complicated and time consuming operations such as database access or a few intense I/O operations, then it is regularly helpful to set various execution routes or threads, with every thread performing a particular job.

Threads are lightweight processes. One common example of use of thread is implementation of concurrent programming simply by modern operating systems. Use of threads saves wastage of CPU cycle and incrrelayves efficiency of an application.

So far we compiintroduced programs where a performle thread operates as a performle process which is the operatening instance of the application. However, this particular way the application can perform one job at a time. To create it execute multiple tasks at a time, it can be divided into smaller threads.

In .Net, the threading is handintroduced through the 'System.Threading' namespace. Creating a variable of the System.Threading.Thread type enables you to generate a brand new thread to start functioning with. It enables you to generate and access individual threads in a program.

Creating Thread

A thread is generated simply by creating a Thread object, giving it is constructor a ThreadStart reference.

ThreadStart childthreat = brand new ThreadStart(childthreadcall);

Thread Life Cycle

The life cycle of a thread starts when an object of the System.Threading.Thread course is generated and ends when the thread is terminated or compallowes execution.

Following are the various states in the life cycle of a thread:

  • The Unstarted State : It is the situation when the instance of the thread is generated but the Start method is not calintroduced.

  • The Ready State : It is the situation when the thread is ready to execute and wait arounding CPU cycle.

  • The Not Runnable State : a thread is not operatenable, when:

    • Sleep method has been calintroduced
    • Wait method has been calintroduced
    • Blocked simply by I/O operations
  • The Dead State : It is the situation when the thread has compallowed execution or has been aborted.

Thread Priority

The Priority home of the Thread course specifies the priority of one thread with respect to other. The .Net operatetime selects the ready thread with the highest priority.

The priorilinks can be categorized as:

  • Above normal
  • Below normal
  • Highest
  • Lowest
  • Normal

Once a thread is generated, it is priority is set uperform the Priority home of the thread course.

NewThread.Priority = ThreadPriority.Highest;

Thread Properlinks & Methods

The Thread course has the following iminterfaceant properlinks:

Property Description
CurrentContext Gets the current context in which the thread is executing.
CurrentCulture Gets or sets the culture for the current thread.
CurrentPrinciple Gets or sets the thread's current principal for role-based security.
CurrentThread Gets the currently operatening thread.
CurrentUICulture Gets or sets the current culture used simply by the Resource Manager to look up culture-specific resources at operate time.
ExecutionContext Gets an ExecutionContext object thead put on contains information about presently generally there the various contexts of the current thread.
IsAreaspect Gets a value indicating the execution status of the current thread.
IsBackground Gets or sets a value indicating whether or not a thread is a background thread.
IsThreadPoolThread Gets a value indicating whether or not a thread bedurationys to the managed thread pool.
ManagedThreadId Gets a unique identifier for the current managed thread.
Name Gets or sets the name of the thread.
Priority Gets or sets a value indicating the scheduling priority of a thread.
ThreadState Gets a value containing the states of the current thread.

The Thread course has the following iminterfaceant methods:

Methods Description
Abort Raises a ThreadAbortException in the thread on which it is withinvoked, to start the process of terminating the thread. Calling this particular method usually terminates the thread.
AllocateDataSlot Allocates an unnamed data slot on all the threads. For better performance, use fields thead put on are marked with the ThreadStaticAttribute attribute instead.
AllocateNamedDataSlot Allocates a named data slot on all threads. For better performance, use fields thead put on are marked with the ThreadStaticAttribute attribute instead.
BeginCriticalRegion Notifies a host thead put on execution is about presently generally there to enter a area of code in which the effects of a thread abort or unhandintroduced exception may endanger other tasks in the application domain.
BeginThreadAffinity Notifies a host thead put on managed code is about presently generally there to execute instructions thead put on depend on the identity of the current physical operating system thread.
EndCriticalRegion Notifies a host thead put on execution is about presently generally there to enter a area of code in which the effects of a thread abort or unhandintroduced exception are limited to the current task.
EndThreadAffinity Notifies a host thead put on managed code has compalloweed executing instructions thead put on depend on the identity of the current physical operating system thread.
FreeNamedDataSlot Eliminates the association between a name and a slot, for all threads in the process. For better performance, use fields thead put on are marked with the ThreadStaticAttribute attribute instead.
GetData Retrieves the value from the specified slot on the current thread, within the current thread's current domain. For better performance, use fields thead put on are marked with the ThreadStaticAttribute attribute instead.
GetDomain Returns the current domain in which the current thread is operatening.
GetDomainID Returns a unique application domain identifier.
GetNamedDataSlot Looks up a named data slot. For better performance, use fields thead put on are marked with the ThreadStaticAttribute attribute instead.
Interrupt Interrupts a thread thead put on is within the WaitSleepJoin thread state.
Join Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping. This method has various overloaded forms.
MemoryBarrier Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way thead put on memory accesses prior to the call to MemoryBarrier execute after memory accesses thead put on follow the call to MemoryBarrier.
ResetAbort Cancels an Abort requested for the current thread.
SetData Sets the data in the specified slot on the currently operatening thread, for thead put on thread's current domain. For better performance, use fields marked with the ThreadStaticAttribute attribute instead.
Start Starts a thread.
Sleep Makes the thread pause for a period of time.
SpinWait Causes a thread to wait around the number of times degreatd simply by the iterations parameter.
VolatileRead() Reads the value of a field. The value is the lacheck generated simply by any kind of processor in a computer, regardless of the number of processors or the state of processor cache. This method has various overloaded forms.
VolatileWrite() Writes a value to a field immediately, so thead put on the value is noticeable to all processors in the computer. This method has various overloaded forms.
Yield Causes the calling thread to yield execution to one more thread thead put on is ready to operate on the current processor. The operating system selects the thread to yield to.

Example

The following example illustrates the uses of the Thread course. The page has a label manage for displaying messages from the child thread. The messages from the main program are immediately displayed uperform the Response.Write() method. Hence they appear on the top of the page.

The source file is as follows:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
   Inherit is="threaddemo._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head operateat="server">
      <title>
         Untitintroduced Page
      </title>
   </head>
   <body>
      <form id="form1" operateat="server">
         <div>
            <h3>Thread Example</h3>
         </div>
         <asp:Label ID="lblmessage" operateat="server" Text="Label">
         </asp:Label>
      </form>
   </body>
</html>

The code at the rear of file is as follows:

uperform System;
uperform System.Collections;
uperform System.Configuration;
uperform System.Data;
uperform System.Linq;
uperform System.Web;
uperform System.Web.Security;
uperform System.Web.UI;
uperform System.Web.UI.HtmlControls;
uperform System.Web.UI.WebControls;
uperform System.Web.UI.WebControls.WebParts;
uperform System.Xml.Linq;
uperform System.Threading;

namespace threaddemo
{
   public partial course _Default : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
         ThreadStart childthreat = brand new ThreadStart(childthreadcall);
         Response.Write("Child Thread Started <br/>");
         Thread child = brand new Thread(childthreat);
         child.Start();
         Response.Write("Main sleeping  for 2 2nds.......<br/>");
         Thread.Sleep(2000);
         Response.Write("<br/>Main aborting child thread<br/>");
         child.Abort();
      }
      public void childthreadcall()
      {
         check{
            lblmessage.Text = "<br />Child thread started <br/>";
            lblmessage.Text += "Child Thread: Coiunting to 10";
            for( int i =0; i<10; i++)
            {
               Thread.Sleep(500);
               lblmessage.Text += "<br/> in Child thread </br>";
            }
            lblmessage.Text += "<br/> child thread compalloweed";
         }
         capture(ThreadAbortException e)
         {
            lblmessage.Text += "<br /> child thread - exception";
         }
         finally{
            lblmessage.Text += "<br /> child thread - unable to capture the  exception";
         }
      }
   }
}

Observe the following

  • When the page is loaded, a brand new thread is started with the reference of the method childthreadcall(). The main thread workionivilinks are displayed immediately on the web page.

  • The 2nd thread operates and sends messages to the label manage.

  • The main thread sleeps for 2000 ms, during which the child thread executes.

  • The child thread operates till it is aborted simply by the main thread. It raises the ThreadAbortException and is terminated.

  • Control returns to the main thread.

When executed the program sends the following messages:

ASP.NET Thread

ASP.NET – Configuration

The behavior of an ASP.NET application is affected simply by various settings in the configuration files:

  • machine.config
  • web.config

The machine.config file contains default and the machine-specific value for all supinterfaceed settings. The machine settings are manageintroduced simply by the system administrator and applications are generally not given access to this particular file.

An application however, can override the default values simply by creating web.config files in it is mains folder. The web.config file is a subset of the machine.config file.

If the application contains child immediateories, it can degreat a web.config file for every folder. Scope of every configuration file is figure outd in a hierarchical top-down manner.

Any web.config file can locally extend, rererigoroused, or override any kind of settings degreatd on the upper level.

Visual Studio generates a default web.config file for every project. An application can execute without presently generally there a web.config file, however, you cannot debug an application without presently generally there a web.config file.

The following figure shows the Solution Explorer for the sample example used in the web services tutorial:

Solution Explorer-2

In this particular application, presently generally there are 2 web.config files for 2 projects i.e., the web service and the web site calling the web service.

The web.config file has the configuration element as the main node. Information inaspect this particular element is grouped into 2 main areas: the configuration section-handler declaration area, and the configuration section settings area.

The following code snippet shows the fundamental syntax of a configuration file:

<configuration>
   <!-- Configuration section-handler declaration area. -->
      <configSections>
         <section name="section1" type="section1Handler" />
         <section name="section2" type="section2Handler" />
      </configSections>
   <!-- Configuration section settings area. -->
   <section1>
      <s1Setting1 attribute1="attr1" />
   </section1>
   <section2>
      <s2Setting1 attribute1="attr1" />
   </section2>
   <system.web>
      <authentication mode="Windows" />
   </system.web>
</configuration>

Configuration Section Handler declarations

The configuration section handlers are contained within the <configSections> tags. Each configuration handler specifies name of a configuration section, contained within the file, which provides a few configuration data. It has the following fundamental syntax:

<configSections>
   <section />
   <sectionGroup />
   <remove />
   <clear/>
</configSections>

It has the following elements:

  • Clear – It removes all references to inherited sections and section groups.

  • Remove – It removes a reference to an inherited section and section group.

  • Section – It degreats an association between a configuration section handler and a configuration element.

  • Section group – It degreats an association between a configuration section handler and a configuration section.

Application Settings

The application settings enable storing application-wide name-value pairs for read-only access. For example, you can degreat a custom application setting as:

<configuration>
   <appSettings>
      <add key="Application Name" value="MyApplication" /> 
   </appSettings>
</configuration>

For example, you can furthermore store the name of a book and it is ISBN number:

<configuration>
   <appSettings>
      <add key="appISBN" value="0-273-68726-3" />
      <add key="appBook" value="Corporate Finance" />
   </appSettings>
</configuration>

Connection Strings

The interinterconnection strings show which database interinterconnection strings are available to the website. For example:

<interinterconnectionStrings>
   <add name="ASPDotNetStepByStepConnectionString" 
      interinterconnectionString="Provider=Microsoft.Jet.OLEDB.4.0;
      Data Source=E:\projectsdatacaching /
      datacachingApp_DataASPDotNetStepByStep.mdb"
      providerName="System.Data.OleDb" />
   <add name="booksConnectionString" 
      interinterconnectionString="Provider=Microsoft.Jet.OLEDB.4.0;
      Data Source=C: databindingApp_Databooks.mdb"
      providerName="System.Data.OleDb" />
</interinterconnectionStrings>

System.Web Element

The system.web element specifies the main element for the ASP.NET configuration section and contains configuration elements thead put on configure ASP.NET Web applications and manage how the applications behave.

It holds many kind of of the configuration elements needed to be adsimplyed in common applications. The fundamental syntax for the element is as given:

<system.web> 
   <anonymousIdentification> 
   <authentication> 
   <authorization> 
   <bcollectionserCaps> 
   <caching> 
   <clayntTarget> 
   <compilation> 
   <customErrors> 
   <deployment> 
   <deviceFilters> 
   <globalization> 
   <healthMonitoring> 
   <hostingEnvironment> 
   <httpCookies> 
   <httpHandlers> 
   <httpModules> 
   <httpRuntime> 
   <identity> 
   <machineKey> 
   <membership> 
   <mobileControls> 
   <pages> 
   <processModel> 
   <profile> 
   <roleManager> 
   <securityPolicy> 
   <sessionPageState> 
   <sessionState> 
   <siteMap> 
   <trace> 
   <trust> 
   <urlMappings> 
   <webControls> 
   <webParts> 
   <webServices> 
   <xhtmlConformance> 
</system.web>

The following table provides brief description of a few of common sub elements of the system.web element:

AnonymousIdentification

This is requireddishdish to identify users who are not authenticated when authorization is requireddishdish.

Authentication

It configures the authentication supinterface. The fundamental syntax is as given:

<authentication mode="[Windows|Forms|Passinterface|None]"> 
   <forms>...</forms>
   <passinterface/>
</authentication>

Authorization

It configures the authorization supinterface. The fundamental syntax is as given:

<authorization> 
   <enable .../>
   <deny .../>
</authorization>

Caching

It Configures the cache settings. The fundamental syntax is as given:

<caching>
   <cache>...</cache>
   <out presently generally thereputCache>...</out presently generally thereputCache>
   <out presently generally thereputCacheSettings>...</out presently generally thereputCacheSettings>
   <sqlCacheDependency>...</sqlCacheDependency>
</caching>

CustomErrors

It degreats custom error messages. The fundamental syntax is as given:

<customErrors defaultReimmediate="url" mode="On|Off|RemoteOnly">
   <error. . ./>
</customErrors>

Deployment

It degreats configuration settings used for deployment. The fundamental syntax is as follows:

<deployment retail="true|false" />

HostingEnvironment

It degreats configuration settings for hosting environment. The fundamental syntax is as follows:

<hostingEnvironment idleTimeout presently generally there="HH:MM:SS" shadowCopyBinAssemblays="true|false" 
   shutdownTimeout presently generally there="number" urlMetadataSlidingExpiration="HH:MM:SS" />

Identity

It configures the identity of the application. The fundamental syntax is as given:

<identity impersonate="true|false" userName="domainusername"
   password="<secure password>"/>

MachineKey

It configures keys to use for enweepption and deweepption of Forms authentication cookie data.

It furthermore enables configuring a validation key thead put on performs message authentication checks on watch-state data and forms authentication tickets. The fundamental syntax is:

<machineKey validationKey="AutoGenerate,IsolateApps" [String]
   deweepptionKey="AutoGenerate,IsolateApps" [String]
   validation="HMACSHA256" [SHA1 | MD5 | 3DES | AES | HMACSHA256 | 
   HMACSHA384 | HMACSHA512 | alg:algorithm_name]
   deweepption="Auto" [Auto | DES | 3DES | AES | alg:algorithm_name]
/>

Membership

This configures parameters of managing and authenticating user accounts. The fundamental syntax is:

<membership defaultProvider="provider name"
   userIsOncollectionTimeWindow="number of minutes" hashAlgorithmType="SHA1">
   <providers>...</providers>
</membership>

Pages

It provides page-specific configurations. The fundamental syntax is:

<pages asyncTimeout presently generally there="number" autoEventWireup="[True|False]"
   buffer="[True|False]" clayntIDMode="[AutoID|Preddishdishictable|Static]"
   compilationMode="[Always|Auto|Never]" 
   manageRenderingCompatibilityVersion="[3.5|4.0]"
   enableEventValidation="[True|False]"
   enableSessionState="[True|False|ReadOnly]"
   enableViewState="[True|False]"
   enableViewStateMac="[True|False]"
   maintainScrollPositionOnPostBack="[True|False]" 
   masterPageFile="file route" 
   maxPageStateFieldLength="number" 
   pageBaseType="typename, assembly"
   pageParserFilterType="string" 
   smartNavigation="[True|False]"
   styleSheetTheme="string"
   all of theme="string"
   userControlBaseType="typename"
   validateRequest="[True|False]"
   watchStateEnweepptionMode="[Always|Auto|Never]" >
   <manages>...</manages>
   <namespaces>...</namespaces>
   <tagMapping>...</tagMapping>
   <ignoreDeviceFilters>...</ignoreDeviceFilters>
</pages>

Profile

It configures user profile parameters. The fundamental syntax is:

<profile enabintroduced="true|false" inherit is="compallowey qualified type reference"
   automaticSaveEnabintroduced="true|false" defaultProvider="provider name">
   <properlinks>...</properlinks>
   <providers>...</providers>
</profile>

RoleManager

It configures settings for user roles. The fundamental syntax is:

<roleManager cacheRolesInCookie="true|false" cookieName="name"
   cookiePath="/" cookieProtection="All|Enweepption|Validation|None"
   cookieRequireSSL="true|false " cookieSlidingExpiration="true|false "
   cookieTimeout presently generally there="number of minutes" generatePersistentCookie="true|false"
   defaultProvider="provider name" domain="cookie domain"> 
   enabintroduced="true|false"
   maxCachedResults="maximum number of role names cached"
   <providers>...</providers>
</roleManager>

SecurityPolicy

It configures the security policy. The fundamental syntax is:

<securityPolicy>
   <trustLevel />
</securityPolicy>

UrlMappings

It degreats chartpings to hide the authentic URL and provide a more user friendly URL. The fundamental syntax is:

<urlMappings enabintroduced="true|false">
   <add.../>
   <clear />
   <remove.../>
</urlMappings>

WebControls

It provides the name of shareddishdish location for claynt scripts. The fundamental syntax is:

<webControls clayntScriptsLocation="String" />

WebServices

This configures the web services.

ASP.NET – Deployment

There are 2 categories of ASP.NET deployment:

  • Local deployment : In this particular case, the entire application is contained within a virtual immediateory and all the contents and assemblays are contained within it and available to the application.

  • Global deployment : In this particular case, assemblays are available to every application operatening on the server.

There are various techniques used for deployment, however, we will speak about the following many kind of common and easiest ways of deployment:

  • XCOPY deployment
  • Copying a Website
  • Creating a set up project

XCOPY Deployment

XCOPY deployment means macalifornia king recursive copies of all the files to the target folder on the target machine. You can use any kind of of the commonly used techniques:

  • FTP transfer
  • Uperform Server management tools thead put on provide replication on a remote site
  • MSI installer application

XCOPY deployment simply copies the application file to the itemion server and sets a virtual immediateory presently generally there. You need to set a virtual immediateory uperform the Internet Information Manager Microsoft Management Console (MMC snap-in).

Copying a Website

The Copy Web Site option is available in Visual Studio. It is available from the Website -> Copy Web Site menu option. This menu item enables duplicateing the current web site to one more local or remote location. It is a sort of integrated FTP tool.

Uperform this particular option, you connect to the target destination, select the desireddishdish duplicate mode:

  • Overwrite
  • Source to Target Files
  • Sync UP Source And Target Projects

Then proceed with duplicateing the files physically. Unlike the XCOPY deployment, this particular process of deployment is done from Visual Studio environment. However, presently generally there are following issues with both the above deployment methods:

  • You pass on your own own source code.
  • There is no pre-compilation and related error checcalifornia king for the files.
  • The preliminary page load will be slower.

Creating a Setup Project

In this particular method, you use Windows Installer and package your own own web applications so it is ready to deploy on the itemion server. Visual Studio enables you to construct deployment packages. Let us check this particular on one of our existing project, say the data binding project.

Open the project and conaspectr the following steps:

Step (1) : Select File -> Add -> New Project with the website main immediateory highlighted in the Solution Explorer.

Step (2) : Select Setup and Deployment, under Other Project Types. Select Setup Wizard.

Select Setup Wizard

Step (3) : Chooperform the default location ensures thead put on the set up project will be located in it is own folder under the main immediateory of the site. Click on okay to get the 1st splash screen of the wizard.

splash screen Wizard

Step (4) : Choose a project type. Select 'Create a setup for a web application'.

splash screen Wizard2

Step (5) : Next, the third screen asks to choose project out presently generally thereputs from all the projects in the solution. Check the check container next to 'Content Files from…'

splash screen Wizard3

Step (6) : The fourth screen enables including other files like ReadMe. However, in our case presently generally there is no such file. Click on compallowe.

splash screen Wizard4

Step (7) : The final screen displays a summary of settings for the set up project.

splash screen Wizard5

Step (8) : The Set up project is added to the Solution Explorer and the main design window shows a file system editor.

splash screen Wizard6

Step (9) : Next step is to construct the setup project. Right click on the project name in the Solution Explorer and select Build.

splash screen Wizard7

Step (10) : When construct is compallowed, you get the following message in the Output window:

splash screen Wizard8

Two files are generated simply by the construct process:

  • Setup.exe
  • Setup-databinding.msi

You need to duplicate these files to the server. Double-click the setup file to install the content of the .msi file on the local machine.

SHARE
Previous articleXStream
Next articleMS SQL Server

NO COMMENTS

LEAVE A REPLY