SlideShare ist ein Scribd-Unternehmen logo
1 von 45
This is part 1 of 3
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, 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
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
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 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();
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
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;
}
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.
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 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, 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).
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 to the Dropbox.
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 deduction per item
(form, class, function) will be made
This is Part 2
STEP 1: Data Layer
1.
Open Microsoft Visual Studio.NET.
2.
Click the ASP.NET project called PayrollSystem to open it.
3.
Open the clsDataLayer class and add the following function:
// This function saves the personnel data
public
static
bool
SavePersonnel
(
string
Database
,
string
FirstName
,
string
LastName
,
string
PayRate
,
string
StartDate
,
string
EndDate
)
{
bool recordSaved
;
try
{
// Add your comments here
OleDbConnection
conn
=
new
OleDbConnection
(
"PROVIDER=Microsoft.ACE.OLEDB.12.0;"
+
"Data Source="
+
Database
);
conn
.
Open
();
OleDbCommand
command
=
conn
.
CreateCommand
();
string
strSQL
;
// 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
();
// Add your comments here
conn
.
Close
();
recordSaved
=
true
;
}
catch
(
Exception
ex
)
{
recordSaved
=
false
;
}
return
recordSaved
;
}
4. In the
frmPersonnelVerified
form, go to the
Page_Load()
event and add the following code after the existing code (but
still in the Page_Load event handler):
// Add your comments here
if
(
clsDataLayer
.
SavePersonnel
(
Server
.
MapPath
(
"PayrollSystem_DB.accdb"
),
Session
[
"txtFirstName"
].
ToString
(),
Session
[
"txtLastName"
].
ToString
(),
Session
[
"txtPayRate"
].
ToString
(),
Session
[
"txtStartDate"
].
ToString
(),
Session
[
"txtEndDate"
].
ToString
()))
{
txtVerifiedInfo
.
Text
=
txtVerifiedInfo
.
Text
+
"nThe information was successfully saved!"
;
}
else
{
txtVerifiedInfo
.
Text
=
txtVerifiedInfo
.
Text
+
"nThe information was NOT saved."
;
}
5. Add comments for all code containing // Add your comments
here.
6. Test your work to make sure that no errors occur! (Make sure
to put in valid date values for the date data entry fields).
STEP 2: Data Display and Search
7. Using the skills that you learned in Week 3, create a new
DataSet
for the
tblPersonnel
table (call the DataSet
dsPersonnel
).
8. Using the skills that you learned in Week 3, create a new
function called
GetPersonnel
in the
clsDataLayer
class. This function should retrieve all data from the
tblPersonnel
table and return it in the form of a
dsPersonnel DataSet.
Use the
GetUserActivity
function as an example.
9. Create a new Web form called
frmViewPersonnel
.
10. Using the skills that you learned in Week 3, add a
GridView
control (called
grdViewPersonnel
) to the form. This GridView control will be used to display
data from the tblPersonnel table. Add the
ACIT logo
at the top of the page and make sure it links back to
frmMain
.
11. Add the following code to the Page_Load() function in
frmViewPersonnel
.
if
(!
Page
.
IsPostBack
)
{
//Declare the Dataset
dsPersonnel myDataSet
=
new
dsPersonnel
();
//Fill the dataset with shat is returned from the method.
myDataSet
=
clsDataLayer
.
GetPersonnel
(
Server
.
MapPath
(
"PayrollSystem_DB.accdb"
));
//Set the DataGrid to the DataSource based on the table
grdViewPersonnel
.
DataSource
=
myDataSet
.
Tables
[
"tblPersonnel"
];
//Bind the DataGrid
grdViewPersonnel
.
DataBind
();
}
12. Return to the
frmPersonnel
Web form and add a button
((ID) = btnViewPersonnel,
Text = View Personnel
) which, when clicked, will display form
frmViewPersonnel
.
13. Open the
frmPersonnelVerified
form and add a button (
(ID) = btnViewPersonnel
,
Text = View Personnel
) which, when clicked, will display form
frmViewPersonnel
. NOTE: This is the same button with the same functionality
that you added to form
frmPersonnel
in the previous step. Also, add a new link and linked image to
frmMain
called
View Personnel
that will go to the new
frmViewPersonnel
page you created.
Let's test the View Personnel page. Start your program in
Internet Explorer. Click on Add New Employee and add
yourself to the database and press Submit. Once you are on the
personnel verified form, click the View Personnel button. You
should see the data that you just entered.
14. You will now add a
Search
feature to allow the user to find and display data. The user will
enter a
last name
and the Web application will display the grid of employees
with all employees that match that last name.
15. Create a new Web form called
frmSearchPersonnel
. Add the hyperlinked ACIT logo to this page. Also, add a new
item on
frmMain
(with a Link button and Image button) called
Search Personnel.
16. On the
frmSearchPersonnel
form, add a label that displays
"Search for employee by last name:"
. Next to the label, add a text box with an ID of
txtSearch
. Add a button with an ID of
btnSearch
and set the text of the button to "
Search
".
17. When the
frmSearchPersonnel
Search button is pressed, the
frmViewPersonnel
is displayed. At this point, no searching is actually happening,
but you have the forms that you need and the navigation is
working. Now you can focus on the coding that you will need to
do to have the grid only display matching employees.
18. Before calling the GetPersonnel method that you added
previously in the lab, you will need to get the value that is in
the Request["txtSearch"] item. When the form posts the search
page results to the frmViewPersonnel, the name value pair for
the search value is passed as part of the Request object. This
value will need to be assigned to a string variable. To do this
task, add the following line of code in the code block below to
the
Page_Load
function in
frmViewPersonnel
after
the line: dsPersonnel myDataSet = new dsPersonnel();
string
strSearch
=
Request
[
"txtSearch"
];
Then, modify the call of the GetPersonnel function one line
below to add the strSearch as one of the arguments:
myDataSet
=
clsDataLayer
.
GetPersonnel
(
Server
.
MapPath
(
"PayrollSystem_DB.accdb"
),
strSearch
);
19. Modify the
GetPersonnel
method that you added in the clsDataLayer.cs class to include a
new parameter called strSearch of type string. Add string
strSearch as an argument to the function as below:
public
static
dsPersonnel
GetPersonnel
(
string
Database
,
string
strSearch
)
Then modify the
sqlDA
select statement within the GetPersonnel function to test if a
value is entered for a search parameter.
if
(
strSearch
==
null
||
strSearch
.
Trim
()==
""
)
{
sqlDA
=
new
OleDbDataAdapter
(
"select * from tblPersonnel"
,
sqlConn
);
}
else
{
sqlDA
=
new
OleDbDataAdapter
(
"select * from tblPersonnel where LastName = '"
+
strSearch
+
"'"
,
sqlConn
);
}
20. Test the search so that when you enter a last name,
employees with that last name are returned. Make sure that
when you access frmViewPersonnel and you are not searching,
all employees are returned.
STEP 3: Test and Submit
Run your project and test it as follows:
The frmMain form should be displayed first.
Click on the
Add New Employee hyperlink
to go to the frmPersonnel data entry form. Click the View
Personnel button on this form. The frmViewPersonnel form
should be displayed in the browser, but at this point, there
should not be very many personnel listed.
Use the Back button in your Web browser to return to the
frmPersonnel form and enter some personnel data for a few
employees, similar to the following:
Now, click the Submit button. The frmPersonnelVerified form
should be displayed, showing the data you entered, and you
should get a message saying that the data were successfully
saved, like this example.
You should be able to view the employee records by clicking
the View Personnel link on the home page.
Test the Search feature and make sure that entering no search
string returns all of the data and that typing in a last name will
return all employees with the same last name.
NOTE
:
Make sure that you include comments in the code provided
where specified (where the " // Your comments here" line
appears) and for any code that you write, or else a 5-point
deduction per item (form, class, function) will be made.
This is Part 3
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, 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
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
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 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();
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
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;
}
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.
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 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, 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).
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 to the Dropbox.
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 deduction per item
(form, class, function) will be made.

Weitere ähnliche Inhalte

Ähnlich wie This is part 1 of 3STEP 1 Modify the clsDataLayer to Use a Two-St.docx

Be sure to read all of Chapters 8 and 9 before starting this assignm.docx
Be sure to read all of Chapters 8 and 9 before starting this assignm.docxBe sure to read all of Chapters 8 and 9 before starting this assignm.docx
Be sure to read all of Chapters 8 and 9 before starting this assignm.docxaman341480
 
Sales force class-3
Sales force class-3Sales force class-3
Sales force class-3Amit Sharma
 
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx        Greetings and Salutations.docxCIS407AWk2iLabDefault.aspx        Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docxclarebernice
 
Cis407 a ilab 6 web application development devry university
Cis407 a ilab 6 web application development devry universityCis407 a ilab 6 web application development devry university
Cis407 a ilab 6 web application development devry universitylhkslkdh89009
 
Cis407 a ilab 1 web application development devry university
Cis407 a ilab 1 web application development devry universityCis407 a ilab 1 web application development devry university
Cis407 a ilab 1 web application development devry universitylhkslkdh89009
 
Cis 407 i lab 6 of 7
Cis 407 i lab 6 of 7Cis 407 i lab 6 of 7
Cis 407 i lab 6 of 7helpido9
 
Cis 407 i lab 1 of 7
Cis 407 i lab 1 of 7Cis 407 i lab 1 of 7
Cis 407 i lab 1 of 7helpido9
 
Tony Vitabile .Net Portfolio
Tony Vitabile .Net PortfolioTony Vitabile .Net Portfolio
Tony Vitabile .Net Portfoliovitabile
 
People code events 1
People code events 1People code events 1
People code events 1Samarth Arora
 
130297267 transformations
130297267 transformations130297267 transformations
130297267 transformationsSunil Pandey
 
Detail view in distributed technologies
Detail view in distributed technologiesDetail view in distributed technologies
Detail view in distributed technologiesjamessakila
 
142500146 using-oracle-fast formula-for-payroll-calculations
142500146 using-oracle-fast formula-for-payroll-calculations142500146 using-oracle-fast formula-for-payroll-calculations
142500146 using-oracle-fast formula-for-payroll-calculationsuday reddy
 
Access tips access and sql part 6 dynamic reports
Access tips  access and sql part 6  dynamic reportsAccess tips  access and sql part 6  dynamic reports
Access tips access and sql part 6 dynamic reportsquest2900
 
Scoring documentation
Scoring documentationScoring documentation
Scoring documentationFatima Khalid
 

Ähnlich wie This is part 1 of 3STEP 1 Modify the clsDataLayer to Use a Two-St.docx (20)

Bam
BamBam
Bam
 
Bam
BamBam
Bam
 
Bam
BamBam
Bam
 
Be sure to read all of Chapters 8 and 9 before starting this assignm.docx
Be sure to read all of Chapters 8 and 9 before starting this assignm.docxBe sure to read all of Chapters 8 and 9 before starting this assignm.docx
Be sure to read all of Chapters 8 and 9 before starting this assignm.docx
 
Sales force class-3
Sales force class-3Sales force class-3
Sales force class-3
 
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx        Greetings and Salutations.docxCIS407AWk2iLabDefault.aspx        Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docx
 
OLT open script
OLT open script OLT open script
OLT open script
 
Cis407 a ilab 6 web application development devry university
Cis407 a ilab 6 web application development devry universityCis407 a ilab 6 web application development devry university
Cis407 a ilab 6 web application development devry university
 
Cis407 a ilab 1 web application development devry university
Cis407 a ilab 1 web application development devry universityCis407 a ilab 1 web application development devry university
Cis407 a ilab 1 web application development devry university
 
Cis 407 i lab 6 of 7
Cis 407 i lab 6 of 7Cis 407 i lab 6 of 7
Cis 407 i lab 6 of 7
 
Salary advanceworkflow
Salary advanceworkflowSalary advanceworkflow
Salary advanceworkflow
 
Cis 407 i lab 1 of 7
Cis 407 i lab 1 of 7Cis 407 i lab 1 of 7
Cis 407 i lab 1 of 7
 
Tony Vitabile .Net Portfolio
Tony Vitabile .Net PortfolioTony Vitabile .Net Portfolio
Tony Vitabile .Net Portfolio
 
data binding.docx
data binding.docxdata binding.docx
data binding.docx
 
People code events 1
People code events 1People code events 1
People code events 1
 
130297267 transformations
130297267 transformations130297267 transformations
130297267 transformations
 
Detail view in distributed technologies
Detail view in distributed technologiesDetail view in distributed technologies
Detail view in distributed technologies
 
142500146 using-oracle-fast formula-for-payroll-calculations
142500146 using-oracle-fast formula-for-payroll-calculations142500146 using-oracle-fast formula-for-payroll-calculations
142500146 using-oracle-fast formula-for-payroll-calculations
 
Access tips access and sql part 6 dynamic reports
Access tips  access and sql part 6  dynamic reportsAccess tips  access and sql part 6  dynamic reports
Access tips access and sql part 6 dynamic reports
 
Scoring documentation
Scoring documentationScoring documentation
Scoring documentation
 

Mehr von abhi353063

number 1answer this in a paragraphShare the findings of your DiS.docx
number 1answer this in a paragraphShare the findings of your DiS.docxnumber 1answer this in a paragraphShare the findings of your DiS.docx
number 1answer this in a paragraphShare the findings of your DiS.docxabhi353063
 
number 1complete the attached test called the urbulence Tole.docx
number 1complete the attached test called the urbulence Tole.docxnumber 1complete the attached test called the urbulence Tole.docx
number 1complete the attached test called the urbulence Tole.docxabhi353063
 
number 1Are you a born leader If yes, provide examples of how y.docx
number 1Are you a born leader If yes, provide examples of how y.docxnumber 1Are you a born leader If yes, provide examples of how y.docx
number 1Are you a born leader If yes, provide examples of how y.docxabhi353063
 
number 1complete the attached test called the urbulence Tole.docx
number 1complete the attached test called the urbulence Tole.docxnumber 1complete the attached test called the urbulence Tole.docx
number 1complete the attached test called the urbulence Tole.docxabhi353063
 
number 1answer this one in a pargraphAlthough you may not be.docx
number 1answer this one in a pargraphAlthough you may not be.docxnumber 1answer this one in a pargraphAlthough you may not be.docx
number 1answer this one in a pargraphAlthough you may not be.docxabhi353063
 
Nr  QuestionMarkDiscuss the three main environments that make.docx
Nr  QuestionMarkDiscuss the three main environments that make.docxNr  QuestionMarkDiscuss the three main environments that make.docx
Nr  QuestionMarkDiscuss the three main environments that make.docxabhi353063
 
nron Corporation was launched in 1985, with the merger of Houston Na.docx
nron Corporation was launched in 1985, with the merger of Houston Na.docxnron Corporation was launched in 1985, with the merger of Houston Na.docx
nron Corporation was launched in 1985, with the merger of Houston Na.docxabhi353063
 
Now that you have your GUI operational, it is time to take the appli.docx
Now that you have your GUI operational, it is time to take the appli.docxNow that you have your GUI operational, it is time to take the appli.docx
Now that you have your GUI operational, it is time to take the appli.docxabhi353063
 
Now that you understand the full project lifecycle and how all the p.docx
Now that you understand the full project lifecycle and how all the p.docxNow that you understand the full project lifecycle and how all the p.docx
Now that you understand the full project lifecycle and how all the p.docxabhi353063
 
Now that you sre beginig your second semester as astudent at Califor.docx
Now that you sre beginig your second semester as astudent at Califor.docxNow that you sre beginig your second semester as astudent at Califor.docx
Now that you sre beginig your second semester as astudent at Califor.docxabhi353063
 
Now that you have developed an in-text citation for a summary, parap.docx
Now that you have developed an in-text citation for a summary, parap.docxNow that you have developed an in-text citation for a summary, parap.docx
Now that you have developed an in-text citation for a summary, parap.docxabhi353063
 
Now that you have completed the sections on fiscal and monetary poli.docx
Now that you have completed the sections on fiscal and monetary poli.docxNow that you have completed the sections on fiscal and monetary poli.docx
Now that you have completed the sections on fiscal and monetary poli.docxabhi353063
 
Now that we have decided to become an S Corp after reviewing the var.docx
Now that we have decided to become an S Corp after reviewing the var.docxNow that we have decided to become an S Corp after reviewing the var.docx
Now that we have decided to become an S Corp after reviewing the var.docxabhi353063
 
Novel Shift by Em BaileyDescribe each of the minor characters i.docx
Novel Shift by Em BaileyDescribe each of the minor characters i.docxNovel Shift by Em BaileyDescribe each of the minor characters i.docx
Novel Shift by Em BaileyDescribe each of the minor characters i.docxabhi353063
 
Nothing in science is written in stone.Whenever new discoveries .docx
Nothing in science is written in stone.Whenever new discoveries .docxNothing in science is written in stone.Whenever new discoveries .docx
Nothing in science is written in stone.Whenever new discoveries .docxabhi353063
 
Now my experiment was to go to randomly selected people and ask th.docx
Now my experiment was to go to randomly selected people and ask th.docxNow my experiment was to go to randomly selected people and ask th.docx
Now my experiment was to go to randomly selected people and ask th.docxabhi353063
 
Notice Due today before 12 am pacifAssignment 1 Discussion—Soci.docx
Notice Due today before 12 am pacifAssignment 1 Discussion—Soci.docxNotice Due today before 12 am pacifAssignment 1 Discussion—Soci.docx
Notice Due today before 12 am pacifAssignment 1 Discussion—Soci.docxabhi353063
 
Notes on Hermes I. Hermes and Boundaries A. Hermes’ na.docx
Notes on Hermes I. Hermes and Boundaries A. Hermes’ na.docxNotes on Hermes I. Hermes and Boundaries A. Hermes’ na.docx
Notes on Hermes I. Hermes and Boundaries A. Hermes’ na.docxabhi353063
 
Note. The purpose of this outline is to assist you in gathering th.docx
Note. The purpose of this outline is to assist you in gathering th.docxNote. The purpose of this outline is to assist you in gathering th.docx
Note. The purpose of this outline is to assist you in gathering th.docxabhi353063
 
Note1. The Topic of research is Roller derbysubculture name .docx
Note1. The Topic of research is Roller derbysubculture name .docxNote1. The Topic of research is Roller derbysubculture name .docx
Note1. The Topic of research is Roller derbysubculture name .docxabhi353063
 

Mehr von abhi353063 (20)

number 1answer this in a paragraphShare the findings of your DiS.docx
number 1answer this in a paragraphShare the findings of your DiS.docxnumber 1answer this in a paragraphShare the findings of your DiS.docx
number 1answer this in a paragraphShare the findings of your DiS.docx
 
number 1complete the attached test called the urbulence Tole.docx
number 1complete the attached test called the urbulence Tole.docxnumber 1complete the attached test called the urbulence Tole.docx
number 1complete the attached test called the urbulence Tole.docx
 
number 1Are you a born leader If yes, provide examples of how y.docx
number 1Are you a born leader If yes, provide examples of how y.docxnumber 1Are you a born leader If yes, provide examples of how y.docx
number 1Are you a born leader If yes, provide examples of how y.docx
 
number 1complete the attached test called the urbulence Tole.docx
number 1complete the attached test called the urbulence Tole.docxnumber 1complete the attached test called the urbulence Tole.docx
number 1complete the attached test called the urbulence Tole.docx
 
number 1answer this one in a pargraphAlthough you may not be.docx
number 1answer this one in a pargraphAlthough you may not be.docxnumber 1answer this one in a pargraphAlthough you may not be.docx
number 1answer this one in a pargraphAlthough you may not be.docx
 
Nr  QuestionMarkDiscuss the three main environments that make.docx
Nr  QuestionMarkDiscuss the three main environments that make.docxNr  QuestionMarkDiscuss the three main environments that make.docx
Nr  QuestionMarkDiscuss the three main environments that make.docx
 
nron Corporation was launched in 1985, with the merger of Houston Na.docx
nron Corporation was launched in 1985, with the merger of Houston Na.docxnron Corporation was launched in 1985, with the merger of Houston Na.docx
nron Corporation was launched in 1985, with the merger of Houston Na.docx
 
