Sie sind auf Seite 1von 13

2 Table of Contents

Table of Contents

Creating ASP.NET Web Applications with C# - Part 2 ............................................................................ 3


Exercise 1 State Management .............................................................................................................................4
Exercise 2 Data Access in Web Forms Pages .....................................................................................................7
Exercise 3 Deploying ASP.NET Web Application ...........................................................................................13
Creating ASP.NET Web Applications with C# - Part 2 3

Creating ASP.NET Web Applications


with C# - Part 2

Objectives After completing this lab, you will be able to:


„ Use State Management in Web applications
„ Use Data access in Web forms
„ Deploy the Web application

Scenario In these labs, you will create a Web application to manage a list of products as
part of a Sales Order System. You will also learn how to create and deploy this
Web application. To sign into the Sales Order System, you need to enter the
User ID and password in the login page. You will first create the login page,
which is an ASP.NET page (Web form) using ASP .NET server controls.
After successfully logging into the Sales Order System, the user can view
details of existing products and modify the same. Finally you will deploy this
application to a web server.
The working solution and associated files for these labs are located at
C:\Microsoft Hands-On-Lab\DEV-HOL03\Solution.
This lab is the second part of two. It uses files created in part one. It is strongly
recommended that the two lab sections be done in order.

Estimated time to
complete this lab: 45
minutes
4 Creating ASP.NET Web Applications with C# - Part 2

Exercise 1
State Management

Scenario
In this exercise, you will use both Client-side and Server-side state management options to preserve
the values of the controls between round trips.

Tasks Detailed steps

1. Use the ViewState object to a. Select Start | All Programs | Visual Studio .NET 2003 | Visual
preserve the Password Studio .NET 2003.
value in the client side. b. Open the base web application for modification by selecting File |
As Web applications are Open | Project.
stateless between server round c. Navigate to C:\Microsoft Hands-on-Lab\DEV-HOL03\Starter
trips the values of a page's Solution\Lab3-CS-Starter-2.
variables and controls are not
preserved. We need to preserve d. Select Lab3-CS-Starter-2.sln and click Open.
these values and they can be e. To view Login.aspx code, in the Solution Explorer, right-click
stored in the client or server. To Login.aspx and select View Code.
store in client, ViewState is f. To preserve value of the Password field using the ASP.NET
used. ViewState object, add the following code at the end of the
btnSignin_Click method.
private void btnSignin_Click(object sender,
System.EventArgs e)
{
.......
.......
.......
//Debugging code
Debug.WriteLine(txtUserID.Text);
Debug.WriteLine(txtPassword.Text);
Debug.Write(lblResult.Text);

//Client side State management using ViewState


ViewState["Password"] = txtPassword.Text;
}
g. Select View | Designer or press SHIFT+F7.
h. Double-click Restore and add the following code to the
btnRestore_Click event handler function as shown below:
private void btnRestore_Click (object sender,
System.EventArgs e)
{
//Client side State management using ViewState
lblResult.Text = "The password you entered is " +
(string) ViewState["Password"];
}
i. Select Debug | Start or press F5.
j. Enter John in User ID and mypassword in Password.
k. Click Sign In.
The server round trip occurs and the value of the Password field is
preserved in ViewState object but the txtPassword field is empty.
Creating ASP.NET Web Applications with C# - Part 2 5

l. Click Restore
You can see The password you typed is mypassword in lblResult.
m. Close the Web browser.
2. Use the Session object to a. Select View | Code or press F7.
preserve the User ID value b. To preserve the value of the User ID field on the server side using the
in the server side. ASP.NET session, add the following code in btnSignin_Click method:
private void btnSignin_Click(object sender,
System.EventArgs e)
{
//Add user authentication logic here
if (txtUserID.Text.Length >= 4 &&
txtPassword.Text.Length >= 4 &&
txtUserID.Text.StartsWith("J"))
{
lblResult.Text= "Valid user!";

//Server side State management using


Session
Session["UserID"] = txtUserID.Text;
Response.Redirect("LoginDemo.aspx");
}
else
{ lblResult.Text = "Invalid user!";
}
//Debugging code
Debug.WriteLine(txtUserID.Text);
Debug.WriteLine(txtPassword.Text);
Debug.Write(lblResult.Text);

//Client side State management using


ViewState
ViewState["Password"] = txtPassword.Text;
}
To access this session value in another page, create a new page (Web
form).
c. To view Solution Explorer, select View | Solution Explorer menu
command or press CTRL+ALT+L.
d. Select Project | Add Web Form.
Add the New Item dialog box appears.
e. Enter LoginDemo.aspx in the Name textbox and click Open.
LoginDemo.aspx is created and added to the project.
To display User ID value, add a new Label control to this form:
f. Select View | Toolbox or press CTRL+ALT+X.
g. Click Web Forms tab to see Web form controls.
h. Select Label control in Web Forms tab of Toolbox.
i. Drag and drop it on to the Design view of LoginDemo.aspx page.
j. Set the following properties for the Label. (To view the Properties
window of a control, click the control select View | Properties
Window menu command or press F4):
ƒ ID - lblUserID
ƒ Text - You are logged in as :
6 Creating ASP.NET Web Applications with C# - Part 2

