70528 Notes

  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View 70528 Notes as PDF for free.

More details

  • Words: 14,740
  • Pages: 35
Accessing and Displaying Data

How to: Create and Retrieve Database Connections This document contains extracts from the article “Connecting to Databases in ASP.NET,” which you can find in the Microsoft® Visual Studio® 2005 Documentation at mshelp://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_aspnetcon/html/3a95463b0fd1-44c0-b6a5-3c36002be1dc.htm. Microsoft ASP.NET gives you flexibility in how you connect to databases. Using data-source controls enables you to encapsulate data-access logic in a control that you can configure by specifying connection and query information. Alternatively, you can write the data-access logic yourself.

Using Data Source Controls in a Web Page To connect to a database in ASP.NET, you should do the following (in addition to using custom objects, Microsoft ADO.NET, or other processes): • •



Determine which provider you need. A provider is a class that communicates with a specific type of database. Construct a connection string that includes the information that the provider needs to open a specific database. Add a data source control, such as SqlDataSource, to the page and configure it with the name of the provider, a connection string (or a reference to a connection string stored elsewhere), and query information (typically, an SQL statement).

You can specify provider and connection information as individual properties of data source controls, or you can define provider and connection string information centrally in the configuration file for the Web application (Web.config). This allows you to share information across multiple data control instances by referencing the configuration values.

Coding Data Access Yourself If it is not practical in your application to use data source controls, you can code data access yourself by using ADO.NET classes. You might code data access yourself if you have complex data access requirements that are not possible with data source controls, or if you want to create a separate component that performs data access outside of your Web pages.

Providers A provider is a class that can communicate with a specific type of database or data store. For example, one provider might be able to communicate with a Microsoft SQL Server™ database, and another provider might be able to communicate with a Microsoft Office Access database. In ASP.NET, you can choose from a number of providers that between them can communicate with a wide variety of data stores. The providers include:

• • • •

The The The The

.NET .NET .NET .NET

Framework Framework Framework Framework

Data Data Data Data

Provider Provider Provider Provider

for for for for

SQL Server in the System.Data.SqlClient namespace. OLE DB in the System.Data.OleDb namespace. ODBC in the System.Data.Odbc namespace. Oracle in the System.Data.OracleClient namespace.

You can indicate your provider in the Web.config file as part of a connection string, as a property of a specific data source control instance on your page, or both.

Connection Strings A connection string provides the necessary information so that an underlying provider can make a connection with a particular database using the necessary authentication information. You can store a connection string in the Web.config file and reference it in your page’s data source control. Depending on the provider, a connection string usually supplies the server or location of the database server, the particular database to use, and the authentication information. As with the provider, you can indicate the connection string within the Web.config file or as a property of a specific data source control instance on your page.

Connection String Storage For organizational purposes, it is good practice to place connection strings in the Web.config file. Within the element, you can create a child element named and place your connection strings there:


providerName="System.Data.SqlClient" / rel="nofollow">
In this example, the name and provider are both supplied, and any data source control can use values from the Web.config file. One advantage to this process is that you can easily change the server name, database, or authentication information without editing individual Web pages.

Retrieving Connection Strings Programmatically You can programmatically retrieve connection strings from the Web.config file at run time and use them in conjunction with data source controls or ADO.NET objects. The following examples show how to retrieve a connection string and use it to open an ADO.NET Connection object:

'[Visual Basic] Dim dbString As String = _ ConfigurationManager.ConnectionStrings _ ("AppConnString").ConnectionString Dim sqlConn As System.Data.SqlClient.SqlConnection = _ New System.Data.SqlClient.SqlConnection(dbString) sqlConn.Open() If sqlConn.State.ToString() = "Open" Then 'Perform data operations End If //[Visual C#] string dbString = ConfigurationManager.ConnectionStrings ["AppConnString"].ConnectionString; System.Data.SqlClient.SqlConnection sqlConn = new System.Data.SqlClient.SqlConnection(dbString); sqlConn.Open(); if (sqlConn.State.ToString() == "Open") { //Perform data operations } Data Source Controls A data source control such as SqlDataSource pulls together all the elements of connecting to a database (provider, connection string, and query) to retrieve or manipulate data. For example, the SqlDataSource control in the following example is configured to connect to a database and pull all records from a Customer table:

" ProviderName="<%$ ConnectionStrings:AppConnString.ProviderName %>" /> In this example, the provider and connection string are contained within the Web.config file, while the SQL query is stated as an attribute of the control declaration.

Accessing and Displaying Data

Products.aspx Page Design The following illustration shows a model page layout for the Products.aspx prototype. You should use this illustration as a guide when you are designing the Product page in the lab.

Accessing and Displaying Data

How to: Access Data by Using SqlDataSource Controls This document contains extracts from the article “SqlDataSource Web Server Control Overview,” which you can find in the Microsoft® Visual Studio® 2005 Documentation at mshelp://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_aspnetcon/html/34779c84-3512-49d98e6f-643aaae216ce.htm. Microsoft ASP.NET includes a set of data source controls that allow you to interact with different types of data sources. All data source controls provide the same basic functionality, regardless of what underlying data source they interact with. For example, all data source controls support a Select method that retrieves data. The data source control model is extensible, so you can also create your own data source controls that interact with different data sources or that provide additional functionality for an existing data source.

SqlDataSource Control The SqlDataSource control allows you to retrieve and update data using SQL commands. The SqlDataSource control works with Microsoft SQL Server™, OLE DB, ODBC, and Oracle databases, depending on the data provider configured for your application. By default, the control works with SQL Server.

Connections When you configure a SqlDataSource control, you specify a connection string in the ConnectingString property that includes information that the control needs to connect to a database. The contents of a connection string differ depending on what type of database the data source control is accessing. For example, the SqlDataSource control (and any other data source control that interacts with SQL Server)

requires a server name, a database (catalog) name, and information about how to authenticate the user. Instead of setting connection strings at design time as part of the data source control, you can store them centrally as part of your application’s configuration settings. In that case, you can programmatically retrieve the connection string and assign it to the data source control when the page runs.

Commands You can specify up to four commands (SQL queries) for the SqlDataSource control: SelectCommand, UpdateCommand, DeleteCommand, and InsertCommand. Each command is a separate property of the data source control. For each command property, you specify a SQL statement that the data source control should execute. If the data source control connects to a database that supports stored procedures, you can specify the name of a stored procedure in place of the SQL statement for a command. You can create parameterized commands that include placeholders for values to be supplied at run time. The following example shows a typical parameterized SQL Select command:

Select CustomerID, CompanyName From Customers Where city = @city You can create parameter objects that specify where the command should get parameter values at run time, such as from another control, from a query string, and so on. Alternatively, you can specify parameter values programmatically. The data source control executes the commands when the corresponding Select, Update,Delete, or Insert method is called. The Select method is called automatically when you call the DataBind method of the page or of a control bound to the data source control. You can also call any of the four methods explicitly when you want the data source control to execute a command. Some controls, such as the GridView command, can call the methods automatically, without requiring that you call the methods or that you explicitly call the DataBind method.

Format of Returned Data The SqlDataSource control can return data in two forms—as a DataSet or as a data reader—which you can select by setting the DataSourceMode property of the data source control. A DataSet contains all the data in memory, allowing you to manipulate the data in various ways after retrieving it. A data reader provides a read-only cursor that can fetch individual records. As a rule, you would choose to return a DataSet if you wanted to filter, sort, or page through data after retrieving it or if you wanted to maintain a cache. In contrast, you would use a data reader if you simply wanted to return the data and load it (bind it) into a control on the page. For example, using a data reader is ideal for returning data that you want to display in a ListBox, DropDownList, or GridView control.

Caching The SqlDataSource control can cache data that it has retrieved, which can enhance the performance of your applications by avoiding expensive queries. Caching is practical in almost any situation in which the data is not highly volatile. Caching is not enabled by default, but you can set it by setting EnableCaching to true. The caching mechanism is based on time; you can set the CacheDuration property to the number of seconds to cache data. The data source control maintains a separate cache for each combination of connection, Select query, parameters, and cache settings. The SqlDataSource control can also take advantage of the cache dependency feature of SQL Server (if available in your version of SQL Server). This feature allows you to specify a database and table. The data in the cache is maintained until SQL Server reports a change in the specified table. This type of caching allows you to create high-performance data access in your Web applications, because you can minimize data retrieval to only those times when it is necessary to get refreshed data.

Sorting and Filtering If you have cached data and have specified a DataSet as the format for data returned by a Select query, you can also filter the data without rerunning the query. The SqlDataSource control supports a FilterExpression property that allows you to specify selection criteria that are applied to the data maintained by the data source control. You can also parameterize the filter expression by creating special FilterParameters objects that provide values at run time to the filter expression.

