Building Web Forms

Displaying data from a database in an HTML table is usually performed using the web form DataGrid control. In design view, after adding a new web form to a given project, choose the DataGrid from the toolbox and paste it onto the web form. (The web form must be displayed in the design view. If HTML code is visible, the HTML view is being displayed. Figure 14-3 shows a web form in design view.) After the DataGrid is pasted on the web form, the name may be edited in the Properties window for the newly created DataGrid control. In Figure 14-5, the name of the DataGrid was set to dgChair.

click to expand
Figure 14-5: Properties window for dgChair DataGrid control

Running the web form at this point in Visual Studio .NET will cause the web form to be compiled into an assembly on the development server. In this example, the development server that hosts the web form is named amd1700. To compile the web form and run it in debug mode in Visual Studio .NET, press the F5 key. Visual Studio .NET will compile the web form and enter into a debugging mode, just as the previous editions of Visual Studio ran a Visual Basic or Visual C++ executable.

After the compilation is complete on the server, the web browser on your workstation will spawn and open the web form. After the development server grinds away at the effort to deliver the web page for a short period of time, the browser will display a blank page. If you close the browser, the debug session will end and Visual Studio .NET returns to the edit mode. In this specific exercise, the browser displays a blank page because the DataGrid dgChair is not loaded with any data. In order for the DataGrid to display any data, you will have to write code in the Codebehind file that obtains a DataSet and places the data from the DataSet into the DataGrid control, dgChair.

Editing Code for a Data-Oriented Web Form

To edit the Codebehind file for the web form hosting the DataGrid dgChair, right-click the web form file in the Solution Explorer or right-click the file itself in design view, and select View Code. By default, Visual Studio .NET does not display all files in the Solution Explorer that are part of the solution. Select the Show All Files icon at the top of the Solution Explorer to display all the files in the Solution Explorer so that the Codebehind file may be chosen directly.

The Codebehind file will be displayed with using directives for the classes that are required to make the web form function, the namespace, and the class framework. The namespace has the same name as the project. The class name is the name of the web form. Listing 14-9 shows the source code of the Codebehind file for the web form showGrid. The web form showGrid was created to demonstrate the use of the DataGrid control and as such, the Web Forms Designer placed a protected member in the class showGrid to represent the DataGrid that was pasted on the web form and named dgChair. The using System.Data.OleDb reference was added to provide an easy means of referring to ADO.NET classes.

Listing 14-9: Source Code for showGrid.aspx.cs after DataGrid Added in Design View

start example
 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.OleDb; //for the OleDbclasses using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace SimpleWF {   /// <summary>   /// Summary description for showGrid.   /// </summary>   public class showGrid : System.Web.UI.Page   {    protected System.Web.UI.WebControls.DataGrid dgChair;    private void Page_Load(object sender, System.EventArgs e)    {    }    #region Web Form Designer generated code    override protected void OnInit(EventArgs e)    {     //     // CODEGEN: This call is required by the      // ASP.NET Web Form Designer.     //     InitializeComponent();     base.OnInit(e);    }        /// <summary>    /// Required method for Designer support - do not modify    /// the contents of this method with the code editor.    /// </summary>    private void InitializeComponent()    {      this.Load += new System.EventHandler             (this.Page_Load);    }    #endregion   } } 
end example

If the desired result is to fill the DataGrid dgChair with data that is hosted in a database table, an ADO.NET DataSet must be obtained that is filled with data from a database. The DataSet may be used to populate the DataGrid dgChair when the web page is requested from the web server. When the page is loaded from the web server, the Load event of the Page object is triggered. The class showGrid inherits from System.Web.UI.Page, as evidenced by the class declaration in Listing 14-9, so the class showGrid inherits the Load event from System.Web.UI.Page. When Load is executed, it can execute code that will obtain a DataSet and fill the DataGrid. Listing 14-10 shows a subroutine named LoadGrid that will fill a DataGrid with a DataSet.

Listing 14-10: Source Code for Subroutine LoadGrid