Now that you have your GUI operational, it is time to take the appli.docx
Now that you have your GUI operational, it is time to take the appli.docxNow that you have your GUI operational, it is time to take the appli.docx
Now that you have your GUI operational, it is time to take the appli.docx
 
Now that you understand the full project lifecycle and how all the p.docx
Now that you understand the full project lifecycle and how all the p.docxNow that you understand the full project lifecycle and how all the p.docx
Now that you understand the full project lifecycle and how all the p.docx
 
Now that you sre beginig your second semester as astudent at Califor.docx
Now that you sre beginig your second semester as astudent at Califor.docxNow that you sre beginig your second semester as astudent at Califor.docx
Now that you sre beginig your second semester as astudent at Califor.docx
 
Now that you have developed an in-text citation for a summary, parap.docx
Now that you have developed an in-text citation for a summary, parap.docxNow that you have developed an in-text citation for a summary, parap.docx
Now that you have developed an in-text citation for a summary, parap.docx
 
Now that you have completed the sections on fiscal and monetary poli.docx
Now that you have completed the sections on fiscal and monetary poli.docxNow that you have completed the sections on fiscal and monetary poli.docx
Now that you have completed the sections on fiscal and monetary poli.docx
 
Now that we have decided to become an S Corp after reviewing the var.docx
Now that we have decided to become an S Corp after reviewing the var.docxNow that we have decided to become an S Corp after reviewing the var.docx
Now that we have decided to become an S Corp after reviewing the var.docx
 
Novel Shift by Em BaileyDescribe each of the minor characters i.docx
Novel Shift by Em BaileyDescribe each of the minor characters i.docxNovel Shift by Em BaileyDescribe each of the minor characters i.docx
Novel Shift by Em BaileyDescribe each of the minor characters i.docx
 
Nothing in science is written in stone.Whenever new discoveries .docx
Nothing in science is written in stone.Whenever new discoveries .docxNothing in science is written in stone.Whenever new discoveries .docx
Nothing in science is written in stone.Whenever new discoveries .docx
 
Now my experiment was to go to randomly selected people and ask th.docx
Now my experiment was to go to randomly selected people and ask th.docxNow my experiment was to go to randomly selected people and ask th.docx
Now my experiment was to go to randomly selected people and ask th.docx
 
Notice Due today before 12 am pacifAssignment 1 Discussion—Soci.docx
Notice Due today before 12 am pacifAssignment 1 Discussion—Soci.docxNotice Due today before 12 am pacifAssignment 1 Discussion—Soci.docx
Notice Due today before 12 am pacifAssignment 1 Discussion—Soci.docx
 
Notes on Hermes I. Hermes and Boundaries A. Hermes’ na.docx
Notes on Hermes I. Hermes and Boundaries A. Hermes’ na.docxNotes on Hermes I. Hermes and Boundaries A. Hermes’ na.docx
Notes on Hermes I. Hermes and Boundaries A. Hermes’ na.docx
 
Note. The purpose of this outline is to assist you in gathering th.docx
Note. The purpose of this outline is to assist you in gathering th.docxNote. The purpose of this outline is to assist you in gathering th.docx
Note. The purpose of this outline is to assist you in gathering th.docx
 
Note1. The Topic of research is Roller derbysubculture name .docx
Note1. The Topic of research is Roller derbysubculture name .docxNote1. The Topic of research is Roller derbysubculture name .docx
Note1. The Topic of research is Roller derbysubculture name .docx
 

Kürzlich hochgeladen

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 

Kürzlich hochgeladen (20)

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 

This is part 1 of 3STEP 1 Modify the clsDataLayer to Use a Two-St.docx

  • 1. This is part 1 of 3 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, 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 ('" +
  • 2. FirstName + "', '" + LastName + "', " + PayRate + ", '" + StartDate + "', '" + EndDate + "')" ; // Add your comments here command . CommandType = CommandType . Text ; command . CommandText
  • 3. = 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 command . CommandType = CommandType
  • 4. . Text ; command . CommandText = strSQL ; // Add your comments here command . ExecuteNonQuery (); // Add your comments here strSQL = "Update tblPersonnel " + "Set PayRate=" + PayRate + ", " + "StartDate='" + StartDate + "', "
  • 5. + "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
  • 6. 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 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
  • 7. transaction if any 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
  • 8. OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Database); conn.Open(); OleDbCommand command = conn.CreateCommand(); 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;
  • 9. 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
  • 10. 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
  • 11. myTransaction.Rollback() ; recordSaved = false; } 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
  • 12. 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. 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
  • 13. 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 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
  • 14. frmEditPersonnel . On frmEditPersonnel, 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
  • 15. 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). 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!
  • 16. 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 to the Dropbox. 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 deduction per item (form, class, function) will be made This is Part 2 STEP 1: Data Layer 1. Open Microsoft Visual Studio.NET. 2. Click the ASP.NET project called PayrollSystem to open it. 3. Open the clsDataLayer class and add the following function: // This function saves the personnel data public static bool SavePersonnel ( string Database , string FirstName , string LastName ,
  • 17. string PayRate , string StartDate , string EndDate ) { bool recordSaved ; try { // Add your comments here OleDbConnection conn = new OleDbConnection ( "PROVIDER=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Database ); conn . Open (); OleDbCommand command = conn .
  • 18. CreateCommand (); string strSQL ; // Add your comments here strSQL = "Insert into tblPersonnel " + "(FirstName, LastName, PayRate, StartDate, EndDate) values ('" + FirstName + "', '" + LastName + "', " + PayRate + ", '" + StartDate + "', '" + EndDate + "')" ; // Add your comments here command .
  • 19. CommandType = CommandType . Text ; command . CommandText = strSQL ; // Add your comments here command . ExecuteNonQuery (); // Add your comments here conn . Close (); recordSaved = true ; } catch ( Exception ex ) { recordSaved = false
  • 20. ; } return recordSaved ; } 4. In the frmPersonnelVerified form, go to the Page_Load() event and add the following code after the existing code (but still in the Page_Load event handler): // Add your comments here if ( clsDataLayer . SavePersonnel ( Server . MapPath ( "PayrollSystem_DB.accdb" ), Session [ "txtFirstName" ]. ToString (), Session [ "txtLastName"
  • 22. . Text = txtVerifiedInfo . Text + "nThe information was NOT saved." ; } 5. Add comments for all code containing // Add your comments here. 6. Test your work to make sure that no errors occur! (Make sure to put in valid date values for the date data entry fields). STEP 2: Data Display and Search 7. Using the skills that you learned in Week 3, create a new DataSet for the tblPersonnel table (call the DataSet dsPersonnel ). 8. Using the skills that you learned in Week 3, create a new function called GetPersonnel in the clsDataLayer class. This function should retrieve all data from the tblPersonnel table and return it in the form of a dsPersonnel DataSet. Use the GetUserActivity function as an example.
  • 23. 9. Create a new Web form called frmViewPersonnel . 10. Using the skills that you learned in Week 3, add a GridView control (called grdViewPersonnel ) to the form. This GridView control will be used to display data from the tblPersonnel table. Add the ACIT logo at the top of the page and make sure it links back to frmMain . 11. Add the following code to the Page_Load() function in frmViewPersonnel . if (! Page . IsPostBack ) { //Declare the Dataset dsPersonnel myDataSet = new dsPersonnel (); //Fill the dataset with shat is returned from the method. myDataSet = clsDataLayer
  • 24. . GetPersonnel ( Server . MapPath ( "PayrollSystem_DB.accdb" )); //Set the DataGrid to the DataSource based on the table grdViewPersonnel . DataSource = myDataSet . Tables [ "tblPersonnel" ]; //Bind the DataGrid grdViewPersonnel . DataBind (); } 12. Return to the frmPersonnel Web form and add a button ((ID) = btnViewPersonnel, Text = View Personnel ) which, when clicked, will display form frmViewPersonnel .
  • 25. 13. Open the frmPersonnelVerified form and add a button ( (ID) = btnViewPersonnel , Text = View Personnel ) which, when clicked, will display form frmViewPersonnel . NOTE: This is the same button with the same functionality that you added to form frmPersonnel in the previous step. Also, add a new link and linked image to frmMain called View Personnel that will go to the new frmViewPersonnel page you created. Let's test the View Personnel page. Start your program in Internet Explorer. Click on Add New Employee and add yourself to the database and press Submit. Once you are on the personnel verified form, click the View Personnel button. You should see the data that you just entered. 14. You will now add a Search feature to allow the user to find and display data. The user will enter a last name and the Web application will display the grid of employees with all employees that match that last name. 15. Create a new Web form called frmSearchPersonnel
  • 26. . Add the hyperlinked ACIT logo to this page. Also, add a new item on frmMain (with a Link button and Image button) called Search Personnel. 16. On the frmSearchPersonnel form, add a label that displays "Search for employee by last name:" . Next to the label, add a text box with an ID of txtSearch . Add a button with an ID of btnSearch and set the text of the button to " Search ". 17. When the frmSearchPersonnel Search button is pressed, the frmViewPersonnel is displayed. At this point, no searching is actually happening, but you have the forms that you need and the navigation is working. Now you can focus on the coding that you will need to do to have the grid only display matching employees. 18. Before calling the GetPersonnel method that you added previously in the lab, you will need to get the value that is in the Request["txtSearch"] item. When the form posts the search page results to the frmViewPersonnel, the name value pair for the search value is passed as part of the Request object. This value will need to be assigned to a string variable. To do this task, add the following line of code in the code block below to the Page_Load
  • 27. function in frmViewPersonnel after the line: dsPersonnel myDataSet = new dsPersonnel(); string strSearch = Request [ "txtSearch" ]; Then, modify the call of the GetPersonnel function one line below to add the strSearch as one of the arguments: myDataSet = clsDataLayer . GetPersonnel ( Server . MapPath ( "PayrollSystem_DB.accdb" ), strSearch ); 19. Modify the GetPersonnel method that you added in the clsDataLayer.cs class to include a new parameter called strSearch of type string. Add string strSearch as an argument to the function as below: public static dsPersonnel
  • 28. GetPersonnel ( string Database , string strSearch ) Then modify the sqlDA select statement within the GetPersonnel function to test if a value is entered for a search parameter. if ( strSearch == null || strSearch . Trim ()== "" ) { sqlDA = new OleDbDataAdapter ( "select * from tblPersonnel" , sqlConn ); } else
  • 29. { sqlDA = new OleDbDataAdapter ( "select * from tblPersonnel where LastName = '" + strSearch + "'" , sqlConn ); } 20. Test the search so that when you enter a last name, employees with that last name are returned. Make sure that when you access frmViewPersonnel and you are not searching, all employees are returned. STEP 3: Test and Submit Run your project and test it as follows: The frmMain form should be displayed first. Click on the Add New Employee hyperlink to go to the frmPersonnel data entry form. Click the View Personnel button on this form. The frmViewPersonnel form should be displayed in the browser, but at this point, there should not be very many personnel listed. Use the Back button in your Web browser to return to the frmPersonnel form and enter some personnel data for a few employees, similar to the following: Now, click the Submit button. The frmPersonnelVerified form should be displayed, showing the data you entered, and you should get a message saying that the data were successfully saved, like this example. You should be able to view the employee records by clicking
  • 30. the View Personnel link on the home page. Test the Search feature and make sure that entering no search string returns all of the data and that typing in a last name will return all employees with the same last name. NOTE : Make sure that you include comments in the code provided where specified (where the " // Your comments here" line appears) and for any code that you write, or else a 5-point deduction per item (form, class, function) will be made. This is Part 3 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
  • 31. with only the FirstName and LastName, followed by an UPDATE to save the PayRate, 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 + ", '" +
  • 32. 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 "
  • 33. + "(FirstName, LastName) values ('" + FirstName + "', '" + LastName + "')" ; // Add your comments here command . CommandType = CommandType . Text ; command . CommandText = strSQL ; // Add your comments here command . ExecuteNonQuery ();
  • 34. // 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
  • 35. . 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 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
  • 36. 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 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) {
  • 37. 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(); 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 " +
  • 38. "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(); // ** 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; }
  • 39. 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
  • 40. not added to the database table. 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
  • 41. 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 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
  • 42. 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, 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
  • 43. 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
  • 44. 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). 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
  • 45. 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 to the Dropbox. 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 deduction per item (form, class, function) will be made.