To Add and Configure an SqlDataSource Control on a Web Page The following steps describe the process of adding and configuring an SqlDataSource control on a Web Page so that it retrieves a list of customers from the Northwind database, by using the NWind connection that has been configured in the Web.config file:

1. 2. 3.

Drag an SqlDataSource control from the Data group in the Toolbox onto the Design view of a Web page. Click Configure Data Source in the Smart Tag of the SqlDataSource control. Click NWind in the Which data connection should your application use to connect to the database? list.

Note

4. 5. 6.

NWind is the name used to identify the database connection in the Web.config file. Click Next. Click Specify a custom SQL statement or stored procedure and then click Next. On the Select tab, type the following SQL code in the SQL statement text box:

Select CustomerID, CompanyName From Customers ORDER BY CompanyName Note

7. 8. 9.

This SQL statement retrieves a list of customer IDs and company names from the database, sorted alphabetically by customer name. Click Next. Click Test Query and review the results. Click Finish.

Accessing and Displaying Data

How to: Access Data by Using ASP.NET Data-Bound Controls Microsoft ASP.NET features several different types of data-bound controls, offering you flexibility in the presentation of data on your page. In the latest release of ASP.NET, the GridView, DetailsView, and FormView controls support editing, updating, and deleting data. In addition, the DetailsView also supports insertion of new data. The GridView control also supersedes the DataGrid from previous versions of ASP.NET; it supports all the functionality of the DataGrid control and provides additional features.

List of Controls In this section, you are introduced to each of the data-bound controls in ASP.NET with an explanation of the control’s purpose and functionality.

FormView The FormView control is a data-bound container allowing you to create a freeform layout for viewing and editing data with individual controls. For example, you could tie a FormView control to a user’s profile, allowing the user to both see and edit his or her profile using simple controls like the TextBox and DropDownList and to use the binding support of FormView to update the data automatically. You can use the control’s EditItemTemplate to tailor how your data is displayed on the form when the user is editing data. Binding syntax is used to bind a particular form control, such as a TextBox, to a data field. A user’s changes to the data can be automatically updated in the database using FormView.

GridView The GridView control displays multiple rows of data in a grid (table) on the page, with a row in the grid for each data record and a column for each data field you are displaying. The GridView control supports automatic paging and sorting. You can configure the control to allow users to edit or delete rows; the user’s action is transmitted to the GridView control’s data source, which performs the appropriate database action. You can customize the appearance of data in a column, and the control provides events that you can handle to modify data as it is displayed or after the user has edited it.

Note The GridView control supersedes the DataGrid control that performed similar functions in earlier versions of ASP.NET. The DataGrid control is still available for backward compatibility with existing Web applications.

DetailsView The DetailsView control displays one or more records from a data source, one record at a time. If the data source provides more than one record, the DetailsView control can page through individual records. You can configure the DetailsView control to allow users to view, edit, delete, and insert records.

DetailsView is useful when used in conjunction with a list-based data display such as GridView. For example, you could click on a name in a GridView and then dynamically display a DetailsView to show a record for that particular name.

DataList The DataList control displays multiple records, typically in a table. Unlike the GridView control, the DataList control does not provide a predetermined layout for the data. For example, the DataList control does not inherently display data in a rows and columns. Instead, you define the layout for the data using templates. Templates contain controls, such as the Label control, that you bind to individual fields in the data record. The DataList control therefore provides a freeform way to lay out the display of multiple rows within a table-like structure. You can configure the DataList control to allow users to select, edit, and delete records. The DataList control is another list-type control that displays your entire result set based on templates that you may edit and configure. The DataList may be customized through properties to customize the control and set data presentation options such as the direction of the data display and a different presentation for alternating rows of data.

Repeater The Repeater control is similar to the DataList control in that it also allows you to create a freeform layout for displaying multiple records. With the Repeater control, you use your own HTML and controls surrounding the data row you want to display, and the repeater control will repeat the markup and controls for each row of data in your result set. Its functionality is similar to scripting a for loop around presentation code but is simpler to use, as the control manages the data presentation. Data-binding syntax is used to populate controls contained within the repeater. For example:


The preceding repeater control iterates through the result set, rendering the ContactName from each row in the context of the HTML contained within the control.

DropDownList and ListBox You can bind data to both the ListBox and DropDownList because of their inheritance of the ListControl. For example, you can bind a DropDownList to your query using one column for a value, and another column for display:

In this DropDownList, the DataValueField property shows a customer ID string, while the DataTextField property shows a user-friendly contact name.

TreeView The TreeView control is a hierarchical data-bound control and may be used in conjunction with an XmlDataSource or a SiteMapDataSource. The inherently hierarchical data from either of these two sources is used to create a straightforward expandable and collapsible tree for the user.

Menu The Menu control features hierarchical data-binding and may be bound to an XmlDataSource or a SiteMapDataSource. The hierarchical data from either of these sources is used to construct the primary selection, depth, and submenus of the Menu control.

Control and DataSource Considerations Your choice of data-bound control may rest on whether it supports your data source. The following two lists contain details of which controls support which data sources. For example, TreeView and the Menu control can only use hierarchical data sources. The rest of the data-bound controls may use either hierarchical or standard data sources. These DataSource controls support the IDataSource interface: • •

ObjectDataSource SqlDataSource



AccessDataSource

These DataSource controls support the IHierarchicalDataSource interface in addition to the IDataSource interface: • •

XmlDataSource SiteMapDataSource

Most data-bound controls require the IDataSource interface, which all DataSource controls support. Some controls require the IHierarchicalDataSource interface, which only two DataSource controls support. Controls that can use any DataSource: • • • • • •

FormView GridView DetailsView DataList Repeater BulletedList

Controls that may only use hierarchical-supporting DataSource controls: • •

TreeView Menu

Accessing and Displaying Data

How to: Access and Display Data by Using the GridView Control This resource describes how to access and display data by using a GridView control. The GridView control can accept parameters that filter the data displayed. In the following example, a parameter will be supplied at run time by the selected value in a DropDownList control named ddCustomerID. The data will be retrieved from the Northwind database; the data source for the GridView control will connect to the database by using a connection string from the Web.config file.

To Add a GridView Control to a Web Page

1. 2. 3. 4. 5. 6.

Drag a GridView control from the Data group in the Toolbox onto a Web page. A Smart Tag appears for the GridView control. In the Choose Data Source list, click New data source. The Data Source Configuration Wizard appears. Click Database in the Where will the application get data from? section. Type dsCustomers in the Specify an ID for the data source box. Click OK. The Configure Data Source dialog box appears. Click NWind in the Which data connection should your application use to connect to the database? list.

Note

7. 8. 9.

NWind is the name used to identify the database connection in the Web.config file. Click Next. Click Specify a custom SQL statement or stored procedure and then click Next. On the Select tab, type the following SQL code in the SQL statement text box:

SELECT CustomerID, CompanyName, Address, City FROM Customers WHERE (CustomerID = @CustomerID) Note

This SQL statement retrieves customer details from the Customer table in the Northwind database. The WHERE clause of the select statement includes a parameter named @CustomerID. The value of this parameter will be determined at run time by referencing the selected item in the ddCustomerID DropDownList control. 10. Click Next.

11. Click Control in the Parameter source list. 12. Click ddCustomerID in the ControlID list. 13. Click Next. 14. Click Test Query.

The Parameter Values Editor dialog box appears.

15. Click Int32 in the Type list and then enter 1 in the Value box. 16. Click OK and review the results. The details of the customer with a CustomerID of 1 are displayed.

17. Click Finish. To Configure the Columns of the GridView Control

1.

On the Smart Tag menu for the GridView control, select the Enable Selection check box.

Note

2. 3.

Enabling selection specifies that the user can select a row in the GridView control at run time. It adds a column to the GridView control that the user can click to select a row. Click Edit Columns and then remove the CustomerID column.

Move the Select field below the CompanyName, Address, and City fields in the Selected fields list. 4. Set the HeaderText property of the CompanyName field to Customers. 5. Set the following properties of the Select field:  HeaderText:  SelectText: [>]  ShowSelectButton: True

Accessing and Displaying Data

How to: Access Objects as Data by Using ObjectDataSource Controls This document contains extracts of the article “Walkthrough: Data Binding to a Custom Business Object,” which you can find in the Microsoft® Visual Studio® 2005 Documentation at mshelp://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_vwdcon/html/a806fa2c-fe6a-405f-869c74e804a642ea.htm. Many Web applications are built by using multiple tiers, with one or more components in the middle tier to provide data access. Microsoft Visual Web Developer™ includes a wizard that helps you create a data component that you can use as a middle-tier data object. However, you might also want to build a custom business object, rather than relying on the data component created by the wizard. Creating a custom business object allows you to implement your own business logic. This walkthrough illustrates how to create a basic business object that you can use as a data source for Microsoft ASP.NET Web pages.