start example
 private void LoadGrid(DataGrid dg) {   //set the connection credentials   string DataSetName = "myChairs";   string ConnectionString =      "Provider=Microsoft.Jet.OLEDB.4.0;" +           "Data Source=C:\\aspData\\employees.mdb;";    //make the DB connection   OleDbConnection myConn = new    OleDbConnection(ConnectionString);   //make a data set to hold chairs   DataSet myDataSet = new DataSet(DataSetName);   //make a data adaptor   OleDbDataAdapter myAdapt = new    OleDbDataAdapter("Select * From tblChair", myConn);   //fill the dataset   myAdapt.Fill(myDataSet);   //get a view in the dataset   DataView myDataView = new DataView(myDataSet.Tables[0]);   //show the data view in the Grid   dg.DataSource = myDataView;   dg.DataBind(); }
end example

LoadGrid is a member function of class showGrid. The function is called by placing the following call in the Page_Load event function for showGrid.aspx:

LoadGrid(dgChair);

ASP.NET Security

When the page showGrid.aspx is loaded, the Load event is captured and the LoadGrid function is called. When LoadGrid is called, the database connection data is set to a string variable and the ADO Connection object is instantiated using the connection string.

Note 

It should be pointed out that coding the literal connection string arguments in the code, as demonstrated in Listing 14-10, is an extremely bad practice. This technique was used to explicitly show the connection credentials that were used and how they applied to the Connection object. A better method for obtaining the database connection credentials is to place the database connection string in the web.config file. See Chapter 15 for more information on obtaining initialization data from the web.config file.

In Listing 14-10, the data source being utilized is Microsoft Access 2000. The host server file permissions for the Access .mdb data file must be configured to allow the ASP.NET web form to read and write the Access database file. If an enterprise database like SQL Server or Oracle were utilized, integrated security could be used to send credentials to the database server when the ASP.NET web form queries the database. The integrated security=sspi argument in the database connection string specifies the use of integrated security so the Windows .NET Server credentials under which the web form is running are presented to the data source. The Windows user account that an ASP.NET application runs under varies based on the following criteria:

  • Authentication established for your ASP.NET application Anonymous or non-anonymous

  • IIS Isolation mode being used IIS 5.0 isolation mode or worker process isolation mode

Depending on the authentication you establish for your application in IIS, the possible Windows user account being used by ASP.NET is as follows:

  • IIS guest Windows user account for anonymous access IUSER_<machine name>

  • Application pool identity Windows user account established in the application pool identity. Default accounts include: Network Service, Local Service, and Local System.

  • Windows user account of the authenticated user consuming the application Credentials presented by the end user during authentication to the ASP.NET server application.

If you set up IIS to allow anonymous access to the site, and the default application isolation mode is set for the server (which is worker process isolation mode), ASP.NET will use the identity established in the application pool being used for the web application. If you were using IIS 5.0 isolation mode for backwards compatibility, the IIS guest user account will be used as an identity for your application. If your application were set to use one of the authentication modes available in IIS so that the end user presents credentials, IIS by default will use the credentials as an identity. The default identities used by an IIS application are summarized in Table 14-1.

Table 14-1: Default Identities for an ASP.NET Application

Authentication

Application Isolation Mode

Windows User Account Used by ASP.NET

Anonymous

IIS 5.0 isolation

IUSER_<machine name>

Anonymous

Worker process isolation

Application pool identity for web application

Non-anonymous

IIS 5.0 isolation

Credentials presented by the user during authentication

Non-anonymous

Worker process isolation

Credentials presented by the user during authentication

Your application can use identities other than the default identities IIS will use. For example, you could use forms authentication to authorize the end user access to the application and still use a special user account for all queries to a database.

In the case of the web form showGrid.aspx, worker process isolation mode will be assumed since that is the default mode for IIS 6. Anonymous access will be allowed so the credentials of the application pool’s Windows user account will be the credentials used to access the data source. For the Microsoft Access database file, the host server file permissions must be set to allow the Windows user account to read, write, and modify the .mdb file. In the case of the enterprise database, the Windows user account must be provided the appropriate access to the database within the database server.

Note 

Don’t forget that the web.config file contains an element named authentication. The default mode for authentication is Windows. Since many programmers use a Windows user account that belongs to the administrators group, it is possible to develop a false sense of confidence in the ASP.NET web form functioning because the programmer’s user account will have the rights to do most anything to the development environment. When the application is migrated to a staging or production server that has restricted access, the web form may no longer work.

ADO.NET Overview

Since ADO.NET will be used to fill the DataGrid dgChair with data from the database table, a namespace must be added to the file showGrid.aspx for the data classes required to access the data source. The web forms by default include the namespace System.Data that is the core namespace of ADO.NET. Other namespaces subordinate to System.Data support a given data source type. The subordinate namespaces native to System.Data are as follows:

  • System.Data.Common

  • System.Data.OleDb

  • System.Data.SqlClient

  • System.Data.SqlTypes

The SqlClient provides an interface to a managed provider of SQL Server. This namespace provides the programmer with the most efficient means of communicating with SQL Server 2000. The namespace System.Data.OleDb supports an interface that is similar to legacy ADO and is not as efficient to use as the SqlClient namespace when communicating with SQL Server 2000. System.Data.OleDb is a good choice to use on data sources other than SQL Server 2000 that have an OLE-DB Provider. The namespaces System.Data.Common and System.Data.SqlTypes provide supporting interfaces for SQL Server and the common interfaces between SQL Server and OLE-DB classes.

ADO.NET ships as a single assembly named System.Data.dll. If support of an ODBC data source is necessary, Microsoft offers another assembly that can be downloaded and will provide a namespace for ODBC classes.

Since the data source used in the examples in this chapter is Microsoft Access 2000, the OleDb namespace will be used. If SQL Server 2000 was being used, SqlClient namespace would be used since it is the most efficient way to communicate with SQL Server 2000. The following line of code must be added at the top of the file showGrid.aspx along with the other namespace directives:

using System.Data.OleDb; //for the OleDb classes

Using ADO.NET Classes to Fill a Web Form Data Grid Control

After the connection is created, an ADO.NET Dataset instance named myDataSet is requested for the table tblChairs in the database. The DataSet is assigned the name myChairs when it is instantiated. The ADO.NET Adaptor object named myAdapt is instantiated for the purpose of filling the DataSet instance myDataSet. After myDataSet has been filled, an ADO.NET DataView object named myDataView is instantiated using myDataSet’s first table. Finally, the argument for the DataGrid, named dg, which was passed into the subroutine, has the data source property set to the DataView instance myDataView and the DataBind method of dg is called to fill the DataGrid instance dg with the data from the contents of table tblChairs.

The use of the DataView class is not required if the entire DataSet is to be displayed. In Listing 14-10, the entire DataSet that is created is displayed in the DataGrid dg. Since the entire DataSet is displayed in the grid, it would have been possible to skip the following line:

  DataView myDataView = new DataView(myDataSet.Tables[0]);

The DataSource property of the DataGrid dg could have been set to the Tables[0] property of the DataSet myDataSet. The line assigning the dg.DataSource to myDataView could be changed to the following:

dg.DataSource = myDataSet.Tables[0]

When you press F5, the page showGrid.aspx should compile and the browser instance will open, displaying the results of the data in table myChairs, as shown in Figure 14-6.

click to expand
Figure 14-6: Results of showGrid.aspx shown hosting DataGrid

Using the DataList Control

In addition to the DataGrid, other types of data controls may be used to display database data. The DataList control is useful for displaying data in a format other than a tabular form. Listing 14-11 shows the source code to datalist.aspx.cs, a web form with a DataList control being filled with data using an ADO.NET DataSet.

Listing 14-11: Web Form Featuring the Use of the DataList Control

start example
 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.OleDb; //for the OleDb classes using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace SimpleWF {   /// <summary>   /// Summary description for datalist.   /// </summary>   public class datalist : System.Web.UI.Page   {    protected System.Web.UI.WebControls.DataList dlChair;       private void LoadList(DataList dl)    {     //set the connection credentials     string DataSetName = "myChairs";     string ConnectionString =      "Provider=Microsoft.Jet.OLEDB.4.0;" +     "Data Source=C:\\aspData\\employees.mdb;";     //make the DB connection     OleDbConnection myConn = new      OleDbConnection(ConnectionString);     //make a data set to hold chairs     DataSet myDataSet = new DataSet(DataSetName);     //make a data adaptor     OleDbDataAdapter myAdapt = new      OleDbDataAdapter("Select * From tblChair", myConn);           //fill the dataset     myAdapt.Fill(myDataSet);     //show the data in the data list     dl.DataSource = myDataSet;     dl.DataBind();    }    private void Page_Load(object sender, System.EventArgs e)    {     LoadList(this.dlChair);    }    #region Web Form Designer generated code    override protected void OnInit(EventArgs e)    {     //     // CODEGEN: This call is required by the      // ASP.NET Web Form Designer.     //     InitializeComponent();     base.OnInit(e);    }        /// <summary>    /// Required method for Designer support - do not modify    /// the contents of this method with the code editor.    /// </summary>    private void InitializeComponent()    {      this.Load += new System.EventHandler(this.Page_Load);    }    #endregion   } }
end example

The DataList uses another mechanism to sculpt the DataSet, called a template. The template describes how the data is to be displayed in the DataList control. Right-click the DataList and select any of the template editing selections under the context menu’s Edit Template command to enable you to edit the template’s properties. Items such as field headings or names may be set in the template to format how the data should be displayed. Headers, footers, and titles can also accompany a DataList. To specify data from an intended DataSet, the template must be edited in HTML view. The tags <%# and %> denote a data binding expression in a web form page. Inside the template code, the data binding fields may be specified. Listing 14-12 shows the HTML view of datalist.aspx.

Listing 14-12: HTML for datalist.aspx Featuring Data Binding Expressions

start example
 <%@ Page language="c#" Codebehind="datalist.aspx.cs"   AutoEventWireup="false" Inherits="SimpleWF.datalist" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML>   <HEAD>    <title>datalist</title>   <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">   <meta name="CODE_LANGUAGE" Content="C#">   <meta name="vs_defaultClientScript" content="JavaScript">   <meta name="vs_targetSchema"    content="http://schemas.microsoft.com/intellisense/ie5">   </HEAD>   <body MS_POSITIONING="GridLayout" bgColor="#ffffff">    <form  method="post" runat="server">     <asp:DataList  style=      "Z-INDEX: 102; LEFT: 18px; POSITION: absolute;       TOP: 34px" runat="server" Height="301px"        Width="316px">      <ItemTemplate>      <DIV style="PADDING-RIGHT: 15px;          PADDING-LEFT: 15px; PADDING-BOTTOM:          15px; FONT: 12pt verdana;          COLOR: black; PADDING-TOP: 15px"          align="left">ID:</DIV>      <%# DataBinder.Eval(Container.DataItem, "ID")%>      <DIV style="PADDING-RIGHT: 15px; PADDING-LEFT:         15px; PADDING-BOTTOM: 15px;         FONT: 12pt verdana;         COLOR: black; PADDING-TOP: 15px"         align="left">Color:</DIV>      <%# DataBinder.Eval(Container.DataItem, "Color")%>      </ItemTemplate>     </asp:DataList>    </form>   </body> </HTML>
end example

The DataList is denoted by the HTML elements <asp:DataList>. Inside the DataList element tags are the template tags denoted by the <ItemTemplate> tag. The template properties in the Web Forms Designer generate the tags inside the <ItemTemplate> tags, but you can edit them by hand using the HTML view of the web form. The data binding tags may be strategically placed inside the template at locations where you want the respective field of the DataSet to be displayed. Listing 14-12 shows two fields from the DataSet being displayed—ID and Color. The binding tag for field ID is <%# DataBinder.Eval(Container.DataItem, "ID")%> and the binding tag for field Color is <%# DataBinder.Eval(Container.DataItem, "Color")%>.

When datalist.aspx is run, the same DataSet that was generated for the DataGrid example shown in Figure 14-6 was generated for the DataList in datalist.aspx. As seen in Figure 14-7, however, the data format is much different given that it is formatted according to the template shown in Listing 14-12.

click to expand
Figure 14-7: Output of datalist.aspx using template to format DataSet

Data Form Wizard

The Web Forms Designer also offers a wizard to use for creating web forms that display DataSets from a data source. Here’s how to use the Data Form Wizard:

  1. In Solution Explorer, right-click and select Add New Item.

  2. In the Add New Item dialog box, many types of files are listed that can be added to the project. All file types are displayed in the right panel, but if the directory tree on the left is expanded, the child roots of the tree will offer categorical sorts that will change the items displayed in the right panel.

  3. Select Data Form Wizard and type in a filename, as shown in Figure 14-8.

    click to expand
    Figure 14-8: Choosing Data Form Wizard

  4. Click the Open button and a new web form will be created in Visual Studio .NET. In this example, the name employees.aspx was given to the new web form that was created.

  5. The Data Form Wizard opens with the introduction page, informing you of the actions that will take place. Click Next.

  6. In the Choose The Dataset You Want To Use step, the wizard will prompt you to choose an existing dataset or create a new DataSet. In this example, a DataSet named dsEmps will be created, as shown in Figure 14-9. All DataSets that are created in this wizard become an item in the project and may be used by other web forms or web services within the same project. The DataSet file has an .xsd extension.

    click to expand
    Figure 14-9: Choose The Dataset You Want To Use step of the Data Form Wizard

  7. Click the Next button, and the Choose A Data Connection step will display, as shown in Figure 14-10. Existing connections that were established in the project previously are listed in the drop-down combo box. You can choose an existing connection or configure a new connection in this step of the wizard. In this example, the existing connection ASPNETExample is chosen.

    click to expand
    Figure 14-10: Choose A Data Connection step of the Data Form Wizard

  8. Click the New Connection button to open the Data Link Properties window, through which a new connection to a database can be configured.

  9. Click the Next button to see the Choose Tables Or Views step. The wizard will open the data connection provided in the previous step and find the database. You can select the tables to which the web form should connect in the data source. Any tables or views that are to be shown in the web form should be selected in the left panel and placed in the right panel by clicking the right arrow (>) button. In this example, the tblEmployee table is chosen, as shown in Figure 14-11.

    click to expand
    Figure 14-11: Choose Tables Or Views step of the Data Form Wizard

  10. Click the Next button, and the Choose Tables And Columns To Display On The Form step is displayed. The wizard will open the tables or views that were chosen in step 9 and display the tables and views along with each respective column that is available for display in a dual list select box.

  11. Place a check mark next to a column name to tell the wizard the columns that should appear on the web form.

    If more than one table was chosen, the Create A Relationship Between Tables screen will appear, where you can define the relationship between the tables selected by choosing the keys and table relationships. In this example, all of the columns in table tblEmployee are selected for display, as shown in Figure 14-12.

    click to expand
    Figure 14-12: Choose tables and columns to display on the form

  12. Click Finish, and Visual Studio .NET will generate a completed web form named employees.aspx with all of the necessary code in the Codebehind file and controls pasted on the form to display the data in table tblEmplyee.

Figure 14-13 shows the web form employees.aspx in design view. The controls may be moved around to be displayed or to fit as desired. The code behind the form is actually quite good quality as far as wizard-generated code goes, since it even has error handling!

click to expand
Figure 14-13: Resulting web form generated from Data Form Wizard, shown in design view

If employees.aspx is set as the start page, you can press F5 to compile employees.aspx to start the web browser requesting the web form. The page will display a Load button with no data shown in the web browser initially. Click the Load button, and data will be displayed in the web browser, as shown in Figure 14-14.

click to expand
Figure 14-14: Data Form Wizard–generated web form employees.aspx displaying tblEmployee data




IIS 6(c) The Complete Reference
IIS 6: The Complete Reference
ISBN: 0072224959
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net