Lab Steps
STEP 1: Login Form
1. In order to do this lab, we need to assign a primary key to the tblUserLogin table. This will allow us to modify the user login table from our Manage Users form that we will create later. Go to Windows Explorer and open the PayrollSystem_DB.accdb. Set the UserID as the Primary key and save the table. Close the database.
2. Open Microsoft Visual Studio.NET.
3. Click the ASP.NET website named PayrollSystem to open it.
4. Create a new Web form named frmLogin.
5. Add the ACIT logo to the top of the frmLogin page. Do not hyperlink the logo.
6. Under the login controls, you will see Login. Drop the Login control onto the form. Set the properties of the login control as follows:
Property
Value
DestinationPageUrl
frmMain.aspx
TitleText
Please enter your UserName and Password in order to log in to the system.
7. Highlight everything in the form, then click Format, Justify, Center. Save your work.
8. Go to the
Solution
Explorer, right-click on frmLogin, and left-click on Set As Start Page.
Then run the website to check if the Web form appears correctly.
If you receive an error, add the following code to the web.config file right above the </configuration> line:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
STEP 2: Login Check
9. Create a new DataSet called dsUser. Use the table tblUserLogin as the database table for this dataset. Do this in the same way that you added datasets in the previous labs.
10. Open the clsDataLayer and add the following function:
// This function verifies a user in the tblUser table
public static dsUser VerifyUser(string Database, string UserName, string UserPassword)
{
// Add your comments here
dsUser DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
// Add your comments here
sqlConn = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + Database);
// Add your comments here
sqlDA = new OleDbDataAdapter("Select SecurityLevel from tblUserLogin " +
"where UserName like '" + UserName + "' " +
"and UserPassword like '" + UserPassword + "'", sqlConn);
// Add your comments here
DS = new dsUser();
// Add your comments here
sqlDA.Fill(DS.tblUserLogin);
// Add your comments here
return DS;
}
11. Double-click on the login control that you added. Add the following code to the login control Authenticate event handler:
// Add your comments here
dsUser dsUserLogin;
// Add your comments here
string SecurityLevel;
// Add your comments here
dsUserLogin = clsDataLayer.VerifyUser(Server.MapPath("PayrollSystem_DB.accdb"),
Login1.UserName, Login1.Password);
// Add your comments here
if (dsUserLogin.tblUserLogin.Count < 1)
{
e.Authenticated = false;
return;
}
// Add your comments here
SecurityLevel = dsUserLogin.tblUserLogin[0].SecurityLevel.ToString();
// Add your comments here
switch (SecurityLevel)
{
case "A":
// Add your comments here
e.Authenticated = true;
Session["SecurityLevel"] = "A";
break;
case "U":
// Add your comments ...
1. Lab Steps
STEP 1: Login Form
1. In order to do this lab, we need to assign a primary key to the
tblUserLogin table. This will allow us to modify the user login
table from our Manage Users form that we will create later. Go
to Windows Explorer and open
the PayrollSystem_DB.accdb. Set the UserID as the Primary key
and save the table. Close the database.
2. Open Microsoft Visual Studio.NET.
3. Click the ASP.NET website named PayrollSystem to open it.
4. Create a new Web form named frmLogin.
5. Add the ACIT logo to the top of the frmLogin page. Do not
hyperlink the logo.
6. Under the login controls, you will see Login. Drop the Login
control onto the form. Set the properties of the login control as
follows:
Property
Value
DestinationPageUrl
frmMain.aspx
TitleText
Please enter your UserName and Password in order to log in to
the system.
7. Highlight everything in the form, then click Format, Justify,
Center. Save your work.
8. Go to the
Solution
2. Explorer, right-click on frmLogin, and left-click on Set As
Start Page.
Then run the website to check if the Web form appears
correctly.
If you receive an error, add the following code to
the web.config file right above the </configuration> line:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode"
value="None" />
</appSettings>
STEP 2: Login Check
9. Create a new DataSet called dsUser. Use the
table tblUserLogin as the database table for this dataset. Do this
in the same way that you added datasets in the previous labs.
10. Open the clsDataLayer and add the following function:
// This function verifies a user in the tblUser table
public static dsUser VerifyUser(string Database, string
UserName, string UserPassword)
{
// Add your comments here
dsUser DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
// Add your comments here
3. sqlConn = new
OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;"
+
"Data Source=" + Database);
// Add your comments here
sqlDA = new OleDbDataAdapter("Select SecurityLevel from
tblUserLogin " +
"where UserName like '" + UserName + "' " +
"and UserPassword like '" + UserPassword + "'", sqlConn);
// Add your comments here
DS = new dsUser();
// Add your comments here
sqlDA.Fill(DS.tblUserLogin);
// Add your comments here
return DS;
}
11. Double-click on the login control that you added. Add the
following code to the login control Authenticate event handler:
// Add your comments here
dsUser dsUserLogin;
// Add your comments here
string SecurityLevel;
// Add your comments here
dsUserLogin =
clsDataLayer.VerifyUser(Server.MapPath("PayrollSystem_DB.a
4. ccdb"),
Login1.UserName, Login1.Password);
// Add your comments here
if (dsUserLogin.tblUserLogin.Count < 1)
{
e.Authenticated = false;
return;
}
// Add your comments here
SecurityLevel =
dsUserLogin.tblUserLogin[0].SecurityLevel.ToString();
// Add your comments here
switch (SecurityLevel)
{
case "A":
// Add your comments here
e.Authenticated = true;
Session["SecurityLevel"] = "A";
break;
case "U":
// Add your comments here
e.Authenticated = true;
Session["SecurityLevel"] = "U";
break;
default:
5. e.Authenticated = false;
break;
}
STEP 3: User Authentication, Test and Submit
12. Open the frmPersonnel form and add the following code to
its Page_Load() function:
// Add your comments here
if (Session["SecurityLevel"] == "A") {
btnSubmit.Visible = true;
//Add your comments here
} else {
btnSubmit.Visible = false;
}
13. Set the start page as frmLogin.aspx. Run the website. Try to
log in with both User Name = Mickey and Password =
Mouse and User Name = Minnie and Password = Mouse. Any
other user ID and password should not allow you to log in.
14. When the user logs in, we want to restrict what they can see
and do based on their user role. The role is stored in the
database table tblUserLogin. Mickey Mouse has all privileges,
whereas Minnie Mouse has read only privileges. We want to
control the visibility of the links on the frmMain page.
15. Initially, we did not set the ID of any of the Link Button or
Image Button controls that we used on frmMain. In order to
make our code more maintainable, we will change the IDs as
6. follows:
Option
Link Button ID
Image Button ID
Annual Salary Calculator
linkbtnCalculator
imgbtnCalculator
Add New Employee
linkbtnNewEmployee
imgbtnNewEmployee
View User Activity
linkbtnViewUserActivity
imgbtnViewUserActivity
View Personnel
linkbtnViewPersonnel
imgbtnViewPersonnel
Search Personnel
linkbtnSearch
imgbtnSearch
Edit Employees
linkbtnEditEmployees
imgbtnEditEmployees
16. Modify the main form so that the following options
are turned off for nonadmin users:
· Add New Employee
7. · View User Activity
· Edit Employees
17. You now have a Web application that honors the role of the
logged-in user. We don't have a way of managing the user roles
and users in the system.
18. Add a new form called frmManageUsers that will allow the
user to add new users. The user will also need to be able to view
all users and modify or delete any of the users in the database.
Add a main form option called Manage Users that is only
accessible to admin users. Add the link and image buttons as we
have done in the past. Add the ACIT logo that is hyperlinked as
you did in previous assignments.
· For the security level of the user, use a dropdown list control
to allow the user to select from A or U.
· Name the controls with names that make sense.
· Add code as appropriate to the code behind and clsDataLayer.
Note: You will need to create a SaveUser function that is very
similar to the SavePersonnel function. Use the following as a
guide:
public static bool SaveUser(string Database, string UserName,
string Password,
string SecurityLevel)
When creating the SaveUser function, be sure to insert the data
into the tblUserLogin table with columns: userName,
UserPassword, and SecurityLevel.
8. 19. Hints:
· Make sure you reestablish your database connection if you
copied the files from a previous lab.
· Update any DataSource controls that you added with the new
Payroll database location.
· You can turn a control on or off by setting
its Visible property.
· You can add a data entry form for new users and a grid
displaying all users all on the same form.
· To force a gridView to refresh, call its DataBind method in
the btnAddUser_click event handler. For example, use the
following code in the btnAddUser_click (be sure to include an
Else condition as well if the user was not added successfully):
if
(clsDataLayer.SaveUser(Server.MapPath("PayrollSystem_DB.ac
cdb"),
txtUserName.Text,
txtPassword.Text,ddlSecurityLevel.SelectedValue))
{
lblError.Text = "The user was successfully added!";
grdUsers.DataBind();
}
20. Test your application to make sure that you are logging in
with a valid user ID. Try to log in with both Minnie and Mickey
and make sure that the UI adjusts by the role properly. Make
9. sure that you can utilize the Manage Users functionality to
Add/Modify/Delete and view user information. Once you have
verified that everything works, save your project, zip up all
files, and submit it.
NOTE: Make sure you include comments in the code provided
where specified (where the " // Your comments here" is
mentioned); also, any code you write needs to be properly
commented, or else a 5-point deduction per item (form, class,
function) will be made.
frmManageUsers
Mickey Mouse (Admin) Login:
Minnie Mouse (User) Login:
spssdatayearidmaritalsibschildsageeducdegreesexracepartyidVO
TE08happysatfintvhourshealth1mntlhlth2,012151022163112211
13102,01212523361632212222302,0121556452401332332142,0
1217153361211153222222,01218325471312221233242,012231
12541421132233102,01224132451622332110202,01227520221
511151212102,012304324413121512322202,012323526314221
01134322,012351104214121212233152,0123852049121220111
16212,01239520271732311221312,01240522301412212232422,
25. using System.Data;
public class clsDataLayer
{
// This function gets the user activity from the tblUserActivity
public static dsUserActivity GetUserActivity(string
Database)
{
// Declare DataSet, connection, and data adapter object
dsUserActivity DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
// Inintialize connection using the connection string to the
database
26. sqlConn = new
OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=" + Database);
// Initialize the data adapter using SQL
sqlDA = new OleDbDataAdapter("select * from
tblUserActivity", sqlConn);
// Create and empty data set
DS = new dsUserActivity();
// It fills the data set from the data adapter
sqlDA.Fill(DS.tblUserActivity);
// returns the retrieved data to the caller
return DS;
}
// This function saves the user activity
27. public static void SaveUserActivity(string Database, string
FormAccessed)
{
// It saves the user information by connecting to the
database and saving it to the dataset
OleDbConnection conn = new
OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;"
+
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
strSQL = "Insert into tblUserActivity (UserIP,
FormAccessed) values ('" +
GetIP4Address() + "', '" + FormAccessed + "')";
28. command.CommandType = CommandType.Text;
command.CommandText = strSQL;
command.ExecuteNonQuery();
conn.Close();
}
// This function gets the IP Address
public static string GetIP4Address()
{
string IP4Address = string.Empty;
foreach (IPAddress IPA in
Dns.GetHostAddresses(HttpContext.Current.Request.UserHostA
ddress))
29. {
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
if (IP4Address != string.Empty)
{
return IP4Address;
}
foreach (IPAddress IPA in
Dns.GetHostAddresses(Dns.GetHostName()))
30. {
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
}
// This function saves the personnel data.
public static bool SavePersonnel(string Database, string
31. FirstName, string LastName,
string PayRate, string StartDate, string EndDate)
{
bool recordSaved;
// Declares the transaction variable.
OleDbTransaction myTransaction = null;
try
{
// Opens the connection to the database.
OleDbConnection conn = new
OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;"
+
"Data Source=" + Database);
32. conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
// Begin transaction as new transaction
myTransaction = conn.BeginTransaction();
command.Transaction = myTransaction;
// It perform an insert interaction with the database to
insert the data below; FirstName and LastName
//from the form filled by the user.
strSQL = "Insert into tblPersonnel " +
"(FirstName, LastName) values ('" +
33. FirstName + "', '" + LastName + "')";
// Indicate the type of command being executed, in this
case is .Text; Second command is to identify
// the command to execute which is strSQL that insert
data into the datasources in the data set.
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// perform a query without returning any value since we
are performing an Insert operation for the database.
command.ExecuteNonQuery();
// perform and UPDATE to save the PayRate, StartDate,
and EndDate into the new record.
strSQL = "Update tblPersonnel " +
34. "Set PayRate=" + PayRate + ", " +
"StartDate='" + StartDate + "', " +
"EndDate='" + EndDate + "' " +
"Where ID=(Select Max(ID) From tblPersonnel)";
// Indicate the type of command being executed, in this
case is .Text; Second command is to identify
// the command to execute which is strSQL that insert
data into the datasources in the data set.
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// perform a query without returning any value since we
are performing an Insert operation for the database.
command.ExecuteNonQuery();
35. // Commits the transaction saving changes and
competing the current transaction.
myTransaction.Commit();
// Close the connection to the database.
conn.Close();
recordSaved = true;
}
catch (Exception ex)
{
// Rollsback the transaction canceling any changes
during the current transaction and ends the transaction.
myTransaction.Rollback();
36. recordSaved = false;
}
return recordSaved;
}
public static dsPersonnel GetPersonnel(string Database, string
strSearch)
{
// Declare DataSet, connection, and data adapter object
dsPersonnel DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
// Inintialize connection using the connection string to the
37. database
sqlConn = new
OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=" + Database);
// Will check if the text box for search is empty or the user
hit the search button with nothing on the text box
// then it will return all the personnel. If a last name is
filled up it will return the table with the last names on the table.
if (strSearch == null || strSearch.Trim() == "")
{
sqlDA = new OleDbDataAdapter("select * from
tblPersonnel", sqlConn);
}
else
{
38. sqlDA = new OleDbDataAdapter("select * from
tblPersonnel where LastName = '" + strSearch + "'", sqlConn);
}
// Create and empty data set
DS = new dsPersonnel();
// It fills the data set from the data adapter
sqlDA.Fill(DS.tblPersonnel);
// returns the retrieved data to the caller
return DS;
}
}
44. using System.Web.UI;
using System.Web.UI.WebControls;
public partial class frmSearchPersonnel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
PayrollSystem (1)/frmUserActivity.aspx
PayrollSystem (1)/frmUserActivity.aspx.cs
using System;
45. using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class frmUserActivity : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Declares the DataSet
46. dsUserActivity myDataSet = new dsUserActivity();
// Fill the dataset with what is returned from the
function
myDataSet =
clsDataLayer.GetUserActivity(Server.MapPath("PayrollSystem_
DB.accdb"));
// Sets the DataGrid to the DataSource based on the
table
grdUserActivity.DataSource =
myDataSet.Tables["tblUserActivity"];
// Binds the DataGrid
grdUserActivity.DataBind();
}
}
}
48. {
if (!Page.IsPostBack)
{
//Declare the Dataset
dsPersonnel myDataSet = new dsPersonnel();
string strSearch = Request["txtSearch"];
//Fill the dataset with shat is returned from the method.
myDataSet =
clsDataLayer.GetPersonnel(Server.MapPath("PayrollSystem_D
B.accdb"), strSearch);
//Set the DataGrid to the DataSource based on the table.
50. using System.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for clsDataLayer
/// </summary>
public class clsDataLayer
{// This function gets the user activity from the tblUserActivity
public static dsUserActivity GetUserActivity(string
Database)
51. {
// Add your comments here
dsUserActivity DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
// Add your comments here
sqlConn = new
OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=" + Database);
// Add your comments here
sqlDA = new OleDbDataAdapter("select * from
tblUserActivity", sqlConn);
// Add your comments here
DS = new dsUserActivity();
52. // Add your comments here
sqlDA.Fill(DS.tblUserActivity);
// Add your comments here
return DS;
}
// This function saves the user activity
public static void SaveUserActivity(string Database, string
FormAccessed)
{
// Add your comments here
OleDbConnection conn = new
OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;"
+
"Data Source=" + Database);
53. conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
strSQL = "Insert into tblUserActivity (UserIP,
FormAccessed) values ('" +
GetIP4Address() + "', '" + FormAccessed + "')";
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
command.ExecuteNonQuery();
conn.Close();
}
// This function gets the IP Address
public static string GetIP4Address()
67. protected void Page_Load(object sender, EventArgs e)
{
// Variables for the Date for the user entries.
DateTime dt1;
DateTime dt2;
// This will make the error textbox blank again and the
entry textbox back to white color.
lblError.Text = "";
Boolean validatedState = false;
// The next 5 validation controls check if there are left
blank or filled with blank spaces and gives the error message.
68. if (Request["txtFirstName"].ToString().Trim() == "")
{
txtFirstName.BackColor =
System.Drawing.Color.Yellow;
lblError.Text = "Must enter a First Name. ";
validatedState = true;
}
else
{
txtFirstName.BackColor =
System.Drawing.Color.White;
}
if (Request["txtLastName"].ToString().Trim() == "")
71. System.Drawing.Color.Yellow;
lblError.Text += "Must enter a Start Date. ";
validatedState = true;
}
if (Request["txtEndDate"].ToString().Trim() == "")
{
txtEndDate.BackColor =
System.Drawing.Color.Yellow;
lblError.Text += "Must enter an End Date. ";
validatedState = true;
}
72. // First this method saves the dates into the dt1 and dt2
variables and then perform the second part described on next
line.
// Second part it is a compare method to ensure the end
date is later than the start date and will make the text boxes
background yellow color.
if (txtStartDate.Text.Trim() != "" &
txtEndDate.Text.Trim() != "")
{
dt1 = DateTime.Parse(txtStartDate.Text);
dt2 = DateTime.Parse(txtEndDate.Text);
73. if (DateTime.Compare(dt1, dt2) > 0)
{
txtStartDate.BackColor =
System.Drawing.Color.Yellow;
txtEndDate.BackColor =
System.Drawing.Color.Yellow;
lblError.Text += "The end date must be a later date
than the start date.";
validatedState = true;
}
else
{
// This will ensure that the background color goes
back to white if the textbox is filled and no errors are found.
txtStartDate.BackColor =
74. System.Drawing.Color.White;
txtEndDate.BackColor =
System.Drawing.Color.White;
}
}
// This method saves the data from the session and pass it
to the frmPersonnelVerified.
if (validatedState == false)
{
Session["txtFirstName"] = txtFirstName.Text;
Session["txtLastName"] = txtLastName.Text;
Session["txtPayRate"] = txtPayRate.Text;
Session["txtStartDate"] = txtStartDate.Text;
77. using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class frmPersonnelVerified : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Get the data from the Session of the previous form, the
frmPersonnel.aspx
txtVerifiedInfo.Text = Session["txtFirstName"].ToString()
+
78. "n" + Session["txtLastName"].ToString() +
"n" + Session["txtPayRate"].ToString() +
"n" + Session["txtStartDate"].ToString() +
"n" + Session["txtEndDate"].ToString();
// call the SavePersonnel method from clsDataLayer.cs and
pass the session data. After it will validate if the
// data was saved if not then will pop an error message
saying that the data was not saved.
if
(clsDataLayer.SavePersonnel(Server.MapPath("PayrollSystem_
DB.accdb"),
Session["txtFirstName"].ToString(),
Session["txtLastName"].ToString(),
85. {
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Declares the DataSet
dsUserActivity myDataSet = new dsUserActivity();
// Fill the dataset with what is returned from the
function
myDataSet =
clsDataLayer.GetUserActivity(Server.MapPath("PayrollSystem_
DB.accdb"));
// Sets the DataGrid to the DataSource based on the
table
grdUserActivity.DataSource =
88. Lab Overview
Scenario/Summary
This week, we will use the .NET OleDbTransaction functions to
either commit a set of changes to the database, if all of them
were done correctly, or to roll back all of the changes if there
was an error in any one of them. We will first modify the code
that we created last week so that it will save personnel data in
the database in two steps; first by inserting a personnel record
for a new employee, and then by updating that record to fill in
the start and end dates. This two-step approach is not really
needed in this simple case, but we will use it to simulate a more
complex database transaction that would have to be done in
multiple steps, such as one involving more than one table or
even more than one database. We will then see what happens
when there is an error in the second operation (the update),
allowing a record to be created containing incomplete
information: not a good result! We will fix the problem by
wrapping both operations (the insert and the update) into a
single transaction that will be committed (made permanent) only
if both operations succeed or will be rolled back (undone) if
either operation fails. We will also add client-side validation
using the ASP.Net validation controls, and we will allow the
user an easy way to edit all employees.
Please watch the tutorial before beginning the Lab.
Transcript
89. Deliverables
All files are located in the subdirectory of the project. The
project should function as specified: When you press
the Submit button in frmPersonnel, a record should be saved in
the tblPersonnel table containing the FirstName, LastName,
PayRate, StartDate, and EndDate that you entered. Test that the
transaction will roll back by entering invalid information in one
or more items, such as Hello for a StartDate. Check that client-
side validation works: The ability to edit employees in a grid is
working. Once you have verified that it works, save your
website, zip up all files, and submit them.
Required Software
Microsoft Visual Studio.NET
Access the software at https://lab.devry.edu (Links to an
external site.)Links to an external site..
Steps: 1, 2, and 3
Lab Steps
STEP 1: Modify the clsDataLayer to Use a Two-Step Process
1. Open Microsoft Visual Studio.NET.
2. Click the ASP.NET project called PayrollSystem to open it.
3. Open the clsDataLayer class.
4. Modify the SavePersonnel() function so that instead of just
doing a single SQL INSERT operation with all of the personnel
data, it does an INSERT with only the FirstName and
LastName, followed by an UPDATE to save the PayRate,
90. StartDate, and EndDate into the new record. (This two-step
approach is not really necessary here because we are dealing
with only one table, tblPersonnel, but we are doing it to
simulate a case with more complex processing requirements, in
which we would need to insert or update data in more than one
table or maybe even more than one database.) Find the
following existing code in the SavePersonnel() function:
// Add your comments here
strSQL = "Insert into tblPersonnel " +
"(FirstName, LastName, PayRate, StartDate, EndDate)
values ('" +
FirstName + "', '" + LastName + "', " + PayRate + ", '" +
StartDate +
"', '" + EndDate + "')";
// Add your comments here
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Add your comments here
command.ExecuteNonQuery();
Modify it so that it reads as follows:
// Add your comments here
strSQL = "Insert into tblPersonnel " +
"(FirstName, LastName) values ('" +
FirstName + "', '" + LastName + "')";
// Add your comments here
91. command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Add your comments here
command.ExecuteNonQuery();
// Add your comments here
strSQL = "Update tblPersonnel " +
"Set PayRate=" + PayRate + ", " +
"StartDate='" + StartDate + "', " +
"EndDate='" + EndDate + "' " +
"Where ID=(Select Max(ID) From tblPersonnel)";
// Add your comments here
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Add your comments here
command.ExecuteNonQuery();
5. Set frmMain as the startup form and run the PayrollSystem
Web application to test the changes. When valid data values are
entered for a new employee, things should work exactly as they
did previously. To test it, enter valid data for a new employee in
frmPersonnel and click Submit. The frmPersonnelVerified form
should be displayed with the entered data values and a message
that the record was saved successfully. Click the View
Personnel button and check that the new personnel record was
indeed saved to the database and that all entered data values,
including the PayRate, StartDate, and EndDate, were stored
92. correctly. Close the browser window.
Now run the PayrollSystem Web application again, but this
time, enter some invalid data (a nonnumeric value) in the
PayRate field to cause an error, like this:
6. Now, when you click Submit, the frmPersonnelVerified form
should display a message indicating that the record
was not saved:
However, when you click on the View Personnel button to
display the personnel records, you should see that an incomplete
personnel record was in fact created, with missing values for the
PayRate, StartDate, and EndDate fields.
This occurred because the Insert statement succeeded but the
following Update statement did not. We do not want to allow
this to happen because we end up with incomplete or incorrect
data in the database. If the Update statement fails, we want the
Insert statement to be rolled back, or undone, so that we end up
with no record at all. We will fix this by adding transaction
code in the next step.
STEP 2: Add Transaction Code
7. In the clsDataLayer.cls class file, add code to the
SavePersonnel() function to create a transaction object. Begin
the transaction, commit the transaction if all database
operations are successful, and roll back the transaction if any
93. database operation fails. The following listing shows the
complete SavePersonnel() function; the lines you will need to
add are marked with ** NEW ** in the preceding comment and
are shown in bold and underlined.
// This function saves the personnel data
public static bool SavePersonnel(string Database, string
FirstName, string LastName,
string PayRate, string StartDate, string
EndDate)
{
bool recordSaved;
// ** NEW ** Add your comments here
OleDbTransaction myTransaction = null;
try
{
// Add your comments here
OleDbConnection conn = new
OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;"
+
"Data Source=" +
Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
94. string strSQL;
// ** NEW ** Add your comments here
myTransaction = conn.BeginTransaction();
command.Transaction = myTransaction;
// Add your comments here
strSQL = "Insert into tblPersonnel " +
"(FirstName, LastName) values ('" +
FirstName + "', '" + LastName + "')";
// Add your comments here
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Add your comments here
command.ExecuteNonQuery();
// Add your comments here
strSQL = "Update tblPersonnel " +
"Set PayRate=" + PayRate + ", " +
"StartDate='" + StartDate + "', " +
"EndDate='" + EndDate + "' " +
"Where ID=(Select Max(ID) From tblPersonnel)";
// Add your comments here
95. command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Add your comments here
command.ExecuteNonQuery();
// ** NEW ** Add your comments here
myTransaction.Commit();
// Add your comments here
conn.Close();
recordSaved = true;
}
catch (Exception ex)
{
// ** NEW ** Add your comments here
myTransaction.Rollback();
recordSaved = false;
}
96. return recordSaved;
}
8. Run your Web application. First, enter valid data in all fields
of frmPersonnel. When you press the Submit button in
frmPersonnel, a record should be saved in the tblPersonnel table
containing the FirstName, LastName, PayRate, StartDate, and
EndDate. With valid data entered in all items, the successfully
saved message should appear, indicating that the transaction
was committed.
Click the View Personnel button and verify that the new record
was in fact added to the database table correctly.
9. Now, close the browser, run the Web application again, and
this time, test that the transaction will roll back after entering
incorrect information. On the frmPersonnel form,
enter invalid data for PayRate and click Submit. The not
saved message should appear, which indicates that the
transaction was rolled back.
Click the View Personnel button and verify that this time, as
desired, an incomplete record was not added to the database
table.
97. 10. You have seen how we used the try/catch block to catch an
unexpected error. You may have noticed that if you enter bad
data for the dates, an exception is thrown. Go back to the
validation code that you added in the frmPersonnel code and
add a try/catch with logic to prevent an invalid date from
causing a server error.
11. In the Week 3 Lab, you learned how to validate code once
the page was posted back to the server. There is some validation
that must be done on the server because it requires server
resources such as the database. Some validation can also be
done on the client. If you can do validation on the client, it
saves a round trip to the server, which will improve
performance. In this approach, we will check values before the
page is submitted to the server for processing. Normally, there
is a combination of server and client validation used in a Web
application. ASP.Net includes validation controls which will
use JavaScript on the client to perform validation. You will find
these controls in the Validation group in the toolbox.
12. Add validation controls to the frmPersonnel form as
follows: For the first, last name, and pay rate, make sure each
field has data in it. Use the RequiredFieldValidator for this
task. Add the control to the right of the text box that you are
validating. The location of the validator control is where the
error message (if there is one) will appear for the control to
which you link the validator. You will be adding one validator
98. control for each text box that you want to validate. Remember
to set the ControlToValidate and ErrorMessage properties on
the validator control. Making this change eliminates the need
for the server-side check you were doing previously. Use
a regular expression validator to check that the start and end
date are in the correct format.
In order to keep the validation controls from causing wrapping,
you may want to increase the Panel width.
A regular expression for mm/dd/yyyy is this:
^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)dd$
13. Remove the View Personnel and Cancel buttons from the
frmPersonnel form, because they will cause a Postback and
invoke the client-side editing that you just added. The user is
able to get to the View Personnel from the main form and from
the personnel verification screen, so there is no need for
these buttons now.
14. Because you have entered data in this lab that is invalid and
those partial records are in the database, you will need to add
the ability to remove or update data. Open up frmMain and add
a new main form option called Edit Employees. Add the link
and image for it. This option will take the user to a new form
called frmEditPersonnel.
15. Add the new form frmEditPersonnel. On frmEditPersonnel,
99. add the ACIT logo at the top of the form. Add a label that
says Edit Employees. Add a GridView control with an ID
of grdEditPersonnel.
16. You will now add a SQLDataSource to the page. You will
be using a databound grid for this form unlike the previous
grids, in which you added as unbound (in the designer).
17. Add a new SQLDataSource control to the frmEditPersonnel
in the Design View. This is not a visible control; that is, it will
only appear in Design View, but the user will never see it. Note:
If you change the folder name or location of your database, you
will need to reconfigure the data source (right-click on the data
source control and select the Configure Data Source option).
18. There is a small > indicator in the Design View of the SQL
Data Source control that you added. If the configuration menu is
collapsed (press it to open the menu), or there is a < with the
menu displayed, from the data source menu, select Configure
Data Source.
19. Press the New Connection button and browse for the
database.
20. Press the Next button.
21. When asked if you want to save the connection in the
application configuration file, check the Yes check box and
press Next.
22. Select the tblPersonnel table.
23. Select all columns (you can use the * for this).
100. 24. Press the Advanced button and check the Generate Insert,
Update, and Delete option and press the OK button.
25. Press the Next button.
26. Press the Test Query button and make sure that you see all
records in the database like the image below. If it does not,
repeat the above steps to make sure that you did everything
properly (and selected the correct database - if you are not sure,
open the database in Windows Explorer to be sure that it is the
one with data in tblPersonnel). Press the Finish button.
27. Click on the grid that you added in the Design View and
expand the Properties menu (the little > in the upper right of the
control). Choose the data source you just added. On the
GridView tasks menu, select Edit columns. Add an Edit,
Update, and Cancel Command field. Add a Delete Command
field. Press OK. You can now test the grid, which is a fully
functioning Update and Delete grid. Try it out!
STEP 3: Test and Submit
28. Once you have verified that everything works as it is
supposed to work, save your project, zip up all files, and submit
it.
NOTE: Make sure you include comments in the code provided
where specified (where the " // Your comments here" is
mentioned) and for any code you write, or else a 5-point