Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / Premier Press - C# Professional Projects

.pdf
Скачиваний:
475
Добавлен:
12.02.2016
Размер:
14.7 Mб
Скачать

488

Project 4

CREATING AN AIRLINE RESERVATION PORTAL

 

 

{

 

 

 

 

 

 

 

 

 

 

case “Admin”:

 

 

 

 

 

Response.Redirect(“.\\NA\\ManageUsers.aspx”);

 

 

break;

 

 

 

 

 

case “BM”:

 

 

 

 

 

Response.Redirect(“.\\BM\\AddFl.aspx”);

 

 

break;

 

 

Y

 

 

case “LOB”:

 

 

 

 

 

 

 

 

 

Response.Redirect(“.\\LOB\\CreateRes.aspx”);

 

 

break;

 

 

 

 

 

}

 

M

 

 

 

 

 

 

 

The complete code of the Click event ofLSubmit button, which incorporates the

 

functionality described previously, isFgiven as follows:

 

 

E

 

 

private void btnSubmit_Click(object sender, System.EventArgs e)

{

T

 

 

 

if (Page.IsValid==true)

A

 

{

string username, password; int datarows;

username=txtUserName.Text.Trim(); password=txtPassword.Text.Trim(); sqlConnection1.Open();

sqlDataAdapter1.SelectCommand.Parameters[“@UserName”].Value=username; datarows=sqlDataAdapter1.Fill(dataSet11,”UserDetails”); sqlConnection1.Close();

if (datarows==0) lblMessage.Text=”Incorrect user name”;

else

{

if (dataSet11.Tables[“UserDetails”].Rows[0][1].ToString().Trim()==password)

{

string Role; Role=dataSet11.Tables[“UserDetails”].Rows[0][2].ToString().Trim(); Session[“usrName”]=username;

Session[“usrRole”]=Role; if (Role==”Disabled”)

{

Team-Fly®

IMPLEMENTING THE BUSINESS LOGIC

Chapter 21

489

 

 

 

 

lblMessage.Text=”Your account has been disabled. Please contact the network administrator.”;

return;

}

switch(Role)

{

case “Admin”: Response.Redirect(“.\\NA\\ManageUsers.aspx”); break;

case “BM”: Response.Redirect(“.\\BM\\AddFl.aspx”); break;

case “LOB”: Response.Redirect(“.\\LOB\\CreateRes.aspx”); break;

}

}

else

lblMessage.Text=”Incorrect password”;

}

dataSet11.Clear();

}

}

The Logoff.aspx Form

The Logoff.aspx form is used for logging a user off from the Web site. This form clears the Session variables assigned to the user so that the user is unable to browse any page on the Web application. All code on the Logoff.aspx form is written in the Load event of the form. To write the code for the Load event, double-click on the form in the Design view. The code for the Load event of the Logoff.aspx form is given as follows:

private void Page_Load(object sender, System.EventArgs e)

{

Session.RemoveAll();

}

490 Project 4 CREATING AN AIRLINE RESERVATION PORTAL

Coding the Forms for Network

Administrators

SkyShark Airlines provides the ManageUsers.aspx and ManageDatabases.aspx forms for network administrators.

By default, when the application is installed, a user account for network administrators is added to the application,with the username and password as Admin and Password, respectively, so that a network administrator can access the ManageUsers.aspx form and create user accounts. You can examine the code for the ManageUsers.aspx form.

The ManageUsers.aspx Form

The ManageUsers.aspx page is used for adding and deleting user accounts. I will examine the steps to add and delete user accounts separately. However, before examining these tasks, perform the following steps to configure data controls for the ManageUsers.aspx form:

1.Drag the dtUsers table from Server Explorer to the Design view of the form.

2.Generate a dataset for the SqlDataAdapter control that is added to the form.

3.Modify the default queries that are associated with the sqlDataAdapter1 control as specified:

SelectCommand. SELECT Username FROM dtUsers

DeleteCommand. UPDATE dtUsers SET Role = ‘Disabled’ WHERE

(Username = @Original_Username)

Adding User Accounts

To add a user account, you need to perform the following steps:

1.Check whether the username already exists. Before adding a record to the dtUsers table, you should check whether the user account already exists. You can check usernames by retrieving them from the dtUsers table and checking each record. The following code snippet retrieves

IMPLEMENTING THE BUSINESS LOGIC

Chapter 21

491

 

 

 

 

records from the dtUsers table and compares them with the username specified by the user.

string username, password, role; int selection; role=lstAddRole.SelectedItem.Text; username=txtAddUserName.Text.Trim(); password=txtAddPassword.Text.Trim(); selection=lstAddRole.SelectedIndex; sqlConnection1.Open();

sqlDataAdapter1.Fill(dataSet11, “UserList”); sqlConnection1.Close();

foreach (DataRow myRow in dataSet11.Tables[“UserList”].Rows)

{

if (myRow[0].ToString().Trim().ToLower()==username.ToLower())

{

lblMessage.Text=”The user name already exists. Please try another user name”;

return;

}

}

2.Add the new user to the database. If the username specified by the user is unique, the application adds a record to the database by using the SQL query associated with the InsertCommand property of the sqlDataAdapter1 control. However, before you execute the quer y, you need to assign values specified by the user as the parameters to the query. To assign values to parameters, you can use the Parameters collection of

InsertCommand. The code snippet to add a new user to the database is given as follows:

sqlDataAdapter1.InsertCommand.Parameters[0].Value=username; sqlDataAdapter1.InsertCommand.Parameters[1].Value=password; sqlDataAdapter1.InsertCommand.Parameters[2].Value=role;

sqlConnection1.Open();

sqlDataAdapter1.InsertCommand.ExecuteNonQuery();

sqlConnection1.Close();

492 Project 4 CREATING AN AIRLINE RESERVATION PORTAL

NOTE

Instead of using the code in Step 2, you could also update the DataSet that corresponds to the data in the dtUsers table and then invoke the Update method of sqlDataAdapter1 to update data in the dtUsers table. The ideal scenario to employ that method is when you want to optimize database interaction by caching changes and then sending them to the database at regular intervals.

3.Send an e-mail message to the registered user. After adding the new user to the SkyShark Airlines application, use the SmtpMail class to send an e-mail message to the registered user. The Send method of the Smtp-

Mail class uses an object of the MailMessage class to send an e-mail message to the user. The code for creating and sending the message is given as follows:

MailAttachment attachment= new MailAttachment(“c:\\Inetpub\\wwwroot\\SkyShark\\NA\\PrivacyPolicy.doc”); MailMessage email= new MailMessage(); email.Attachments.Add(attachment);

email.To=username + “@skyshark.com”; email.From=”admin@skyshark.com”; email.Subject=”Message from SkyShark Airlines”;

email.Body=”Dear “ + username + “,\n\nYour account has been added “ + “to the SkyShark Airlines application. You can log on to the “ + “application at http://npandey-d185/skyshark. \n\nYour logon name” +

is “ + username + “ and the password is password. Please change” +

your password when you log on. \n\n By logging on to the application,” +

you agree to abide by the terms and conditions attached in the mail” + “\n\n Happy Browsing.\n\n Network Administrator (SkyShark)”; SmtpMail.Send(email);

When a new user registers on the Web site, the details of the new user are added to the dtUsers table and an e-mail message is sent to the user. The complete code

IMPLEMENTING THE BUSINESS LOGIC

Chapter 21

493

 

 

 

 

of the Click event of the Submit button is obtained by combining the code snippets given earlier. The code is given as follows:

private void btnAddSubmit_Click(object sender, System.EventArgs e)

{

if (txtAddUserName.Text==null || txtAddUserName.Text==”” || txtAddPassword.Text ==null || txtAddPassword.Text==”” || txtAddConfPassword.Text

==null || txtAddConfPassword.Text==””)

{

lblMessage.Text=”One or more required values are missing. Try again.”;

}

if (Page.IsValid)

{

string username, password, role; int selection; role=lstAddRole.SelectedItem.Text; username=txtAddUserName.Text.Trim(); password=txtAddPassword.Text.Trim(); selection=lstAddRole.SelectedIndex; sqlConnection1.Open();

sqlDataAdapter1.Fill(dataSet11, “UserList”); sqlConnection1.Close();

foreach (DataRow myRow in dataSet11.Tables[“UserList”].Rows)

{

if (myRow[0].ToString().Trim().ToLower()==username.ToLower())

{

lblMessage.Text=”The user name already exists. Please try another user name”; return;

}

}

sqlDataAdapter1.InsertCommand.Parameters[0].Value=username; sqlDataAdapter1.InsertCommand.Parameters[1].Value=password; sqlDataAdapter1.InsertCommand.Parameters[2].Value=role; sqlConnection1.Open(); sqlDataAdapter1.InsertCommand.ExecuteNonQuery(); sqlConnection1.Close();

MailAttachment attachment= new MailAttachment(“c:\\Inetpub\\wwwroot\\SkyShark\\NA \\PrivacyPolicy.doc”);

494 Project 4 CREATING AN AIRLINE RESERVATION PORTAL

MailMessage email= new MailMessage(); email.Attachments.Add(attachment); email.To=username + “@niit.com”; email.From=”nitinp@niit.com”; email.Subject=”Message from SkyShark Airlines”;

email.Body=”Dear “ + username + “,\n\nYour account has been added “ + “to the SkyShark Airlines application. You can log on to the “ + “application at http://npandey-d185/skyshark. \n\nYour logon name” +

is “ + username + “ and the password is password. Please change” +

your password when you log on. \n\n By logging on to the application,” +

you agree to abide by the terms and conditions attached in the mail” + “\n\n Happy Browsing.\n\n Network Administrator (SkyShark)”; SmtpMail.Send(email);

lblMessage.Text=”User added successfully”; txtAddUserName.Text=””;

dataSet11.Clear();

}

}