Creating an XML File for Business Data In the following procedure, you will create a simple XML file for the business component data. To create the XML file

1.

In Solution Explorer, right-click App_Data and then click Add New Item.

Note

2. 3. 4. 5.

Be sure you create the XML file in the App_Data folder. The App_Data folder has permissions set on it that will allow the Web page to read and write data to the XML file. Under Visual Studio installed templates, click XML file. In the Name box, type Authors.xml. Click Add. A new XML file is created containing only the XML directive. Copy the following XML data and then paste it into the file, overwriting what is already in the file. The XML file includes schema information that identifies the database structure of the data, including a primary-key constraint for the key.

Note

Business components can work with data in any way that is suitable for your application. This walkthrough uses an XML file.

<xs:schema id="dsPubs" targetNamespace="http://www.tempuri.org/dsPubs.xsd" xmlns:mstns="http://www.tempuri.org/dsPubs.xsd" xmlns="http://www.tempuri.org/dsPubs.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema"

xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified"> <xs:element name="dsPubs" msdata:IsDataSet="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="authors"> <xs:complexType> <xs:sequence> <xs:element name="au_id" type="xs:string" /> <xs:element name="au_lname" type="xs:string" /> <xs:element name="au_fname" type="xs:string" /> <xs:element name="au_phone" type="xs:string" /> <xs:unique name="Constraint1" msdata:PrimaryKey="true"> <xs:selector xpath=".//mstns:authors" /> <xs:field xpath="mstns:au_id" /> 172-32-1176 West Paul 408 555-0123 213-46-8915 Gray Chris 415 555-0120
6.

Save the Authors.xml file and then close it.

Creating a Component The next step is to create a class to act as your business component. You will keep the component in the App_Code folder of your Web site. In a real application, you can keep the component in any convenient store, including the Global Assembly Cache (GAC). If your Web site does not already have a directory called App_Code, you must create one. To create an App_Code folder

1. 2.

In Solution Explorer, right-click the name of your Web site, and then click New Folder. Name the folder App_Code.

Note The folder must be named App_Code. You can now add the component to your site. To create the business component

1.

In Solution Explorer, right-click App_Code and then click Add New Item. The Add New Item dialog box appears

Note

2.

Be sure to create the new item in the App_Code folder. Under Visual Studio installed templates, click Class.

3. 4. 5. 6.

In the Language box, click the programming language you prefer. In the Name box, type BusinessObject. Click Add. Visual Web Developer creates the new class file and opens the code editor. Copy the following code, and then paste it into the file, overwriting what is already in the file:

[Visual Basic] Imports Microsoft.VisualBasic Imports System Imports System.Web Imports System.Data Namespace PubsClasses Public Class AuthorClass Private dsAuthors As DataSet = _ New System.Data.DataSet("ds1") Private filePath As String = _ HttpContext.Current.Server.MapPath("~/Data/authors.xml") Public Sub New() dsAuthors.ReadXml(filePath, Data.XmlReadMode.ReadSchema) End Sub Public Function GetAuthors() As DataSet Return dsAuthors End Function End Class End Namespace [C#] using System; using System.Web; using System.Data; namespace PubsClasses { public class AuthorClass { private DataSet dsAuthors = new DataSet("ds1"); private String filePath = HttpContext.Current.Server.MapPath("~/App_Data/Authors.xm l"); public AuthorClass() { dsAuthors.ReadXml (filePath, XmlReadMode.ReadSchema); } public DataSet GetAuthors () { return dsAuthors; } } } Note

7.

Make sure the value of the filePath variable references the name of the XML file that you created previously. When the class is instantiated, it reads the XML file and translates it into a DataSet. The GetAuthors method for the class returns the DataSet. Save the file.

Displaying Data by Using the Business Component You can now invoke the business component in a Web page and display its data. To reference the component, you use an ObjectDataSource control, which is specifically designed to work with objects. To create an ObjectDataSource control that references the component 1.

Switch to or open the Default.aspx page.

Note

2.

3. 4. 5. 6. 7. 8. 9.

If you do not have a Default.aspx page, you can use another page. Alternatively, you can add a new page to the Web site. In Solution Explorer, right-click the name of your Web site, click Add New Item, and then add a Web Form. Switch to Design view. In the Toolbox, from the Data folder, drag an ObjectDataSource control onto the page. In the Properties window, set ID to AuthorsObjectDataSource. Right-click the ObjectDataSource control and then click Show Smart Tag. On the Common ObjectDataSource Tasks menu, click Configure Data Source. The Configure Data Source Wizard appears. In the Enter the name of your business object list, click PubsClasses.AuthorClass. This is the type name (namespace and class name) of the class that you created previously. Click Next.

On the Select tab, in the Choose a method list, click GetAuthors. The GetAuthors method is defined in the business class that you created previously. It returns a DataSet containing the data from the Authors.xml file. 10. Click Finish. The configuration information you have entered specifies that to get data from the component, the component’s GetAuthors method should be called. You can now get data from the component by using the ObjectDataSource control. You will display the data in a GridView control on the page. To display data from the component

1. 2. 3. 4.

In the Toolbox, from the Data folder, drag a GridView control onto the page. Right-click the GridView control and then click Show Smart Tag. On the Common GridView Tasks menu, in the Choose Data Source box, click AuthorsObjectDataSource. Press CTRL+F5 to run the page. The GridView control with the XML data in it is displayed.

Inserting Data by Using the Business Component As with other data source controls, such as the SqlDataSource control, the ObjectDataSource control supports updating (inserting, updating, and deleting). In this section, you will modify the business component with a method that inserts an author record. Then you will change the page so that users can type new author information and modify the ObjectDataSource control to perform the insertion.

Note During this part of the walkthrough, the Authors.xml file you created previously will be updated. It is important that the application have permission to write to the file at run time; if it does not, the Web page will display an error when you try to update the file. If you created the Authors.xml file in the App_Data folder, permissions are set automatically.

To modify the business component to allow inserts 1.

2.

Switch to the BusinessObject file. Add the following method as the final member of AuthorClass:

[Visual Basic] Public Sub InsertAuthor(ByVal au_id As String, _ ByVal au_lname As String, _ ByVal au_fname As String, ByVal au_phone As String) Dim workRow As DataRow = dsAuthors.Tables(0).NewRow workRow.BeginEdit() workRow(0) = au_id workRow(1) = au_lname workRow(2) = au_fname workRow(3) = au_phone workRow.EndEdit() dsAuthors.Tables(0).Rows.Add(workRow) dsAuthors.WriteXml(filePath, Data.XmlWriteMode.WriteSchema) End Sub [C#] public void InsertAuthor (String au_id, String au_lname, String au_fname, String au_phone) {

}

DataRow workRow = dsAuthors.Tables[0].NewRow (); workRow.BeginEdit (); workRow[0] = au_id; workRow[1] = au_lname; workRow[2] = au_fname; workRow[3] = au_phone; workRow.EndEdit (); dsAuthors.Tables[0].Rows.Add (workRow); dsAuthors.WriteXml (filePath, XmlWriteMode.WriteSchema);

Note

3.

Pay close attention to the names of the variables used to pass author information into the method (au_id, au_lname, au_fname, and au_phone). They must match the column names defined in the schema of the XML file you created previously. The new method takes four values to insert, which you will provide in the page as parameters. The method creates a new row in the DataSet and then writes the updated DataSet out as an XML file. Save the file.

The next step is to change the page so that users can enter new author information. For the following procedure, you will use the DetailsView control. To add a control for inserting data 1. 2.

3.

Switch to or open the Default.aspx page. Switch to Design view. In the Toolbox, from the Data folder, drag a DetailsView control onto the page.

Note

4.

The exact layout of the page is not important. On the Common DetailsView Tasks menu, in the Choose Data Source box, click AuthorsObjectDataSource.

Note

5.

If the Common DetailsView Tasks menu is not visible, right-click the control, and then click Show Smart Tag. In the Properties window, set AutoGenerateInsertButton to true. This causes the DetailsView control to render a New button that users can click to put the control into data-entry mode.

Finally, you must configure the ObjectDataSource control to specify what action the control should take to insert data. To configure the data source control for inserting data



Right-click AuthorsObjectDataSource, click Properties, and then set InsertMethod to InsertAuthor. This is the name of the method that you added to the business component.

You can now insert new authors into the XML file. To test insertion 1.

2. 3.

Press CTRL+F5 to run the Default.aspx page. In the DetailsView control, click New. The control is redisplayed with text boxes. Enter new author information, and then click Insert. The new author information is added to the XML file. The GridView control immediately reflects the new record.

Accessing and Displaying Data

How to: Access XML Data by Using XmlDataSource Controls This document is an extract from the article “XmlDataSource Class,” which you can find in the Microsoft® Visual Studio® 2005 Documentation at mshelp://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20.en/cpref16/html/T_System_Web_UI_WebControl s_XmlDataSource.htm.

The following code example demonstrates how to use an XmlDataSource control with a TreeView control to display XML data. The XmlDataSource loads XML data from the XML file identified by the DataFile property.

[Visual Basic] <%@ Page Language="VB" %>
[C#] <%@ Page Language="C#" %>
The XML file in the code example has the following data:



<securitybooks>


Controlling Access to a Web Application

How to: Configure Authentication for a Web Application Microsoft® ASP.NET uses authentication providers to implement authentication for Web applications. An authentication provider is a core module that contains the code necessary to authenticate credentials. An authentication provider handles many of the common tasks involved. The ASP.NET authentication providers are:



Windows Authentication. When your application uses Windows Authentication, Internet Information Services (IIS) validates credentials against Microsoft Windows® accounts stored in Active Directory® directory service or the Security Account Manager (SAM). The users must have valid Windows accounts. IIS prompts the user for details, if necessary. Basic, Digest or Windows Integrated authentication is used, depending on the configuration of IIS and the capabilities of the browser. Passport Authentication. When your application uses Passport Authentication, users can use their MSN® Passport to access your site. Forms Authentication. When your application uses Forms Authentication, you can create a custom ASP.NET page to collect the credentials from the user. If users attempt to access a page for which they are not authorized, they will be automatically redirected to the login page. You can store user credentials in a variety of locations, including Microsoft SQL Server™ and Microsoft Office Access databases.

• •

This document describes how to configure each of these providers.

Configuring Windows Authentication To use Windows Authentication, you configure ASP.NET and IIS and create user accounts for each user you need to identify. To configure the ASP.NET application 1.

2.

Open the Web.config file in the root folder of your application. Locate the <system.web> and tags. Add the following element between these tags:

To configure the IIS Web site

1. 2. 3.

4. 5. 6. 7. 8. 9.

Click Start, right-click My Computer, and then click Manage. In the Computer Management console, expand Services and Applications and then click Internet Information Services. In the Internet Information Services console, select the Web site or virtual directory that hosts your application. Right-click the Web site and then click Properties. In the Web Site properties dialog box, click the Directory Security tab. In the Anonymous access and authentication control section, click Edit. In the Authenticated access section of the Authentication Methods dialog box, choose the Basic or Integrated Windows Authentication option as appropriate. Clear the Enable Anonymous Access check box. Click OK twice to apply your configuration and close the dialog boxes. Close the Computer Management console.

Configuring Passport Authentication

To implement Passport Authentication, you must first register with the Microsoft Passport Service on the Microsoft Passport Network Web site. You should also download the .NET Passport SDK from the same location. To configure Passport Authentication for your ASP.NET application 1.

2.

Open the Web.config file in the root folder of your application. Locate the <system.web> and tags. Add the following element between these tags:

Configuring Forms Authentication Forms authentication requires a login page to collect credentials from the user and compare them against stored credentials. For more information on login pages, see the resource document “How to: Implement a Login Page and Add Login Controls.” After you have created the login page you must configure the application to use it. This involves modifying the Web.config file. To configure Forms Authentication for your ASP.NET Application 1.

2.

Open the Web.config file in the root folder of your application. Locate the <system.web> and tags. Add the following element between these tags:

You frequently store accounts in a database or some other external location. However, it is possible to keep a list of users in the Web.config file itself. This is appropriate when the number of users is small and fixed. To configure Forms Authentication with credentials stored in the Web.config file 1.

2.

Open the Web.config file in the top folder of your application. Locate the <system.web> and tags. Add the following elements between them:

<user name="Kim" password="07B7F3EE06F278DB966BE960E7CBBD103DF30CA6"/> <user name="John" password="BA56E5E0366D003E98EA1C7F04ABF8FCB3753889"/> In this example, the passwords have been hashed by using a one-way algorithm so that the password is held in the file in a non-reversible format.

Controlling Access to a Web Application

How to: Configure Authorization for a Web Application There are two ways to configure authorization for a Microsoft® ASP.NET Web application:

• •

File Authorization. This is available only if your application uses Microsoft Windows® Authentication. You can set permissions on files and directories by using Access Control Lists (ACLs). URL Authorization. This is available regardless of which authentication provider you are using. You use the Web.config file in each directory of the application to assign permissions for the contents of the directory.

This document discusses using URL Authorization. To configure URL Authorization for a directory in an ASP.NET application

1. 2. 3.

In Microsoft Visual Studio®, if there is no Web.config file in the directory, right-click the directory in Solution Explorer and then click Add New Item. In the Add New Item dialog box, click Web Configuration File and then click Add. A new Web.config file is added and displayed Locate the <system.web> and tags. Add the following markup between these tags:

<deny users="John"/> <deny users="?"/> This example demonstrates how to assign authorizations to users, such as Kim, or roles, such as Admins. Use of tags permit access and <deny> tags prevent access. Authorizations appearing earlier in the list take precedence over those that appear later. There are two special characters that can be used: • •

“?” indicates anonymous users. “*” indicates all users. If you place this entry at the bottom of the list, it becomes the default authorization for any users not mentioned above it.

If you are using Windows Authentication, you must apply an authorization to a Windows account by specifying the full name, for example, LON-DEV-01\Student. To configure URL Authorization for a single file in an ASP.NET application

1. 2. 3.

In Visual Studio, if there is no Web.config file in the directory holding the file, right-click the directory in Solution Explorer and then click Add New Item. In the Add New Item dialog box, click Web Configuration File and then click Add. A new Web.config file is added and displayed. Locate the and tags. Add the following markup between these tags:

<system.web> <deny users="*"/>

Controlling Access to a Web Application

Introduction to Membership

This document is a copy of the article “Introduction to Membership,” which you can find in the Microsoft® Visual Studio® 2005 documentation at mshelp://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_aspnetcon/html/79184d17-f4c7-4c9fa073-cec4f5543980.htm. Microsoft ASP.NET membership gives you a built-in way to validate and store user credentials. ASP.NET membership, therefore, helps you manage user authentication in your Web sites. You can use ASP.NET membership with ASP.NET Forms authentication or with the ASP.NET login controls to create a complete system for authenticating users. ASP.NET membership supports facilities for: • • • •

Creating new users and passwords. Storing membership information (user names, passwords, and supporting data) in Microsoft SQL Server™, Microsoft Office Access, or in an alternative data store. Authenticating users who visit your site. You can authenticate users programmatically, or you can use the ASP.NET login controls to create a complete authentication system that requires little or no code. Managing passwords, which includes creating, changing, or resetting them; maintaining password expiration dates, and so on. Depending on which membership options you choose, the

membership system can also provide an automated password reminder system that uses a usersupplied question and response. Exposing a unique identification for authenticated users that you can use in your own applications and that also integrates with the ASP.NET personalization and role management (authorization) systems. Specifying a custom membership provider, which allows you to substitute your own code to manage membership and maintain membership data in a custom data store.

• •

Membership, Roles, and the User Profile Although membership is a self-standing feature in ASP.NET for authentication, it can be integrated with ASP.NET role management to provide authorization services for your site. Membership can also be integrated with the user profile to provide application-specific customization that can be tailored to individual users.

How Membership Works To use membership, you must first configure it for your site. In summary, you follow these steps: 1.

2.

3.

Specify membership options as part of your Web site configuration. By default, membership is enabled. You can also specify the membership provider you want to use. (In practical terms, this means that you are specifying the type of database you want to keep membership information in.) The default provider uses an Access database. You can also choose to use SQL Server to store membership information, or you can specify a custom provider. Configure your application to use Forms authentication (as distinct from Microsoft Windows® Authentication or Passport authentication). You typically specify that some pages or folders in your application are protected and are accessible only to authenticated users. Define user accounts for membership. You can do this in a variety of ways. You can use the Web Site Administration Tool, which provides a wizard-like interface for creating new users. Alternatively, you can create a “new user” ASP.NET Web page where you collect a user name and a password (and optionally an e-mail address) and then use a membership function named CreateUser to create a new user in the membership system.

You can now use membership to authenticate users in your application. Most often, you will provide a login form, which might be a separate page or a special area on your home page. You can create the login form by hand using ASP.NET TextBox controls, or you can use ASP.NET login controls. Because you have configured the application to use Forms authentication, ASP.NET will automatically display the login page if an unauthenticated or unauthorized user requests a protected page.

Note The ASP.NET login controls encapsulate virtually all of the logic required to prompt users for credentials and validate the credentials in the membership system.

If you use login controls, they will automatically use the membership system to validate a user. If you have created a login form by hand, you can prompt the user for a user name and password and then call ValidateUser to perform the validation. When the user is validated, information about the user is persisted (for example, using an encrypted cookie if the user’s browser accepts cookies). The login controls perform this task automatically. If you have created a login form by hand, you can call methods of the FormsAuthentication class to create the cookie and write it to the user’s computer. If a user has forgotten his or her password, code in the login page can call membership functions that help the user remember the password or create a new one. Each time the user requests another protected page, ASP.NET Forms authentication checks whether the user is authenticated and then either allows the user to view the page or redirects the user to the login page. By default, the authentication cookie remains valid for the user’s session. After a user has been authenticated, the membership system makes available an object that contains information about the current user. For example, you can get properties of the membership user object to determine the user’s name or e-mail address, when the user last logged into your application, and so on. An important aspect of the membership system is that you never need to explicitly perform any lowlevel database functions to get or set user information. For example, you create a new user by calling the membership CreateUser method. The membership system handles the details of creating the necessary database records to store the user information. When you call the ValidateUser method to check a user’s credentials, the membership system does all the database lookup for you.

Anonymous Users in the Membership System The membership system allows your application to accept and work with anonymous users, defined as those who have not been authenticated. Anonymous identification is not enabled by default, but when it is enabled, unauthenticated users are assigned a temporary ID in the membership system. The ID allows you to track users who are online at your site, even if they have not been authenticated. In

addition, the ID for the anonymous user allows the membership system to associate data, such as profile information, with the anonymous user, and provides an ID that can be used with the profile for that user. The anonymous user’s ID is stored in a cookie, much as a forms authentication ticket, except that the membership system does not consider the user to be logged in. If the user’s browser does not accept cookies, the anonymous identification can be embedded in the URL of requested pages. If an anonymous user logs in, the anonymous identification information is discarded and the user is treated thereafter as an authenticated user. If you are using personalization, the user’s personalization values can be migrated so that they are retained as part of the user’s logged-in user identity.

Membership Configuration and Management You configure the membership system in your application’s Web.config file. The easiest way to configure and manage membership is with the Web Site Administration Tool, which provides a wizard-based interface. As part of membership configuration, you specify: • • •

What membership provider to use. (This typically also specifies what database to store membership information in.) Password options such as encryption and whether to support password recovery based on a userspecific question. Users and passwords. If you are using the Web Site Administration Tool, you can create and manage users directly. Otherwise, you must call membership functions to create and manage users programmatically.

Controlling Access to a Web Application

How to: Configure an ASP.NET Application to Use Membership This document contains extracts from the article “Configuring an ASP.NET Application to Use Membership,” which you can find in the Microsoft® Visual Studio® 2005 documentation at mshelp://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_aspnetcon/html/283c397e-3a2d-458f84e3-df94460ab052.htm. Microsoft ASP.NET Membership is configured using the < membership>element in the Web.config file for your application. The < membership>element is a sub-element of the < system.web>section. You can also enable ASP.NET Membership for an application by directly editing the Web.config file for that application, or you can use the Web Site Administration Tool, which provides a wizard-based interface. As part of membership configuration, you specify: • • •

What membership provider to use. (This typically also specifies what database to store membership information in.) Password options such as encryption and whether to support password recovery based on a userspecific question. Users and passwords. If you are using the Web Site Administration Tool, you can create and manage users directly. Otherwise, you must call membership functions to create and manage users programmatically.

Specifying the Default Provider You specify the default membership provider using the defaultProvider attribute of the < membership>element. The machine configuration specifies a SqlMembershipProvider instance named AspNetSqlProvider that is identified as the default provider if you do not specify a default provider explicitly. AspNetSqlProvider connects to the aspnetdb database in the local computer running Microsoft SQL Server™.

Note You need to set up the database used by SqlMembershipProvider before using it in an application.

You can also specify the default provider instance and options for that provider by configuring a provider in the < membership>section. You use the < providers>element to identify a provider to add to the collection of providers available for the application. You can identify your provider instance as the default provider using the value of the name attribute as the defaultProvider value. When you specify a provider instance, you must also specify a valid connection string for that instance using the < connectionStrings>section of the configuration. For example, the following Web.config file identifies a SqlMembershipProvider instance that connects to a computer running SQL Server that is not the local server:

<system.web> <deny users="?" /> <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15"> <providers>

Controlling Access to a Web Application

Login and Membership Page Design The following examples will help you design the Web pages in this lab. The illustrations show the pages in Microsoft® Visual Studio® Design view.

MemberUpdate.aspx

MembersLogin.aspx

TopLevel.master

Controlling Access to a Web Application

How to: Implement a Login Page and Add Login Controls If you are using Forms authentication, you must create a login page that prompts the user for a user name and password. You can create this page by using the Login Web server control. The name of the page must match the loginUrl attribute of the < forms>element in the Web.config file. By default, Microsoft® ASP.NET Membership is configured to use a login page called login.aspx.

The Login Web server control is designed to work with ASP.NET Membership. Therefore, you must have configured Membership before using this control. For details see “How to: Configure an ASP.NET Application to Use Membership.” To create the login page and add a Login control

1. 2.

In Microsoft Visual Studio®, add a new Web form to the Web application. Ensure that the name of this file matches the loginUrl attribute of the < forms>element specified in the application’s Web.Config file. In Design view, drag a Login control onto the page from the Login section of the Toolbox, or in Source view, add the following markup to the page:

To add a PasswordRecovery control to the page



In Design view, drag a PasswordRecovery control onto the page from the Login section of the Toolbox, or in Source view, add the following markup to the page:

To add a LoginStatus control to the page



In Design view, drag a LoginStatus control onto the page from the Login section of the Toolbox, or in Source view, add the following markup to the page:

The LoginStatus control indicates whether the current user is authenticated or anonymous. To add a LoginName control to the page



In Design view, drag a LoginName control onto the page from the Login section of the Toolbox, or in Source view, add the following markup to the page:

The LoginName control shows the user name of the current authenticated user. To add a LoginView control to the page, including templates for logged-in and anonymous users •

In Source view, add the following markup to the page:

Welcome,
Change Password
Click Login to sign in.
Register Forgot your password?


Controlling Access to a Web Application

How to: Create a Membership Management Administrative User Interface If you are using Microsoft® ASP.NET Forms authentication and URL authorization, you can assign permissions to individual users or to roles. A role is a group of users. Any permission you assign to a role automatically applies to all the members of that role. To use roles, you must first configure the ASP.NET Roles Provider in the Web.config file. You can set up the membership of each role by using the ASP.NET Administration Tool. This document shows you how to perform these tasks programmatically. For details on granting permissions, see “How to: Configure Authorization for a Web Application.”

To configure the ASP.NET Roles Provider 1. 2.

In Microsoft Visual Studio®, open the Web.config file in the root folder of your application. Add the following markup to the <system.web> section:

<providers> This example uses the ASP.NET SQL Server Roles Provider. To use this provider, you must have created the ASP.NET Roles database in SQL by using the aspnet_regsql.exe tool. To list the users in a role The following code lists all the members of a role called Moderators, and all users who are not members of this role:

[Visual Basic] Dim allUsers As MembershipUserCollection = _ Membership.GetAllUsers() Dim currentUser As MembershipUser For Each currentUser In allUsers If Roles.IsUserInRole(currentUser.UserName, _ "Moderators") Then lblMembers.Text &= currentUser.UserName & "
" Else lblNonMembers.Text &= currentUser.UserName & "
" End If Next [C#] MembershipUserCollection allUsers = Membership.GetAllUsers(); foreach (MembershipUser userCurrent in allUsers) { if (Roles.IsUserInRole(userCurrent.UserName, "Moderators")) { lblMembers.Text += userCurrent.UserName + "
"; } else { lblNonMembers.Text += userCurrent.UserName + "
"; } } To add users to a role The following code adds a user called Sam to a role called Moderators. Note that the code checks that the role exists before adding the user.

[Visual Basic] If Not Roles.RoleExists("Moderators") Then Roles.CreateRole("Moderators") End If Roles.AddUserToRole("Sam", "Moderators") [C#] if (!Roles.RoleExists("Moderators")) Roles.CreateRole("Moderators"); Roles.AddUserToRole("Sam", "Moderators"); To remove users from a role The following code removes a user called Bob from a role called Administrators:

[Visual Basic] Roles.RemoveUserFromRole("Bob", "Administrators")

[C#] Roles.RemoveUserFromRole("Bob", "Administrators");

Deploying a Web Application

Features of the Copy Web Site Utility This document is a copy of the article “Copying Web Sites with the Copy Web Tool,” which you can find in the Microsoft® Visual Studio® 2005 documentation at mshelp://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_vwdcon/html/fb4e125f-6238-48c0a03c-4854bf9895e8.htm. The Copy Web tool allows you to copy files between the current Web site and another site. The Copy Web tool is similar to an FTP utility, but differs in the following ways: • •

It allows you to connect to and copy files between any types of Web sites you can create in Visual Studio, including local Web sites, IIS Web sites, Remote (Microsoft Office FrontPage®) Web sites, and FTP sites. It supports a synchronization feature. This examines the files on both sites and makes sure that all files on both sites are up to date.

You can use the Copy Web tool to move files from your local computer to a staging server or to a production server. The Copy Web tool is especially useful in situations in which you cannot open files from the remote site to edit them. You can use the Copy Web tool to copy the files to your local computer, edit them, and then copy them back to the remote site. You can also use the tool to copy files from a staging server to the production server when you have finished your development.

Source and Remote Sites The Copy Web tool copies files between a source site and a remote site. These terms are used to distinguish the two sites that the tool is working with. The terms are used with specific meanings: •



The source site is the site that you currently have open in Visual Studio. The remote site is the site that you want to copy files to. A remote site can be a location on another computer that you can access using FrontPage Server Extensions or FTP. In those cases, the site is literally remote. However, the remote site can also be another site on your own computer. For example, you can publish from a file system Web site on your computer to a local IIS Web site that is also on your computer. In that case, although the site is local to your computer, it is the “remote site” for purposes of the Copy Web tool.

Note The source site is not necessarily the source for copying. You can copy from the remote site to the source site.

Synchronizing Sites In addition to copying files, the Copy Web tool allows you to synchronize sites. Synchronizing examines the files on the local and remote sites and makes sure that all files on both sites are up to date. For example, if a file on the remote site is more current than the version of the same file on the local site, synchronizing the files copies the remote file to your local site.

Note The Copy Web tool does not merge files that have the same name but different content. In that case, synchronization gives you the opportunity to specify which version of a file you want to keep.

Synchronization makes the tool well suited to a multi-developer environment in which developers keep copies of the Web site on their local computers. Individual developers can copy their latest changes to a shared remote server and at the same time update the local computer with changed files from other developers. A new developer on a project can also quickly get copies of all the files for a Web site by creating a local Web site on his or her own computer and then synchronizing with the site on the shared server.

File Status To synchronize files, the Copy Web tool needs information about the state of the files on both sites. Therefore, the tool maintains information consisting of the files’ timestamps plus additional information required to perform synchronization. For example, the tool maintains a list of when the files were last checked, which enables the tool to determine information such as if a file has been deleted. When you connect to (or refresh) a site, the tool compares the timestamps of the files on both sites and the information it has stored for both sites and reports the state of each file. The following table shows the status of the files.

Status

Description

Unchange d

The file has not changed since the last time the file was copied.

Changed

The file has a timestamp that is newer than the timestamp taken when the file was last copied.

New

The file has been added since the last time the site was copied.

Deleted

The file has been removed since the last time the site was copied. If you select Show Deleted Files in the Copy Web tool, an entry for the file is displayed in the window.

Deploying a Web Application

How to: Deploy a Web Site by Using the Copy Web Site Utility This document is a copy of the article “How to: Copy Web Site Files with the Copy Web Tool,” which you can find in the Microsoft® Visual Studio® 2005 documentation at mshelp://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_vwdcon/html/b819aed4-014b-427ebe80-02317b1bb003.htm. You can use the Copy Web tool in Visual Studio to copy files from a local site to a remote site or vice versa. You can copy selected files individually or copy all files at once. Additionally, you can synchronize two sites, which copies files as required to be sure that both sites have identical copies of all files.

Note You must have sufficient permissions to be able to read, write, create, and delete files on the remote site. If you are unsure of your permissions, check with the administrator for the remote site.

To Connect to a Remote Site

1. 2.

On the Website menu, choose Copy Web Site. The Copy Web window is displayed with files from the currently open Web site in the Source Web Site list. From the Connect to list, select the site to connect to as the remote site. If the site you want to connect to is not in the list, select Connect to and then use the Open Web Site dialog box to connect to the site you want to copy files to or from. When the Copy Web tool opens the remote site, it examines the files on both sites and indicates their status (New, Unchanged, Changed, or Deleted). If there are two different versions of a file, one on the source site and one on the remote site, an arrow points from the newer version to the older version.

Note To see files that have been deleted, select the Show Deleted Files check box. The names of deleted files have a glyph next to them indicating that they have been deleted.

Removing a Connection Connection information is persisted in Visual Studio. (The connection is live only while you are working with a site.) If you do not need to connect to a remote site any more, you can remove the connection information. To remove a connection to a remote site

1. 2.

From the Connect to list, select the connection to remove. Click Disconnect from currently selected remote site.

Copying Files To copy files 1.

2.

Select the file or files you want to copy. Click the copy button between the Source Web Site and Remote Web Site lists, using the button that indicates the direction in which you want to copy. To copy the recent version of a file to the site with the older version, select the synchronize button.

The status pane at the bottom of the window displays the results of the copy operation.

Note Files that have not changed are not copied.

Deploying a Web Application

Features of the Publish Web Site Utility This document contains extracts from the article “Publishing Web Sites,” which you can find in the Microsoft® Visual Studio® 2005 documentation at mshelp://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_vwdcon/html/c8048c31-012b-4718b8ac-06a2dd41c137.htm. Microsoft Visual Web Developer™ allows you to publish your Web sites, which compiles the sites and copies the output to a location you specify, such as a production server. Publishing accomplishes the following tasks: • •

Precompiles each page, the source code in the App_Code folder, and so on Creates executable output and writes it to a target folder

Note The Publish Web utility is not available in Visual Web Developer Express Edition.

Publishing offers the following advantages over simply copying the Web site to a target Web server: • • •

The precompilation finds any compilation errors throughout the site and identifies errors in the configuration file. Initial response speed for individual pages is faster because the pages are already compiled. (If you copy pages to a site instead of precompiling them, the pages are compiled and the compiled code is loaded on first request.) No source code is deployed with the site, providing you with some security for your files. You can publish the site with markup protection, which compiles .aspx files, or without markup protection, which copies .aspx files to the site as is and allows you to change their layout after deployment.

Precompilation The first step in publishing is to precompile the Web site. Precompilation for publishing, which is somewhat different than precompiling in place (building), performs essentially the same compilation process that normally occurs when a page is compiled dynamically upon being requested in a browser. The precompiler produces assemblies from the pages (both the markup and the code). It also compiles files in the App_Code, App_GlobalResources, App_LocalResources, and App_Themes folders. You can compile both single-file ASP.NET pages and code-behind pages.

Precompilation vs. Building The precompilation step in publishing differs from the compilation that occurs when you build a Web site while testing it. Building compiles the site or the current page and any of its dependent files and then runs it. The build process is a form of testing, and does not produce output that you can deploy. Precompilation during publishing, on the other hand, creates output in a specified folder that you can, in turn, deploy to a production server.

Writing Precompilation Output When the precompilation process is finished, the resulting output is written to a folder that you specify. You can write the output to any folder that is accessible to you in the file system by using FTP, or across HTTP. You must have appropriate permissions to be able to write to the target site.

Note The publishing process deploys only the files in your Web site folders and subfolder. It does not deploy the machine.config file. Therefore, the configuration of the target Web server might be different than it is on your computer, which might affect the behavior of your application.

You can specify a target folder on a staging server or production server, or you can write the output to a folder on your local computer. If you specify a folder on a production server, you can precompile and deploy in one step. If you choose to write the output to a folder that is not part of a Web site, you can copy the output to the server in a separate step. The output of the compilation process includes the compiled assemblies for any code or pages. If you choose the option to allow the precompiled site to be updateable, the code-behind classes, if any, for your .aspx, .asmx, and .ashx files are compiled into assemblies. However, the .aspx, .asmx, and .ashx

files themselves are copied as-is to the target folder so that you can make changes to their layout after deploying the site. For updateable precompiled sites, the code in single-file pages is not compiled into an assembly, but is instead deployed as source code. Static files are not compiled; instead, they are copied as is to the output folder. Static files include graphics, .htm or .html files, text files, and so on. If an error occurs during precompilation, it is reported to you in the Output window and in the Error List window. Errors during precompilation will prevent the site from being compiled and published.

Deploying a Web Application

How to: Precompile and Deploy a Web Site by Using the Publish Web Site Utility This document contains extracts from the article “How to: Publish Web Sites (Visual Studio),” which you can find in the Microsoft® Visual Studio® 2005 documentation at mshelp://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_vwdcon/html/d0a1a20f-15be-49409485-cb8e4aa8181b.htm. Publishing a Web site compiles the executable files in the Web site into object code and then writes the output to a folder that you specify. To publish a Web site

1. 2. 3.

On the Build menu, click Publish Web Site. The Publish Web Site dialog box appears. Type the path of the folder you want to publish to, or click the ellipsis button (…) to browse for local IIS Web sites, remote Web sites, or FTP locations.

You can write the Web site output to a local or shared folder, to an FTP site, or to a Web site that you access with a URL. You must have create and write permissions in the target folder. If you want to be able to change the layout (but not the code) for aspx files after publishing the site, select Allow this precompiled site to be updateable.

Deploying a Web Application

Features of Windows Installer Setup Projects This document contains extracts from the article “Setup Projects,” which you can find on the MSDN® Web site. Setup projects allow you to create installers to distribute an application. The resulting Microsoft® Windows® Installer .msi file contains the application, any dependent files, information about the application such as registry entries, and instructions for installation. When the .msi file is distributed and run on another computer, you can be assured that everything necessary for installation is included; if for any reason the installation fails (for example, the target computer does not have the required operating system version), the installation will be rolled back and the computer returned to its preinstallation state. There are two types of setup projects in Microsoft Visual Studio®: Setup projects and Web Setup projects. The distinction between Setup projects and Web Setup projects is where the installer will be deployed: Setup projects install files into the file system of a target computer; Web Setup projects install files into a virtual directory of a Web server. In addition, a Setup Wizard is available to simplify the process of creating a Setup project or a Web Setup project.

Deploying a Web Application

How to: Create a Windows Installer Package for Deploying a Web Application The simplest way to create a Microsoft® Windows® Installer Package for deploying a Web application is to create a Web Setup project in the Microsoft Visual Studio® 2005 integrated development environment (IDE) and then add the project output of the Web application to be deployed to the Web Setup project.

To create a Web Setup project 1.

2. 3. 4. 5.

Using Visual Studio 2005, open the solution containing the Web site to be deployed. On the File menu, point to Add and then click New Project. The Add New Project dialog box appears. Expand the Other Project Types node in the Project types tree view and then click Setup and Deployment. In the Templates section of the Add New Project dialog box, click Web Setup Project. Provide a meaningful name and choose a location for the new project, and then click OK.

To add Web site output to a Web Setup project 1.

2. 3. 4. 5.

In Solution Explorer, right-click the new Web Setup project that you have just added to the solution. Point to Add on the shortcut menu and then click Project Output. The Add Project Output Group dialog box appears. Click Content Files. Ensure that the Web site project is selected in the Project drop-down list, and that (Active) is selected in the Configuration drop-down list. Click OK.

To set properties of the Web Setup project •

Click the Web Setup project in Solution Explorer, and then use the Properties window to set the following properties:  Author:  Description:  Manufacturer:  Product Name:  Title: Setup Application for

To define the user interface for a Web Setup project

1. 2. 3. 4. 5.

In Solution Explorer, right-click the Web Setup project, point to View on the shortcut menu, and then click User Interface. The User Interface designer appears. Right-click the Start node in the Install section of the tree-view and then click Add Dialog on the shortcut menu. The Add Dialog dialog box appears. Click License Agreement and then click OK. Drag the License Agreement node into the tree-view so that it appears directly below the Welcome item. Use the Properties window to set the LicenseFile property to a rich-text format file that contains the license agreement for your Web application.

To build the Windows Installer package



Right-click the Web Setup project in Solution Explorer, and then click Build.

After the Windows Installer package has been created, you can copy the installer files that it creates to the destination Web server and then run the package to install the Web site.

Note You can add other features to the Windows Installer, such as custom actions, launch conditions, file-type associations, and registry settings. For more details of these features, review the Visual Studio 2005 documentation.

Making Web Applications Available to Mobile Devices

How to: Detect and Redirect Mobile Devices

Mobile devices typically have much smaller screens than conventional desktop and laptop computers, which means that they might not display in a usable way an ordinary Web Form designed to be displayed by a desktop computer. Also, some mobile devices have gray-scale or two-tone screens and might have limited network connectivity. To support mobile devices, it is therefore sensible to create two versions of each Web form, one for desktop computers and one for mobile devices.

When a mobile device makes a request to a Web Form, it should be detected and redirected to the Mobile Web Form. Use the HttpBrowserCapabilities class to determine the source of a request. The Request.Browser method returns an HttpBrowserCapabilities object for the browser that requested the page. To redirect a mobile device to a Mobile Web Forms page Insert the following code into the Web Form designed for desktop computers. This example redirects mobile devices to a page called default.aspx, in the Mobile subfolder.

[Visual Basic] Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles Me.Load If Request.Browser.IsMobileDevice Then Response.Redirect("Mobile/default.aspx") End If End Sub [C#] protected void Page_Load(object sender, EventArgs e) { if (Request.Browser.IsMobileDevice) Response.Redirect("Mobile/default.aspx"); } Some mobile devices do not permit you to use relative URLs such as Mobile/default.aspx. You can ensure that requests for these devices are redirected correctly by configuring the Web application as follows. To configure the Web application to redirect with fully qualified URLs Insert the following markup into the Web.config file:

<system.web>

Making Web Applications Available to Mobile Devices

How to: Browse Mobile Web Pages with Specific Device Emulators Microsoft® Visual Studio® 2005 includes Microsoft Device Emulator 1.0 to help developers write applications for mobile devices such as Pocket PCs and mobile phones. Device Emulator can be used to simulate devices running Microsoft Windows® CE 5.0, Microsoft Pocket PC 2003 SE, and Microsoft Smartphone 2003 SE. This article explains how to browse a Microsoft ASP.NET application on a development computer, with an emulator installed on the same computer, using Microsoft ActiveSync® 4.0 to make the connection. The host computer and the emulator must already have been configured, as described in “How to: Configure Device Emulator 1.0 to Connect to an ASP.NET Application.” To browse an application with the Device Emulator, you must know the IP address of the host computer.

To obtain the IP address of the host computer 1. 2. 3.

On the host computer, open a command prompt. Type the following command:

ipconfig

The computer’s IP address, subnet mask, and default gateway address are returned.

To browse to a Web page by using the Pocket PC 2003 SE Emulator

1. 2. 3. 4. 5.

If ActiveSync is not already running and visible in the notification area, start it from the Programs menu. In Visual Studio, on the Tools menu, click Device Emulator Manager. In the Device Emulator Manager, select Pocket PC 2003 SE Emulator. On the Actions menu, click Connect. The emulator starts. In the Device Emulator Manager, on the Actions menu, click Cradle. ActiveSync connects to the emulator and synchronizes.

6. 7.

Once the synchronization is complete, in the emulator, click Start, and then click Internet Explorer. In the Address box, type the address

http://x.x.x.x/page.aspx where x.x.x.x is the IP address you obtained for the host computer, and page. aspx is the file name of the page you want to browse to.

To browse to a Web page by using the Smartphone 2003 SE Emulator

1. 2. 3. 4. 5. 6. 7.

8. 9.

If ActiveSync is not already running and visible in the notification area, start it from the Programs menu. In Visual Studio, on the Tools menu, click Device Emulator Manager. In the Device Emulator Manager, select Smartphone 2003 SE Emulator. On the Actions menu, click Connect. The emulator starts. In the Device Emulator Manager, on the Actions menu, click Cradle. ActiveSync connects to the emulator and synchronizes. When the synchronization is complete, in the emulator, click the left button to open the Start menu. Use the down button to move to Microsoft Internet Explorer. Click the center button to open Internet Explorer. Click the right button to open the menu. Click the center button to open the Address Bar. In the Address Bar, type the address

http://x.x.x.x/page.aspx

where x.x.x.x is the IP address of the host computer and page. aspx is the file name of the page you want to display. 10. Use the left button to choose Go. The Web page appears.

Making Web Applications Available to Mobile Devices

How to: Design and Implement a Mobile Web Form Microsoft® Visual Studio® 2005 provides the Microsoft ASP.NET Mobile Designer for designing and creating Mobile Web Forms. You can add a Mobile Web Form to any Visual Studio ASP.NET project. To add a Mobile Web Form to a Web project

1. 2.

Right-click the project and then click Add New Item. In the Add New Item dialog box, select Mobile Web Form. Give the new page the name of your choice and then click Add. The page is added and displayed in the Visual Studio Source view.

Every Mobile Web Form includes one or more <mobile:Form> tags. Each of these tags defines a form that can be displayed by the page. Only one form—the active form—will be displayed at a time by the mobile device. To add a second <mobile:Form> to the page



In Design view, drag a Form control from the Mobile Web Forms section of the Toolbox onto the page. or Add the following markup to the page:



<mobile:Form ID="SecondForm" Runat="server">

To activate the second form when the user presses a button

1. 2. 3.

In Design view, drag a Command control from the MobileWeb Forms section of the Toolbox onto the page. Double-click the Command object to create the default click event handler. Add the following code to this handler:

[Visual Basic] Me.ActiveForm = SecondForm [C#] this.ActiveForm = SecondForm;

Within a single form you can use pagination to present a lot of information over several screens. This is useful, for example, if you have a long list of products, and the device can display only 10 lines at a time. To use pagination with a list of items 1.

2. 3. 4.

In Design view, select the form in which you want to use pagination. In the Properties window, set the Paginate property to true, set the PagerStyle.NextPageText property to Next, and then set the PagerStyle.PreviousPageText property to Previous. In Design view, drag a List control from the Mobile Web Forms section of the Toolbox onto the form. Select the new list object. In the Properties window, set the ItemsPerPage property to 10. Add items to the Items collection.

When the form is displayed, if there are more than 10 items in the list, Next and Previous links appear, enabling the user to navigate through the list.

Making Web Applications Available to Mobile Devices

Mobile Controls Microsoft® ASP.NET 2.0 includes a wide variety of controls for use on Mobile Web Form pages. These controls are optimized for use on many types of mobile devices, such as phones and Pocket PCs. The controls adapt to the capabilities of the device displaying the Web page. For example, they render differently on gray-scale and color displays. The following controls are available:

• • • • • • • • • • • • • • • • •

Form: This control contains child controls for displaying information or gathering user input. Each page can have multiple forms, but only one form is active at a time. Panel: Use this control to group other child controls. The child controls inherit default property values from the parent panel. You can also use a panel to modify several controls in a single operation. Label: This control displays text on the page. If the label has an ID, it can be programmatically modified as the page is rendered. TextBox: Use this control to gather input from the user. TextView: This control is similar to a Label control but is designed to support longer text strings. This control supports pagination, and long text strings will automatically be spread over several pages, as long as the form has been configured to enable this feature. Command: This control is the equivalent of a Button control on a Web Form. Link: This control represents a link to another control on the Mobile Form or any other URL. PhoneCall: This control allows users with telephony devices to place a call to a number you specify. If the device is not able to place calls, alternate text can been displayed. Image: This control displays an image on the page. List: This control displays a list of text items. You can bind a List control to a data source, such as a database table or array, to display items at run time. Alternatively, you can populate the list at design time by using the Items collection. SelectionList: This control enables the user to select one or more items from a list. You can determine which item the user has selected by using the SelectionList.Selection.Text property. ObjectList: This control displays a list of items such as the List control. However, each item can be any type of object, including an instance of a custom class. This control is useful when you need to store information that is more complex than simple text and values. DeviceSpecific: This control enables you to display different content, depending on the capabilities of the device. See the resource “How to: Design Device Specific Features for a Mobile Web Form” for more details. StyleSheet: Use this control to format a Mobile Form page or control in much the same way as a StyleSheet on a static HTML Web page. Calendar: This control enables the user to select a day, week, or month of the year. You can set which of these is selected by using the SelectionMode property and determine the value the user selected by using the SelectedDate property. AdRotator: This control displays a randomly selected advertisement. Validation Controls: Use these controls to check the validity of user input on a Mobile Form. The RequiredFieldValidator, for example, ensures that the user does not leave a field blank. If the validation test is not satisfied when the user submits the form, a message is displayed describing the error.

Making Web Applications Available to Mobile Devices

How to: Design Device Specific Features for a Mobile Web Form Mobile devices can vary greatly in their capabilities. For example, some devices can send e-mail messages, some can place phone calls, some have color screens, and some have gray-scale screens. When you are designing a Web page and you do not know what type of device the user will use, you should cater to all possible types of devices. Microsoft® ASP.NET Mobile Forms enable you to specify different properties for a tag, depending on the capabilities of the device. You can do this by using the DeviceSpecific/ Choice construct. To specify different attribute values based on filters 1. 2.

In Source view, locate the control that should change depending on the device used to view it. Add and tags. The following example shows how to display different images for different types of devices in an image control:

<mobile:Image runat=server> The Filter attribute in each tag can be used in one of two ways. It can either specify the name of a method on the Mobile Form—which you must write—or the name of a device filter in the Web.config file. To use a method on the Mobile Form as a filter



If the Filter attribute specifies the name of a method in the Mobile Form, the method must return a Boolean value and match the signature shown by the following example:

[Visual Basic] Public Function isColor(ByVal capabilities As MobileCapabilities, _ ByVal optionalArgument As String) As Boolean If capabilities.IsColor Then isColor = True Else isColor = False End If End Function [C#] public bool isColor(System.Web.Mobile.MobileCapabilities capabilities, string optionalArgument) { if (capabilities.IsColor) return true;

}

return false;

If the Filter attribute does not specify the name of a method on the page, it must specify the name of a filter defined in the Web.config file. These filters can be of two types: comparison filters, in which a capability is checked against the Argument attribute of the Choice element; and evaluator delegate filters, which specify a class and method used to perform the test.

To use a Comparison Filter in the Web.config file 1. 2.

Edit the Web.config file. Add the following markup to the file:

<system.web> <deviceFilters>

This example tests for the IsColor capability. For more information, see the “Device Capability Names” section later in this resource.

To use an Evaluator Delegate Filter in the Web.config file 1. 2.

Edit the Web.config file. Add the following markup to the file:

<system.web> <deviceFilters> Device Capability Names When using Comparison Filters, you must specify a capability from the Capabilities Dictionary for the compare attribute. Capabilities you can test for include the following:

• • • • • • •

CanInitiateVoiceCalls: The device can place telephone calls. CanSendMail: The device can send e-mail messages. HasBackButton: The browser has a Back button for displaying the previous page. IsColor: The device has a color display. IsMobileDevice: The device is a Pocket PC, mobile phone, or other mobile device. MobileDeviceManufacturer: The name of the device manufacturer. MobileDeviceModel: The model name of the device. This, with the MobileDeviceManufacturer capability, enables you to add features that are specific to particular piece of client hardware. ScreenCharactersHeight and ScreenCharactersWidth: The maximum size of the device screen, specified in characters. ScreenPixelsHeight and ScreenPixelsWidth: The maximum size of the page, specified in pixels. SupportsBodyColor: The device can display a background color for the page. SupportsBold: The device can display text in bold format. SupportsFontColor: The device can display colored fonts. SupportsItalic: The device can display text in italic format.

• • • • • •

Making Web Applications Available to Mobile Devices

How to: Configure Microsoft Device Emulator 1.0 to Connect to an ASP.NET Application Microsoft® Visual Studio® 2005 includes Microsoft Device Emulator 1.0 to help developers write applications for mobile devices such as PDAs and mobile phones. Device Emulator can be used to simulate devices running Microsoft Windows® CE 5.0, Microsoft Pocket PC 2003 SE, and Microsoft Smartphone 2003 SE. Device Emulator can connect only to Microsoft ASP.NET applications running in IIS, not in the ASP.NET Development Web server. Therefore, you must configure IIS to host your application: To configure IIS to host your ASP.NET application 1.

2. 3. 4.

On your development computer, open a command prompt. Type the following command to start the IIS management console as Administrator:

Runas /user:administrator "mmc %windir%\system32\inetsrv\iis.msc" In the IIS management console, in the Web Sites section, right-click the Default Web Site object and then click Properties. In the Default Web Site Properties dialog box, click the Home Directory tab. In the Local Path box, type the path to the folder where your ASP.NET application has been saved and then click OK.

Microsoft ActiveSync® 4.0 is used to make a connection from the Device Emulator to the Web site as if the device were cradled. Therefore, the network adapter in the Device Emulator is not necessary:

To disable the network adapter in the Device Emulator

1. 2.

In Visual Studio, on the Tools menu, click Options. In the Options dialog box, expand Device Tools and then click Devices.

3. 4. 5.

In the Devices list, select the emulator you want to use and then click Properties. In the Emulator Properties dialog box, click Emulator Options. On the Network tab, clear all check boxes and then click OK three times.

The connection must be made with the DMA protocol.

To configure ActiveSync to use DMA

1. 2. 3.

Open ActiveSync from the Start menu. On the File menu, click Connection Settings. Select the Allow connections to one of the following check box. Select DMA from the list.

If you are using the Pocket PC 2003 SE Emulator, you must configure the device to connect to the Work network for connections to the Internet.

To configure options in the Pocket PC 2003 SE Emulator

1. 2. 3. 4. 5.

In the Pocket PC Emulator, click Start and then click Settings. On the Connections tab, double-click Connections. On the Advanced tab, click Select Networks. Select My Work Network in both drop-down lists. Click OK in the top-right corner twice and then close the Connections dialog box.

To make a connection to the Device Emulator with ActiveSync

1. 2. 3. 4. 5.

If ActiveSync is not already running, open it from the Program menu. In Visual Studio, on the Tools menu, click Device Emulator Manager. In the Device Emulator Manager, right-click the emulator you want to use and then click Connect. The emulator starts. In the Device Emulator Manager, on the Actions menu, click Cradle. The ActiveSync Connection Wizard starts and guides you through making a connection to the host computer.

Note If Microsoft Office Outlook® is not installed, do not configure ActiveSync to synchronize the Inbox in the Connection Wizard.

Related Documents

70528 Notes
June 2020 0
Notes)
June 2020 31
Notes
June 2020 29
Notes
November 2019 46
Notes
August 2019 65
Notes
June 2020 27