RSS

STEP 1: Modify the clsDataLayer to Use a Two-Step Process

26 Nov

STEP 1: Modify the clsDataLayer to Use a Two-Step Process

  1. Open Microsoft Visual Studio.NET.
  2. Click the ASP.NET project calledPayrollSystemto open it.
  3. Open theclsDataLayerclass.
  4. Modify theSavePersonnel() function so that instead of just doing a singleSQL 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();

  1. SetfrmMainas 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:

  1. Now, when you click Submit, the frmPersonnelVerified form should display a message indicating that the record wasnotsaved:

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

  1. In theclsDataLayer.clsclass 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;     }

  1. Run your Web application. First, entervalid datain 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.

  1. 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, enterinvaliddata 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.

  1. You have seen how we used thetry/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.
  2. In the Week 3 Lab, you learned how tovalidate 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.
  3. Add validation controls to thefrmPersonnel 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)\d\d$

  1. Remove theView 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.
  2. 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 toremove 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.
  3. Add the new formfrmEditPersonnel. 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.
  4. You will now add aSQLDataSource 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).
  5. Add a newSQLDataSource 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).
  6. 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.
  7. Press theNew Connection button and browse for the database.
  8. Press theNext button.
  9. When asked if you want to save the connection in the application configuration file, check theYes check box and press Next.
  10. Select thetblPersonnel table.
  11. Select all columns (you can use the * for this).
  12. Press theAdvanced button and check the Generate Insert, Update, and Delete option and press the OK button.
  13. Press theNext button.
  14. Press theTest 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.
  15. Click on the grid that you added in the Design View and expand theProperties 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 fieldAdd 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

  1. 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.

 

 
Leave a comment

Posted by on November 26, 2016 in academic writing, Academic Writing

 

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: