Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 75 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
75
Dung lượng
863,6 KB
Nội dung
The logic that you implement in the usp_UpdateRole stored procedure in the next Try It Out involves the use of IF statements, variables, and the implementation of error handling. You saw these SQL state- ments in action in the various INSERT stored procedures that you wrote in Chapter 11. Try It Out Admin Form Stored Procedures To complete this exercise: 1. Open your Time Tracker application in Visual Studio 2005. 2. View the Server Explorer window and click the Auto Hide icon on the window to keep it visible and then view the Stored Procedures node for your database. 3. The first stored procedure to be created is the usp_UpdateRole stored procedure. This stored procedure updates a single role in the Roles table. Readers using SQL Server should right-click the Stored Procedures and choose Add New Stored Procedure from the context menu. Readers using Oracle should use their favorite Oracle tool such as iSQL *Plus to create the stored proce- dures. Enter the code for the following stored procedure: SQL Server CREATE PROCEDURE usp_UpdateRole ( @RoleID UNIQUEIDENTIFIER, @RoleName VARCHAR(50), @RoleDescription TEXT, @Ranking TINYINT ) AS Declare local variables DECLARE @ID UNIQUEIDENTIFIER See if the ranking exists SELECT @ID = RoleID FROM Roles WHERE Ranking = @Ranking BEGIN IF @ID IS NOT NULL BEGIN The ranking exists, now verify it doesn’t belong to the role you are updating IF @RoleID <> @ID BEGIN RAISERROR(‘Ranking already exists and cannot be duplicated.’,18,1) RETURN END END END Either the ranking does not exist or it belongs to the role being updated BEGIN TRY UPDATE Roles Set RoleName = @RoleName, RoleDescription = @RoleDescription, Ranking = @Ranking, LastUpdateDate = GETDATE() WHERE RoleID = @RoleID END TRY 438 Chapter 13 16_58894x ch13.qxd 10/13/05 5:58 PM Page 438 BEGIN CATCH BEGIN RAISERROR(‘Update role failed.’,18,1) RETURN END END CATCH Click the Save icon on the toolbar to create the stored procedure. Oracle CREATE OR REPLACE PROCEDURE usp_UpdateRole ( inRoleID CHAR, inRoleName VARCHAR2, inRoleDescription CLOB, inRanking NUMBER ) AS Declare local variables varID CHAR(36); BEGIN BEGIN See if the ranking exists SELECT RoleID INTO varID FROM Roles WHERE Ranking = inRanking; The ranking exists, now verify it doesn’t belong to the role you are updating IF inRoleID <> varID THEN RAISE_APPLICATION_ERROR (-20999, ‘Ranking already exists and cannot be duplicated.’); RETURN; END IF; EXCEPTION WHEN NO_DATA_FOUND THEN Handle the error but perform no processing NULL; END; BEGIN Either the ranking does not exist or it belongs to the role being updated UPDATE Roles Set RoleName = inRoleName, RoleDescription = inRoleDescription, Ranking = inRanking, LastUpdateDate = SYSDATE WHERE RoleID = inRoleID; EXCEPTION WHEN OTHERS THEN RAISE_APPLICATION_ERROR( -20999,’Update role failed.’); RETURN; END; END; 439 Updating Data 16_58894x ch13.qxd 10/13/05 5:58 PM Page 439 Click the Execute button to have the stored procedure created in your database. 4. The next stored procedure that you create is the usp_UpdateUser stored procedure, which updates a user in the Users table. SQL Server users should right-click the Stored Procedures node in the Server Explorer and choose Add New Stored Procedure and Oracle users should use their Oracle tool. Enter the following code: SQL Server CREATE PROCEDURE usp_UpdateUser ( @UserID UNIQUEIDENTIFIER, @LoginName VARCHAR(15), @Password VARCHAR(30), @FirstName VARCHAR(15), @LastName VARCHAR(15), @Email VARCHAR(50), @Phone VARCHAR(20), @Status BIT, @GroupID UNIQUEIDENTIFIER, @RoleID UNIQUEIDENTIFIER, @ManagerID UNIQUEIDENTIFIER ) AS Check to see if the password is blank (no updates to the password) IF LEN(@Password) = 0 BEGIN Get the current password SELECT @Password = Password FROM Users WHERE UserID = @UserID END Update the user BEGIN TRY UPDATE Users SET LoginName = @LoginName, Password = @Password, FirstName = @FirstName, LastName = @LastName, Email = @Email, Phone = @Phone, Status = @Status, GroupID = @GroupID, RoleID = @RoleID, ManagerID = @ManagerID, LastUpdateDate = GETDATE() WHERE UserID = @UserID END TRY BEGIN CATCH BEGIN RAISERROR(‘Update user failed.’,18,1) RETURN END END CATCH 440 Chapter 13 16_58894x ch13.qxd 10/13/05 5:58 PM Page 440 Click the Save icon on the toolbar to have the stored procedure created in your database. Oracle CREATE OR REPLACE PROCEDURE usp_UpdateUser ( inUserID CHAR, inLoginName VARCHAR2, inPassword VARCHAR2, inFirstName VARCHAR2, inLastName VARCHAR2, inEmail VARCHAR2, inPhone VARCHAR2, inStatus NUMBER, inGroupID CHAR, inRoleID CHAR, inManagerID CHAR ) AS Declare local variables varPassword VARCHAR2(30); BEGIN BEGIN Check to see if the password is null (no updates to the password) IF inPassword IS NULL THEN Get the current password SELECT Password INTO varPassword FROM Users WHERE UserID = inUserID; ELSE varPassword := inPassword; END IF; END; BEGIN Update the user UPDATE Users SET LoginName = inLoginName, Password = varPassword, FirstName = inFirstName, LastName = inLastName, Email = inEmail, Phone = inPhone, Status = inStatus, GroupID = inGroupID, RoleID = inRoleID, ManagerID = inManagerID, LastUpdateDate = SYSDATE WHERE UserID = inUserID; EXCEPTION WHEN OTHERS THEN RAISE_APPLICATION_ERROR (-20999,’Update Users failed.’); 441 Updating Data 16_58894x ch13.qxd 10/13/05 5:58 PM Page 441 RETURN; END; END; Click the Execute button to have the stored procedure created in your database. 5. Add some code to your data access component to execute these stored procedures. Starting with the WDARoles class, you add a function to update a role. Add the UpdateRole function to this class: SQL Server Public Function UpdateRole(ByVal Role As DataSet) As Boolean Try MyBase.SQL = “usp_UpdateRole” ‘Initialize the Command object MyBase.InitializeCommand() ‘Add the Parameters to the Parameters collection MyBase.AddParameter(“@RoleID”, _ SqlDbType.UniqueIdentifier, 16, _ Role.Tables(“Role”).Rows(0).Item(“RoleID”)) MyBase.AddParameter(“@RoleName”, _ SqlDbType.VarChar, 50, _ Role.Tables(“Role”).Rows(0).Item(“RoleName”)) MyBase.AddParameter(“@RoleDescription”, _ SqlDbType.Text, _ Role.Tables(“Role”).Rows(0).Item( _ “RoleDescription”).ToString.Length, _ Role.Tables(“Role”).Rows(0).Item(“RoleDescription”)) MyBase.AddParameter(“@Ranking”, _ SqlDbType.TinyInt, 1, _ Role.Tables(“Role”).Rows(0).Item(“Ranking”)) ‘Execute the stored procedure UpdateRole = ExecuteStoredProcedure() Catch ExceptionErr As Exception Throw New System.Exception(ExceptionErr.Message, _ ExceptionErr.InnerException) End Try End Function Oracle Public Function UpdateRole(ByVal Role As DataSet) As Boolean Try MyBase.SQL = “usp_UpdateRole” ‘Initialize the Command object MyBase.InitializeCommand() ‘Add the Parameters to the Parameters collection MyBase.AddParameter(“inRoleID”, _ OracleClient.OracleType.Char, 36, _ Role.Tables(“Role”).Rows(0).Item(“RoleID”).ToString) MyBase.AddParameter(“inRoleName”, _ OracleClient.OracleType.VarChar, 50, _ Role.Tables(“Role”).Rows(0).Item(“RoleName”)) MyBase.AddParameter(“inRoleDescription”, _ OracleClient.OracleType.Clob, _ Role.Tables(“Role”).Rows(0).Item( _ 442 Chapter 13 16_58894x ch13.qxd 10/13/05 5:58 PM Page 442 “RoleDescription”).ToString.Length, _ Role.Tables(“Role”).Rows(0).Item(“RoleDescription”)) MyBase.AddParameter(“inRanking”, _ OracleClient.OracleType.Number, 1, _ Role.Tables(“Role”).Rows(0).Item(“Ranking”)) ‘Execute the stored procedure UpdateRole = ExecuteStoredProcedure() Catch ExceptionErr As Exception Throw New System.Exception(ExceptionErr.Message, _ ExceptionErr.InnerException) End Try End Function 6. Add the UpdateUser function, which is in the WDAUsers class. View the code for that class and add the following function: SQL Server Public Function UpdateUser(ByVal User As DataSet) As Boolean Try MyBase.SQL = “usp_UpdateUser” ‘Initialize the Command object MyBase.InitializeCommand() ‘Add the Parameters to the Parameters collection MyBase.AddParameter(“@UserID”, _ SqlDbType.UniqueIdentifier, 16, _ User.Tables(“User”).Rows(0).Item(“UserID”)) MyBase.AddParameter(“@LoginName”, _ SqlDbType.VarChar, 15, _ User.Tables(“User”).Rows(0).Item(“LoginName”)) MyBase.AddParameter(“@Password”, _ SqlDbType.VarChar, 30, _ User.Tables(“User”).Rows(0).Item(“Password”)) MyBase.AddParameter(“@FirstName”, _ SqlDbType.VarChar, 30, _ User.Tables(“User”).Rows(0).Item(“FirstName”)) MyBase.AddParameter(“@LastName”, _ SqlDbType.VarChar, 30, _ User.Tables(“User”).Rows(0).Item(“LastName”)) MyBase.AddParameter(“@Email”, _ SqlDbType.VarChar, 50, _ User.Tables(“User”).Rows(0).Item(“Email”)) MyBase.AddParameter(“@Phone”, _ SqlDbType.VarChar, 20, _ User.Tables(“User”).Rows(0).Item(“Phone”)) MyBase.AddParameter(“@Status”, _ SqlDbType.Bit, 1, _ User.Tables(“User”).Rows(0).Item(“Status”)) MyBase.AddParameter(“@GroupID”, _ SqlDbType.UniqueIdentifier, 16, _ User.Tables(“User”).Rows(0).Item(“GroupID”)) MyBase.AddParameter(“@RoleID”, _ SqlDbType.UniqueIdentifier, 16, _ User.Tables(“User”).Rows(0).Item(“RoleID”)) MyBase.AddParameter(“@ManagerID”, _ SqlDbType.UniqueIdentifier, 16, _ User.Tables(“User”).Rows(0).Item(“ManagerID”)) 443 Updating Data 16_58894x ch13.qxd 10/13/05 5:58 PM Page 443 ‘Execute the stored procedure UpdateUser = ExecuteStoredProcedure() Catch ExceptionErr As Exception Throw New System.Exception(ExceptionErr.Message, _ ExceptionErr.InnerException) End Try End Function Oracle Public Function UpdateUser(ByVal User As DataSet) As Boolean Try MyBase.SQL = “usp_UpdateUser” ‘Initialize the Command object MyBase.InitializeCommand() ‘Add the Parameters to the Parameters collection MyBase.AddParameter(“inUserID”, _ OracleClient.OracleType.Char, 36, _ User.Tables(“User”).Rows(0).Item(“UserID”).ToString) MyBase.AddParameter(“inLoginName”, _ OracleClient.OracleType.VarChar, 15, _ User.Tables(“User”).Rows(0).Item(“LoginName”)) MyBase.AddParameter(“inPassword”, _ OracleClient.OracleType.VarChar, 30, _ User.Tables(“User”).Rows(0).Item(“Password”)) MyBase.AddParameter(“inFirstName”, _ OracleClient.OracleType.VarChar, 30, _ User.Tables(“User”).Rows(0).Item(“FirstName”)) MyBase.AddParameter(“inLastName”, _ OracleClient.OracleType.VarChar, 30, _ User.Tables(“User”).Rows(0).Item(“LastName”)) MyBase.AddParameter(“inEmail”, _ OracleClient.OracleType.VarChar, 50, _ User.Tables(“User”).Rows(0).Item(“Email”)) MyBase.AddParameter(“inPhone”, _ OracleClient.OracleType.VarChar, 20, _ User.Tables(“User”).Rows(0).Item(“Phone”)) MyBase.AddParameter(“inStatus”, _ OracleClient.OracleType.Number, 1, _ User.Tables(“User”).Rows(0).Item(“Status”)) MyBase.AddParameter(“inGroupID”, _ OracleClient.OracleType.Char, 36, _ User.Tables(“User”).Rows(0).Item(“GroupID”).ToString) MyBase.AddParameter(“inRoleID”, _ OracleClient.OracleType.Char, 36, _ User.Tables(“User”).Rows(0).Item(“RoleID”).ToString) MyBase.AddParameter(“inManagerID”, _ OracleClient.OracleType.Char, 36, _ User.Tables(“User”).Rows(0).Item(“ManagerID”).ToString) ‘Execute the stored procedure UpdateUser = ExecuteStoredProcedure() Catch ExceptionErr As Exception Throw New System.Exception(ExceptionErr.Message, _ ExceptionErr.InnerException) End Try End Function 444 Chapter 13 16_58894x ch13.qxd 10/13/05 5:58 PM Page 444 7. Now you add code in your business logic component to support the functions just added in your data access component. View the code for the WBLRoles class and add the following func- tion to update a role: Public Function UpdateRole(ByVal Role As DataSet) As Boolean Try ‘Validate role data ValidateRoleData(Role) ‘Call the data component to update the role Return objWDARoles.UpdateRole(Role) Catch ExceptionErr As Exception Throw New System.Exception(ExceptionErr.Message, _ ExceptionErr.InnerException) End Try End Function 8. Now view the code for the WBLUsers class and add the UpdateUser function: Public Function UpdateUser(ByVal User As DataSet) As Boolean Try ‘Validate the Login Name exists If User.Tables(“User”).Rows(0).Item( _ “LoginName”).ToString.Trim.Length = 0 Then Throw New System.Exception(“Login Name is a required field.”) End If ‘Validate the First Name exists If User.Tables(“User”).Rows(0).Item( _ “FirstName”).ToString.Trim.Length = 0 Then Throw New System.Exception(“First Name is a required field.”) End If ‘Validate the Last Name exists If User.Tables(“User”).Rows(0).Item( _ “LastName”).ToString.Trim.Length = 0 Then Throw New System.Exception(“Last Name is a required field.”) End If ‘Validate the password If User.Tables(“User”).Rows(0).Item( _ “Password”).ToString.Trim.Length = 0 Then ‘The old password is not being updated so set it to Null User.Tables(“User”).Rows(0).Item(“Password”) = DBNull.Value Else ‘A new password has been supplied If Not IsValidPassword(User.Tables( _ “User”).Rows(0).Item(“Password”)) Then Throw New System.Exception(strErrorMessage) Else ‘Hash the password User.Tables(“User”).Rows(0).Item(“Password”) = _ HashPassword(User.Tables(“User”).Rows(0).Item( _ “Password”)) End If 445 Updating Data 16_58894x ch13.qxd 10/13/05 5:58 PM Page 445 End If ‘Validate the email If Not IsValidEmail(User.Tables( _ “User”).Rows(0).Item(“Email”)) Then Throw New System.Exception(strErrorMessage) End If ‘Validate the phone number If Not IsValidPhoneNumber(User.Tables( _ “User”).Rows(0).Item(“Phone”)) Then Throw New System.Exception(strErrorMessage) End If ‘Validate manager If Not IsDBNull(User.Tables(“User”).Rows(0).Item(“ManagerID”)) Then If Not TypeOf User.Tables(“User”).Rows(0).Item(“ManagerID”) _ Is Guid Then If User.Tables(“User”).Rows(0).Item(“ManagerID”) = _ String.Empty Then ‘Set it to a null value User.Tables(“User”).Rows(0).Item(“ManagerID”) = _ DBNull.Value End If End If End If ‘Trim spaces User.Tables(“User”).Rows(0).Item(“LoginName”) = _ User.Tables(“User”).Rows(0).Item(“LoginName”).ToString.Trim User.Tables(“User”).Rows(0).Item(“Password”) = _ User.Tables(“User”).Rows(0).Item(“Password”).ToString.Trim User.Tables(“User”).Rows(0).Item(“FirstName”) = _ User.Tables(“User”).Rows(0).Item(“FirstName”).ToString.Trim User.Tables(“User”).Rows(0).Item(“LastName”) = _ User.Tables(“User”).Rows(0).Item(“LastName”).ToString.Trim User.Tables(“User”).Rows(0).Item(“Email”) = _ User.Tables(“User”).Rows(0).Item(“Email”).ToString.Trim ‘Format the phone number User.Tables(“User”).Rows(0).Item(“Phone”) = _ FormatPhoneNumber(User.Tables(“User”).Rows(0).Item(“Phone”)) ‘Call the data component to update the user Return objWDAUsers.UpdateUser(User) Catch ExceptionErr As Exception Throw New System.Exception(ExceptionErr.Message, _ ExceptionErr.InnerException) End Try End Function 9. Switch to the code in the Admin form and update it to execute the functions you added in your business logic component. View the code for the ActionUpdate procedure and add the follow- ing code under the Case “Roles” statement: 446 Chapter 13 16_58894x ch13.qxd 10/13/05 5:58 PM Page 446 Case “Roles” ‘Initialize a new instance of the business logic component Using objRoles As New WroxBusinessLogic.WBLRoles( _ strCompany, strApplication) ‘Get a new Role DataSet objDataSet = objRoles.GetNewRoleDS() ‘Initialize a datarow object from the Role DataSet Dim objDataRow As Data.DataRow = _ objDataSet.Tables(“Role”).NewRow ‘Set the values in the DataRow objDataRow.Item(“RoleID”) = New Guid(txtRoleID.Text) objDataRow.Item(“RoleName”) = txtRoleName.Text objDataRow.Item(“RoleDescription”) = _ txtRoleDescription.Text objDataRow.Item(“Ranking”) = _ CType(txtRanking.Text, Byte) ‘Add the DataRow to the DataSet objDataSet.Tables(“Role”).Rows.Add(objDataRow) ‘Update the Role in the database If Not objRoles.UpdateRole(objDataSet) Then Throw New Exception(“Update Role Failed”) End If End Using ‘Clear the input fields txtRoleID.Text = String.Empty txtRoleName.Text = String.Empty txtRoleDescription.Text = String.Empty txtRanking.Text = String.Empty txtRoleUpdateDate.Text = String.Empty ‘Reload the Roles list Call LoadRoles() 10. Now add the following code under the Case “Users” statement in the same procedure: Case “Users” ‘Initialize a new instance of the business logic component Using objUsers As New WroxBusinessLogic.WBLUsers( _ strCompany, strApplication) ‘Get a new User DataSet objDataSet = objUsers.GetNewUserDS() ‘Initialize a datarow object from the Role DataSet Dim objDataRow As Data.DataRow = _ objDataSet.Tables(“User”).NewRow ‘Set the values in the DataRow objDataRow.Item(“UserID”) = New Guid(txtUserID.Text) objDataRow.Item(“LoginName”) = txtLogin.Text objDataRow.Item(“Password”) = txtPassword.Text objDataRow.Item(“FirstName”) = txtFirstName.Text objDataRow.Item(“LastName”) = txtLastName.Text objDataRow.Item(“Email”) = txtEmail.Text objDataRow.Item(“Phone”) = txtPhone.Text objDataRow.Item(“Status”) = optStatusActive.Checked 447 Updating Data 16_58894x ch13.qxd 10/13/05 5:58 PM Page 447 [...]... or her timesheet, as well as the functionality for a manager to approve a timesheet Try It Out Completing the TimeSheet Form To complete this exercise: 1 2 Open your Time Tracker application in Visual Studio 2005 if it is not still open 3 Create the usp_UpdateTimeSheetItem stored procedure first This stored procedure updates a single timesheet item in a timesheet for a user Readers using SQL Server... contains one project per row in the DataSet and a column for each business day of the week for that project You will be calling the update stored procedure for each day of the week in each row Therefore, you basically call the update stored procedure five times for each row of data in the DataSet You see how this is implemented in the SaveTimeSheet function in the data access component in the next exercise... DataRow object to the DataSet Then you call the UpdateUser method in the business logic component and encapsulate that call in an If Then statement to handle any errors that might be thrown from that call 4 57 Chapter 13 If all was successful, you clear the Text property of the text boxes in the User Details section of the Users screen by setting them to an empty string Next, you call the LoadManagers and... TimeSheet.Tables(“TimeSheet”).Rows(intIndex).Item( _ “FridayHours”) SaveTimeSheet = ExecuteStoredProcedure() Next Catch ExceptionErr As Exception Throw New System.Exception(ExceptionErr.Message, _ ExceptionErr.InnerException) End Try End Function 7 Add the SubmitTimeSheet function in the same class next Add the following code: SQL Server Public Function SubmitTimeSheet(ByVal TimeSheetID As Guid) As Boolean Try MyBase.SQL = “usp_SubmitTimeSheet”... Then Throw New Exception(“Save TimeSheet Failed”) End If ‘Display a statusbar message ToolStripStatus.Text = “Timesheet saved” Catch ExceptionErr As Exception MessageBox.Show(ExceptionErr.Message, strAppTitle) End Try End Using End Sub 13 466 When users complete their timesheet for the week, they will submit their timesheet for approval Click the Class Name combo box and select btnSubmit, and in the... becomes read-only Call LoadTimeSheet(cboWeekEnding) ‘Display a statusbar message ToolStripStatus.Text = “Timesheet submitted” Catch ExceptionErr As Exception MessageBox.Show(ExceptionErr.Message, strAppTitle) End Try End Using End Sub 14 When managers approve a timesheet for a user, they click the Approve button You need to add some code to the Click event for that button Click the Class Name combo... Throw New Exception(“Approve TimeSheet Failed”) End If ‘Display a statusbar message ToolStripStatus.Text = “Timesheet approved” Catch ExceptionErr As Exception MessageBox.Show(ExceptionErr.Message, strAppTitle) End Try End Using End Sub That’s all the code that’s needed to complete the functionality in your TimeSheet form To test your changes, start your project and log in as a user When the TimeSheet... will be saved and you’ll see a message in the status bar indicating that the timesheet was saved, as shown in Figure 13-3 You can continue to make changes to the timesheet and save it again if you want 4 67 Chapter 13 Figure 13-3 Now test the functionality of the Submit button Click the Submit button and you see a message in the status bar indicating that the timesheet was submitted, as shown in Figure... handle any errors that may occur and will return the appropriate error message to the caller of this stored procedure SQL Server CREATE PROCEDURE usp_SubmitTimeSheet ( @TimeSheetID UNIQUEIDENTIFIER ) 470 Updating Data AS BEGIN TRY UPDATE TimeSheets SET Submitted = 1 WHERE TimeSheetID = @TimeSheetID END TRY BEGIN CATCH BEGIN RAISERROR(‘Submit timesheet failed.’,18,1) RETURN END END CATCH The Oracle version... to handle any errors that may occur and to pass the appropriate error message to the caller of this stored procedure SQL Server CREATE PROCEDURE usp_ApproveTimeSheet ( @TimeSheetID UNIQUEIDENTIFIER, 471 Chapter 13 @ManagerID UNIQUEIDENTIFIER ) AS BEGIN TRY UPDATE TimeSheets SET ApprovalDate = GETDATE(), ManagerID = @ManagerID WHERE TimeSheetID = @TimeSheetID END TRY BEGIN CATCH BEGIN RAISERROR(‘Approve . Form Stored Procedures To complete this exercise: 1. Open your Time Tracker application in Visual Studio 2005. 2. View the Server Explorer window and click the Auto Hide icon on the window to keep. txtPhone.Text objDataRow.Item(“Status”) = optStatusActive.Checked 4 47 Updating Data 16_58894x ch13.qxd 10/13/05 5:58 PM Page 4 47 objDataRow.Item(“GroupID”) = _ cboUserGroup.SelectedItem.Item(“GroupID”) objDataRow.Item(“RoleID”). Then statement to handle any errors that might be thrown from that call. 4 57 Updating Data 16_58894x ch13.qxd 10/13/05 5:58 PM Page 4 57