Deleting User Accounts

The procedure for deleting user accounts is straightforward. The username specified by the network administrator is checked in the dtUsers database to ensure that it exists. Next, the DeleteCommand property of the sqlDataAdapter1 control is used to delete the username specified by the network administrator from the database. The code for the Click event of the Delete button is given as follows:

private void btnDelDelete_Click(object sender, System.EventArgs e)

{

string username=txtDelUserName.Text.Trim(); bool userexists=false;

if (username==null || username==””)

{

lblMessage.Text=”Please specify a valid user name”;

}

else

{

sqlConnection1.Open(); sqlDataAdapter1.Fill(dataSet11, “UserList”);

IMPLEMENTING THE BUSINESS LOGIC

Chapter 21

495

 

 

 

 

sqlConnection1.Close();

foreach (DataRow myRow in dataSet11.Tables[“UserList”].Rows)

{

if (myRow[0].ToString().Trim().ToLower()==username.ToLower())

{

userexists=true;

}

}

if (userexists==false)

{

lblMessage.Text=”The user does not exist”; return;

}

sqlDataAdapter1.DeleteCommand.Parameters[0].Value=username; sqlConnection1.Open(); sqlDataAdapter1.DeleteCommand.ExecuteNonQuery(); sqlConnection1.Close();

lblMessage.Text=”User disabled successfully”; txtDelUserName.Text=””;

}

}

The ManageDatabases.aspx Form

The ManageDatabases.aspx form is used for moving data between the dtReser-

vations and dtDepartedFlights tables. It is also used to update the dtPassen-

gerDetails table for the frequent fliers program.

For updating the dtDepartedFlights and dtPassengerDetails tables,I have created stored procedures in SQL Server. These procedures are called from the SkyShark Airlines application so that the data can be updated directly at the back end. There are several advantages of using a stored procedure in this scenario:

Since the data is not required in the application, it does not need to be retrieved from the application and then posted back again.This saves a lot of unnecessary network congestion and improves the performance of the application and the database.

496 Project 4 CREATING AN AIRLINE RESERVATION PORTAL

The developer does not need to write unnecessary code for the application. SQL queries that are used in stored procedures can be easily tested by using Query Analyzer.

To move data from the dtReservations table to the dtDepartedFlights table, you need to write the following stored procedure:

CREATE PROCEDURE UpdateReservations

@date datetime

AS

INSERT INTO dtDepartedFlights

SELECT * from dtReservations

WHERE (DateOfJourney < @date) AND (TicketConfirmed=1)

DELETE from dtReservations

WHERE (DateOfJourney < @date)

GO

To execute a stored procedure, you need to associate it with an SqlCommand object. Stored procedures can be associated with SqlCommand objects in the same way as you associate SQL Server tables with your application. The stored procedures in the SkyShark Airlines database are shown in Figure 21-2.

FIGURE 21-2 Stored procedures can be accessed from Server Explorer

IMPLEMENTING THE BUSINESS LOGIC

Chapter 21

497

 

 

 

 

To write the code for executing the UpdateReservations stored procedure from the SkyShark Airlines application,drag the Update Reservations stored procedure form Ser ver Explorer to the design view of the form. Visual Studio .NET automatically creates the sqlDataAdapter1 and sqlCommand1 controls. To run the stored procedure when a user clicks on the Archive button, write the following code for the Click event of the Archive button:

private void BtnArchive_Click(object sender, System.EventArgs e)

{

lblMessage.Text=””; sqlConnection1.Open();

sqlCommand1.Parameters[1].Value=DateTime.Today.Date.ToShortDateString(); sqlCommand1.ExecuteNonQuery();

sqlConnection1.Close(); lblMessage.Text=”Done.”;

}

To move data between the dtDepartedFlights and dtPassengerDetails tables, I

have created the FrequentFlier stored procedure.The definition of this procedure is given as follows:

CREATE PROCEDURE FrequentFlier

AS

DELETE dtFrequentFliers

INSERT INTO dtPassengerDetails

SELECT EMail, Sum(Fare), Count(EMail) from dtDepartedFlights where EMAIL!=’NotSpecified’ group by EMail

GO

To run this procedure, specify the following code in the Click event of the Update button:

private void btnUpdate_Click(object sender, System.EventArgs e)

{

lblMessage.Text=””; sqlConnection1.Open(); sqlCommand2.ExecuteNonQuery(); sqlConnection1.Close(); lblMessage.Text=”Done.”;

}