Upload
bu0n167
View
225
Download
0
Embed Size (px)
Citation preview
8/7/2019 Creating ASP[1].NET Web Applications with C# -Part 2_20050412_225745
1/13
8/7/2019 Creating ASP[1].NET Web Applications with C# -Part 2_20050412_225745
2/13
2 Table of Contents
Table of Contents
Creating ASP.NET Web Appl icat ions with C# - Part 2 ............................................................................3Exercise 1 State Management .............................................................................................................................4
Exercise 2 Data Access in Web Forms Pages .....................................................................................................7
Exercise 3 Deploying ASP.NET Web Application ...........................................................................................13
8/7/2019 Creating ASP[1].NET Web Applications with C# -Part 2_20050412_225745
3/13
Creating ASP.NET Web Appli cations with C# - Part 2 3
Creating ASP.NET Web Applicationswith 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 aspart 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 theUser 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 viewdetails 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 tim e tocomplete this lab: 45minutes
8/7/2019 Creating ASP[1].NET Web Applications with C# -Part 2_20050412_225745
4/13
4 Creating ASP.NET Web Applic ations with C# - Part 2
Exercise 1State Management
ScenarioIn this exercise, you will use both Client-side and Server-side state management options to preservethe values of the controls between round trips.
Tasks Detailed steps
1. Use the ViewState object to
preserve the Password
value in the client side.
As Web applications are
stateless between server round
trips the values of a page's
variables and controls are notpreserved. We need to preserve
these values and they can be
stored in the client or server. To
store in client, ViewState is
used.
a. Select Start | All Programs | Visual Studio .NET 2003 | Visual
Studio .NET 2003.
b. Open the base web application for modification by selecting File |
Open | Project.
c. Navigate to C:\Microsoft Hands-on-Lab\DEV-HOL03\Starter
Solution\Lab3-CS-Starter-2.
d. Select Lab3-CS-Starter-2.sln and clickOpen.
e. To view Login.aspx code, in the Solution Explorer, right-click
Login.aspx and select View Code.
f. To preserve value of the Password field using the ASP.NET
ViewState object, add the following code at the end of the
btnSignin_Click method.
private void btnSignin_Click(object sender,
System.EventArgs e)
{
.......
.......
.......
//Debugging codeDebug.WriteLine(txtUserID.Text);
Debug.WriteLine(txtPassword.Text);
Debug.Write(lblResult.Text);
//Client side State management using ViewStateViewState["Password"] = txtPassword.Text;
}
g. Select View | Designer or press SHIFT+F7.
h. Double-clickRestore 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. ClickSign In.
The server round trip occurs and the value of the Passwordfield is
preserved in ViewState object but the txtPasswordfield is empty.
8/7/2019 Creating ASP[1].NET Web Applications with C# -Part 2_20050412_225745
5/13
Creating ASP.NET Web Appli cations with C# - Part 2 5
l. ClickRestore
You can see The password you typed is mypasswordin lblResult.
m. Close the Web browser.
2. Use the Session object to
preserve the User ID value
in the server side.
a. Select View | Code or press F7.
b. To preserve the value of the User ID field on the server side using the
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
SessionSession["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
commandor 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 clickOpen.
LoginDemo.aspx is created and added to the project.
To display User ID value, add a new Labelcontrol to this form:
f. Select View | Toolbox or press CTRL+ALT+X.
g. ClickWeb Forms tab to see Web form controls.
h. Select Label control in Web Forms tab ofToolbox.
i. Dragand drop it on to the Design view ofLoginDemo.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 :
8/7/2019 Creating ASP[1].NET Web Applications with C# -Part 2_20050412_225745
6/13
6 Creating ASP.NET Web Applic ations 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
SessionlblUserID.Text = lblUserID.Text+" "+
Session["UserID"];
}
}m. Select Debug | Start or press F5.
n. Enter John in User ID and mypassword in Password.
o. ClickSign 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.
8/7/2019 Creating ASP[1].NET Web Applications with C# -Part 2_20050412_225745
7/13
Creating ASP.NET Web Appli cations with C# - Part 2 7
Exercise 2Data Access in Web Forms Pages
ScenarioThis exercise explains how to use data access in Web form and ASP.NET DataGridcontrol to bindto 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
create a connection to
Northwind database.
a. Add the following code at the top in the LoginDemo page, which
allows you to use SqlConnection class:
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 servers 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 = newSqlConnection("server=localhost;database=northwind;Trusted_Connection=yes");............
............
2. Fetch data from a Products
table and how to display it
in a DataGrid.
a. ClickView | Designer or press SHIFT+F7.
b. Select View | Toolbox or press CTRL+ALT+X.
c. Select DataGrid control in Web Forms tab ofToolbox.
d. Drag and drop it on to the Design view ofLoginDemo.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/7/2019 Creating ASP[1].NET Web Applications with C# -Part 2_20050412_225745
8/13
8 Creating ASP.NET Web Applic ations 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 Prodcutstable
SqlDataAdapter myCommand = newSqlDataAdapter("select * from Products",
myConnection);
//Create dataset and fill it with Product data
DataSet ds = new DataSet();myCommand.Fill(ds, "Products");
//Bind Product data to DatagridDataView 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.
8/7/2019 Creating ASP[1].NET Web Applications with C# -Part 2_20050412_225745
9/13
Creating ASP.NET Web Appli cations with C# - Part 2 9
k. ClickSign 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
features ofDataGridcontrol.
Add paging functionality to the DataGrid:
a. Select View | Designer or press SHIFT+F7.
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 forDataGridpaging functionality:
c. In the Properties Window, click the button to display a list of
DataGrid events.
d. Double-clickPageIndexChanged item.
Visual Studio .NETswitches to the code-behind page and creates an event
handler function nameddgProducts_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
pagedgProducts.CurrentPageIndex =
e.NewPageIndex;
BindGrid("ProductID");}
f. Select Debug | Start or press F5.
g. Enter John in User ID and mypassword in Password.
h. ClickSign In.
You are redirected to another page LoginDemo.aspx, where the Products
data is displayed in the DataGridcontaining 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 ofDataGrid properties.
n. Set the following properties:
AllowSorting - Trueo. Click the button to display a list ofDataGrid events
p. Double-clickSortCommand item.
Visual Studio .NETswitches to the code-behind page and creates an event
8/7/2019 Creating ASP[1].NET Web Applications with C# -Part 2_20050412_225745
10/13
10 Creating ASP.NET Web Applic ations with C# - Part 2
handler function nameddgProducts_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. ClickSign In.
You are redirected to another page LoginDemo.aspx, where the Products
data is displayed in the DataGridcontaining 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 toDataGrid control and use
the in-place editing feature
ofDataGrid.
Add a custom column to the DataGrid:
a. Select View | Designer or press SHIFT+F7.
b. Click the HTML tab (at the bottom of the page) to view the contents of
the page.
c. Add the following code between and
elements. This code creates a custom column named
Edit of type LinkButton (Snippet 5):
8/7/2019 Creating ASP[1].NET Web Applications with C# -Part 2_20050412_225745
11/13
Creating ASP.NET Web Appli cations with C# - Part 2 11
the DataGrid in the Design view ofLoginDemo.aspx page.
m. Click the button to display a list ofLabel 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 ofDataGrid events
q. Double-clickEditCommand item.
Visual Studio .NETswitches to the code-behind page and creates an event
handler function nameddgProducts_EditCommand
r. Select View | Designer or press SHIFT+F7.
s. ClickDataGrid control and select View | Properties Window.
t. Double-clickCancelCommand item.
Visual Studio .NETswitches to the code-behind page and creates an event
handler function nameddgProducts_CancelCommand
u. Select View | Designer or press SHIFT+F7.
v. Click the DataGrid control and select View | Properties Window.
w. Double-clickUpdateCommand item.
Visual Studio .NETswitches to the code-behind page and creates an event
handler function nameddgProducts_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 indexselected by the userdgProducts.EditItemIndex = (int)e.Item.ItemIndex;
BindGrid("ProductID");
}
private void dgProducts_CancelCommand (Objectsender, DataGridCommandEventArgs e)
{//Set the DataGrid's EditItemIndex to the -1 to
cancel the updatedgProducts.EditItemIndex = -1;
BindGrid("ProductID");
}
private void dgProducts_UpdateCommand (Object
sender, DataGridCommandEventArgs e)
{
8/7/2019 Creating ASP[1].NET Web Applications with C# -Part 2_20050412_225745
12/13
12 Creating ASP.NET Web Applic ations with C# - Part 2
//Create an update command, add parameters toit 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=
"Product " +dgProducts.DataKeys[(int)e.Item.ItemIndex]+" is
updated
" ;
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. ClickSign In.
You are redirected to another page LoginDemo.aspx, where the Products
data is displayed in the DataGrid.
bb. ClickEdit linkin any row in the DataGrid.
YourDataGridis 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. ClickUpdate link of that row.
You get a message displaying Product is updatedin the lblMessage
control.
ee. Close the Web browser.
8/7/2019 Creating ASP[1].NET Web Applications with C# -Part 2_20050412_225745
13/13
Creating ASP.NET Web Appli cations with C# - Part 2 13
Exercise 3Deploying ASP.NET Web Application
ScenarioYou can use XCOPY or FTP to deploy an ASP.NET application on to a server. You also can useMicrosoft 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
application from Microsoft
Visual Studio .NET 2003
IDE.
a. Select Project | Copy Project.
The Copy Project dialog appears.
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. ClickOK.
Microsoft Visual Studio .NETcreates a folderProductApp 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 enterhttp://localhost/ProductApp/Login.aspx inthe 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.