ƒ Font (Expand the Font node)


ƒ Bold - True
ƒ Name - Tahoma
ƒ Size - X-Small
k. Select View | Code or press F7.
l. Add the following code in Page_Load method, which retrieves the
User ID value from the session created in the Login.aspx page:
private void Page_Load(object sender,
System.EventArgs e)
{
// Put user code to initialize the page here
if (!Page.IsPostBack)
{
//Server side State management using
Session
lblUserID.Text = lblUserID.Text+" "+
Session["UserID"];
}
}
m. Select Debug | Start or press F5.
n. Enter John in User ID and mypassword in Password.
o. Click Sign In.
Now, the User ID value is stored in Session.
The user is redirected to another page LoginDemo.aspx, where the
following message is displayed: You are logged in as : John
p. Close the Web browser.
Creating ASP.NET Web Applications with C# - Part 2 7

Exercise 2
Data Access in Web Forms Pages

Scenario
This exercise explains how to use data access in Web form and ASP.NET DataGrid control to bind
to the results of SQL queries. You will also learn to use ADO.NET objects, bind data to DataGrid
and customize the data display.

Tasks Detailed steps

1. Use SqlConnection class to a. Add the following code at the top in the LoginDemo page, which
create a connection to allows you to use SqlConnection class:
Northwind database. using System.Data.SqlClient;
b. Add a class-level variable of type SqlConnection as shown below:
public class LoginDemo : System.Web.UI.Page
{
private SqlConnection myConnection;
............
............
c. Add the following code in Page_Load method, which creates a
SqlConnection object to connect to the local SQL server’s Northwind
database (Snippet 3).
private void Page_Load(object sender,
System.EventArgs e)
{
// Put user code to initialize the page here
// Create a connection to the Northwind database
myConnection = new
SqlConnection("server=localhost;database=northwind
;Trusted_Connection=yes");
............
............
2. Fetch data from a Products a. Click View | Designer or press SHIFT+F7.
table and how to display it b. Select View | Toolbox or press CTRL+ALT+X.
in a DataGrid.
c. Select DataGrid control in Web Forms tab of Toolbox.
d. Drag and drop it on to the Design view of LoginDemo.apx page.
e. Set the following properties for the DataGrid. (To view the Properties
window of a control, click the control and select View | Properties
Window or press F4).
ƒ ID - dgProducts
ƒ BackColor - LemonChiffon
ƒ BorderColor - Black
ƒ BorderStyle - Solid
ƒ BorderWidth - 2px
ƒ DataKeyField - ProductID
ƒ Font (Expand the Font node)
ƒ Name - Arial
8 Creating ASP.NET Web Applications with C# - Part 2

ƒ Size - X-Small
ƒ HeaderStyle (Expand the HeaderStyle node)
ƒ BackColor - Khaki
ƒ Font (Expand the Font node)
ƒ Name - Arial
ƒ Size - X-Small
ƒ Width - 100%
f. Select View | Code or press F7.
g. To get data from the Products table and bind it to DataGrid, add the
following method after the Page_Load event handler: (Snippet 4)
private void Page_Load(object sender,
System.EventArgs e)
{
...
}
public void BindGrid(string sortfield)
{
//Create DataAdapter to fetch data from Prodcuts
table
SqlDataAdapter myCommand = new
SqlDataAdapter("select * from Products",
myConnection);

//Create dataset and fill it with Product data


DataSet ds = new DataSet();
myCommand.Fill(ds, "Products");

//Bind Product data to Datagrid


DataView Source =
ds.Tables["Products"].DefaultView;
Source.Sort = sortfield;
dgProducts.DataSource = Source;
dgProducts.DataBind();
}
h. Bind the DataGrid when the page is loaded by adding the following
line of code to the Page_Load method:
private void Page_Load(object sender,
System.EventArgs e)
{
// Put user code to initialize the page here
// Create a connection to the Northwind database
myConnection = new SqlConnection

("server=(local);database=Northwind;User
ID=sa;Password=;");
if (!Page.IsPostBack)
{
// Server side State management using
Session
lblUserID.Text=lblUserID.Text+" "+
Session["UserID"];
BindGrid("ProductID");
}
}
i. Select Debug | Start or press F5.
j. Enter John in User ID and mypassword in Password.
Creating ASP.NET Web Applications with C# - Part 2 9

k. Click Sign In.


The user is redirected to another page LoginDemo.aspx, where the
Products data is displayed in the DataGrid.
l. Close the Web browser.
3. Use paging and sorting Add paging functionality to the DataGrid:
features of DataGrid a. Select View | Designer or press SHIFT+F7.
control.
b. Click the DataGrid control and select View | Properties Window or
press F4. Set the following properties:
ƒ AllowPaging - True
ƒ Page Size - 15
ƒ PagerStyle (Expand the PagerStyle node)
ƒ Mode - NumericPages
ƒ VerticalAlign - Middle
Add code for DataGrid paging functionality:
c. In the Properties Window, click the button to display a list of
DataGrid events.
d. Double-click PageIndexChanged item.
Visual Studio .NET switches to the code-behind page and creates an event
handler function named dgProducts_PageIndexChanged.
e. Add the following code in dgProducts_PageIndexChanged method :
private void dgProducts_PageIndexChanged (Object
sender, DataGridPageChangedEventArgs e)
{
//Set current page of Datagrid to selected
page
dgProducts.CurrentPageIndex =
e.NewPageIndex;
BindGrid("ProductID");
}
f. Select Debug | Start or press F5.
g. Enter John in User ID and mypassword in Password.
h. Click Sign In.
You are redirected to another page LoginDemo.aspx, where the Products
data is displayed in the DataGrid containing the page numbers.
i. Click page numbers to navigate to various pages.
j. Close the Web browser.
Add sorting functionality to the DataGrid:
k. Select View | Designer or press SHIFT+F7.
l. Click the DataGrid control and select View | Properties Window or
press F4.
m. Click the button to display a list of DataGrid properties.
n. Set the following properties:
ƒ AllowSorting - True
o. Click the button to display a list of DataGrid events
p. Double-click SortCommand item.
Visual Studio .NET switches to the code-behind page and creates an event
10 Creating ASP.NET Web Applications with C# - Part 2

handler function named dgProducts_SortCommand


q. Add the following code in dgProducts_ SortCommand method :
private void dgProducts_ SortCommand (Object
sender, DataGridSortCommandEventArgs e)
{
//Bind Datagrid by specifying field to sort
BindGrid(e.SortExpression);
}
r. Select Debug | Start or press F5.
s. Enter John in User ID and mypassword in Password.
t. Click Sign In.
You are redirected to another page LoginDemo.aspx, where the Products
data is displayed in the DataGrid containing column names, which are now
hyperlinks.
u. Click any column name to sort data displayed in DataGrid by that
column.
v. Close the Web browser.
4. Add a custom column to Add a custom column to the DataGrid:
DataGrid control and use a. Select View | Designer or press SHIFT+F7.
the in-place editing feature
of DataGrid. b. Click the HTML tab (at the bottom of the page) to view the contents of
the page.
c. Add the following code between <asp:Datagrid > and
</asp:datagrid> elements. This code creates a custom column named
Edit of type LinkButton (Snippet 5):
<asp:datagrid id="dgProducts"
…………………………………………………………… >
<HeaderStyle …………………………… </HeaderStyle>
<PagerStyle …………………………… </PagerStyle>

<Columns>
<asp:EditCommandColumn ButtonType="LinkButton"
UpdateText="Update" CancelText="Cancel"
EditText="Edit"><ItemStyle
Wrap="False"></ItemStyle>
</asp:EditCommandColumn>
</Columns>

</asp:Datagrid>
d. Click the Design tab (at the bottom of the page).
e. Select Debug | Start or press F5.
f. Enter John in User ID and mypassword in Password.
g. Click Sign In.
You are redirected to another page LoginDemo.aspx, where the Products
data is displayed in the DataGrid with new column Edit.
h. Close the Web browser.
To display data updated message to the user, add a Label control:
i. Select View | Designer or press SHIFT+F7.
j. Select View |Toolbox or press CTRL+ALT+X.
k. Click Web Forms tab to see Web form controls.
l. Select Label control in Web Forms tab of Toolbox and drag it above
Creating ASP.NET Web Applications with C# - Part 2 11

the DataGrid in the Design view of LoginDemo.aspx page.


m. Click the button to display a list of Label properties (To view the
Properties window of a control, click the control and select View |
Properties Window menu command or press F4).
n. Set the following properties for the Label.
ƒ ID - lblMessage
ƒ Text - “” (Clear the text)
ƒ Font (Expand the Font node)
ƒ Bold - True
ƒ Name - Tahoma
ƒ Size - X-Small
To add edit, update and cancel update functionalities to the DataGrid:
o. Click the DataGrid control and select View | Properties Window.
p. Click the button to display a list of DataGrid events
q. Double-click EditCommand item.
Visual Studio .NET switches to the code-behind page and creates an event
handler function named dgProducts_EditCommand
r. Select View | Designer or press SHIFT+F7.
s. Click DataGrid control and select View | Properties Window.
t. Double-click CancelCommand item.
Visual Studio .NET switches to the code-behind page and creates an event
handler function named dgProducts_CancelCommand
u. Select View | Designer or press SHIFT+F7.
v. Click the DataGrid control and select View | Properties Window.
w. Double-click UpdateCommand item.
Visual Studio .NET switches to the code-behind page and creates an event
handler function named dgProducts_UpdateCommand
x. Add the following methods, which allow Edit, Update and Cancel
functionalities within the DataGrid (Snippets 6, 7, and 8):
private void dgProducts_EditCommand (Object sender,
DataGridCommandEventArgs e)
{
//Set the DataGrid's EditItemIndex to the index
selected by the user
dgProducts.EditItemIndex = (int)e.Item.ItemIndex;
BindGrid("ProductID");
}

private void dgProducts_CancelCommand (Object


sender, DataGridCommandEventArgs e)
{
//Set the DataGrid's EditItemIndex to the -1 to
cancel the update
dgProducts.EditItemIndex = -1;
BindGrid("ProductID");
}

private void dgProducts_UpdateCommand (Object


sender, DataGridCommandEventArgs e)
{
12 Creating ASP.NET Web Applications with C# - Part 2

//Create an update command, add parameters to


it and execute the command
String updateCmd = "UPDATE Products SET
UnitsInStock = @UnitsInStock where "+
"ProductID = " +
dgProducts.DataKeys[(int)e.Item.ItemIndex];
SqlCommand myCommand = new
SqlCommand(updateCmd, myConnection);
myCommand.Parameters.Add(new
SqlParameter("@UnitsInStock",
SqlDbType.Int, 4));
myCommand.Parameters["@UnitsInStock"].Value =
((System.Web.UI.WebControls.TextBox)
e.Item.Cells[7].Controls[0]).Text;

myCommand.Connection.Open();

try
{
myCommand.ExecuteNonQuery();
lblMessage.Text= lblMessage.Text=
"<b>Product " +
dgProducts.DataKeys[(int)e.Item.ItemIndex]
+" is updated</b><br>" ;

dgProducts.EditItemIndex = -1;
}
catch (Exception exc)
{
lblMessage.Text = "ERROR: "+ exc.Message;
}

myCommand.Connection.Close();

BindGrid("ProductID");
}
y. Select Debug | Start or press F5.
z. Enter John in User ID and mypassword in Password.
aa. Click Sign In.
You are redirected to another page LoginDemo.aspx, where the Products
data is displayed in the DataGrid.
bb. Click Edit link in any row in the DataGrid.
Your DataGrid is in editable format
You can see that the row is in edit mode, where you can update the details
of a ProductID.
cc. Change UnitInStock value to a positive integer value.
dd. Click Update link of that row.
You get a message displaying Product <xxx> is updated in the lblMessage
control.
ee. Close the Web browser.
Creating ASP.NET Web Applications with C# - Part 2 13

Exercise 3
Deploying ASP.NET Web Application

Scenario
You can use XCOPY or FTP to deploy an ASP.NET application on to a server. You also can use
Microsoft Visual Studio .NET 2003 IDE to deploy a Web Application.
In this exercise, you will learn how to deploy Web application from within the Microsoft Visual
Studio .NET 2003 IDE.

Tasks Detailed steps

1. Deploy your Web a. Select Project | Copy Project.


application from Microsoft The Copy Project dialog appears.
Visual Studio .NET 2003
IDE. b. Enter http://localhost/ProductApp/ in the Destination project folder
filed.
c. Select File share option as Web access method.
d. Enter c:\inetpub\wwwroot\ProductApp in the Path filed of the Web
access method.
e. Select Only files needed to run this application option (default) in
Copy.
f. Click OK.
Microsoft Visual Studio .NET creates a folder ProductApp in
c:\inetpub\wwwroot and copies only the files required for executing the
Web application into the folder. This does not include files containing
source code.
g. Open Internet Explorer and enter
http://localhost/ProductApp/Login.aspx in the Address field and
click the Go button.
h. The Login page of your application is displayed.
i. Close the Web browser.
j. Select File | Exit to close Visual Studio .NET.