1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning Visual Basic 2005 Databases phần 4 pot

75 279 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Nội dung

AS BEGIN DELETE FROM GroupProjects WHERE GroupID = inGroupID; END; At this point, you have all of the views and stored procedures needed to insert, display, and delete group projects in your Time Tracker application. All that is left to do is to modify your application to implement these views and stored procedures. In the next Try It Out, you implement the code to select data from the vw_SelectGroupProjects view to display all projects for a specific group. You also implement the code to insert, update, and delete group projects in the GroupProjects table. In addition, you implement drag-and-drop functionality into your application. A complete list of available projects will be displayed in one ListBox control from which you drag the projects and drop them into another ListBox to be added to a group. Try It Out Implementing Views and Stored Procedures in VB 2005 To implement this functionality: 1. Open your Time Tracker project in Visual Studio 2005 and view the code for the Admin form. 2. Add the following variable declarations at the top of your form class: Private blnLoading As Boolean Private objGroupsDS As DataSet Private objProjectsDS As DataSet Private objGroupProjectsDS As DataSet 3. Edit the ActionAdd procedure and add the following code to the Case “Group Projects” statement: SQL Server and Oracle Case “Group Projects” ‘Turn the loading flag on so no items are processed blnLoading = True ‘Delete any previous projects Call ActionDelete() ‘Turn the loading flag off blnLoading = False ‘Set the SQL string objData.SQL = “usp_InsertGroupProject” ‘Open the database connection objData.OpenConnection() ‘Initialize the Command object objData.InitializeCommand() For intIndex = 0 To _ objGroupProjectsDS.Tables( _ “GroupProjects”).Rows.Count - 1 213 Stored Procedures and Views for SQL Server and Oracle 12_58894x ch09.qxd 10/13/05 5:52 PM Page 213 SQL Server ‘Add the Parameters to the Parameters collection objData.AddParameter(“@GroupProjectID”, _ Data.SqlDbType.UniqueIdentifier, 16, _ Guid.NewGuid()) objData.AddParameter(“@GroupID”, _ Data.SqlDbType.UniqueIdentifier, 16, _ cboGroups.SelectedItem.Item(“GroupID”)) objData.AddParameter(“@ProjectID”, _ Data.SqlDbType.UniqueIdentifier, 16, _ objGroupProjectsDS.Tables( _ “GroupProjects”).Rows(intIndex).Item(“ProjectID”)) Oracle ‘Add the Parameters to the Parameters collection objData.AddParameter(“inGroupProjectID”, _ Data.OracleClient.OracleType.Char, 36, _ Guid.NewGuid.ToString.ToUpper) objData.AddParameter(“inGroupID”, _ Data.OracleClient.OracleType.Char, 36, _ cboGroups.SelectedItem.Item(“GroupID”)) objData.AddParameter(“inProjectID”, _ Data.OracleClient.OracleType.Char, 36, _ objGroupProjectsDS.Tables( _ “GroupProjects”).Rows(intIndex).Item(“ProjectID”)) SQL Server and Oracle ‘Execute the stored procedure objData.Command.ExecuteNonQuery() ‘Clear the Parameters collection for the next insert objData.Command.Parameters.Clear() Next ‘Close the database connection objData.CloseConnection() ‘Clear previous bindings lstGroupProjects.DataSource = Nothing lstGroupProjects.DisplayMember = String.Empty lstGroupProjects.ValueMember = String.Empty lstGroupProjects.Items.Clear() ‘Turn the loading flag on so no items are processed blnLoading = True cboGroups.SelectedIndex = -1 ‘Turn the loading flag off blnLoading = False 4. Edit the ActionUpdate procedure and add the following code to the Case “Group Projects” statement: Case “Group Projects” ‘Turn the loading flag on so no items are processed blnLoading = True Call ActionAdd() 214 Chapter 9 12_58894x ch09.qxd 10/13/05 5:52 PM Page 214 5. Edit the ActionDelete procedure and add the following code to the Case “Group Projects” statement: SQL Server and Oracle Case “Group Projects” ‘Set the SQL string objData.SQL = “usp_DeleteGroupProjects” ‘Initialize the Command object objData.InitializeCommand() SQL Server ‘Add the Parameters to the Parameters collection objData.AddParameter(“@GroupID”, _ Data.SqlDbType.UniqueIdentifier, _ 16, cboGroups.SelectedItem.Item(“GroupID”)) Oracle ‘Add the Parameters to the Parameters collection objData.AddParameter(“inGroupID”, _ Data.OracleClient.OracleType.Char, _ 36, cboGroups.SelectedItem.Item(“GroupID”)) SQL Server and Oracle ‘Open the database connection objData.OpenConnection() ‘Execute the stored procedure objData.Command.ExecuteNonQuery() ‘Close the database connection objData.CloseConnection() ‘Clear previous bindings If Not blnLoading Then lstGroupProjects.DataSource = Nothing lstGroupProjects.DisplayMember = String.Empty lstGroupProjects.ValueMember = String.Empty lstGroupProjects.Items.Clear() blnLoading = True cboGroups.SelectedIndex = -1 blnLoading = False End If 6. Modify the LoadProjects procedure as follows: SQL Server and Oracle Try ‘Clear previous bindings lstProjects.DataSource = Nothing lstProjects.DisplayMember = String.Empty lstProjects.ValueMember = String.Empty 215 Stored Procedures and Views for SQL Server and Oracle 12_58894x ch09.qxd 10/13/05 5:52 PM Page 215 SQL Server ‘Get all Projects in a DataSet objData.SQL = “usp_SelectProjects” objProjectsDS = New Data.DataSet Call objData.FillDataSet(objProjectsDS, “Projects”) Oracle ‘Get all Projects in a DataSet objData.SQL = “ProjectsPackage.usp_SelectProjects” objData.InitializeCommand() objData.AddParameter(“results_cursor”, _ Data.OracleClient.OracleType.Cursor, _ Data.ParameterDirection.Output) objProjectsDS = New Data.DataSet Call objData.FillDataSet(objProjectsDS, “Projects”) SQL Server and Oracle ‘Clear previous list lvwProjects.Items.Clear() ‘Process all rows For intIndex = 0 To objProjectsDS.Tables(“Projects”).Rows.Count - 1 ‘Create a new listview item objListViewItem = New ListViewItem ‘Add the data to the listview item objListViewItem.Text = objProjectsDS.Tables( _ “Projects”).Rows(intIndex).Item(“ProjectName”) objListViewItem.Tag = objProjectsDS.Tables( _ “Projects”).Rows(intIndex).Item(“ProjectID”) ‘Add the sub items to the listview item objListViewItem.SubItems.Add(objProjectsDS.Tables( _ “Projects”).Rows(intIndex).Item(“ProjectDescription”)) objListViewItem.SubItems.Add(objProjectsDS.Tables( _ “Projects”).Rows(intIndex).Item(“SequenceNumber”)) objListViewItem.SubItems.Add(Format(objProjectsDS.Tables( _ “Projects”).Rows(intIndex).Item(“LastUpdateDate”), “g”)) ‘Add the listview item to the listview control lvwProjects.Items.Add(objListViewItem) Next ‘Rebind ListBox control lstProjects.DataSource = objProjectsDS.Tables(“Projects”) lstProjects.DisplayMember = “ProjectName” lstProjects.ValueMember = “ProjectID” SQL Server and Oracle Catch ExceptionErr As Exception 7. Modify the LoadGroups procedure as follows: 216 Chapter 9 12_58894x ch09.qxd 10/13/05 5:52 PM Page 216 SQL Server and Oracle Private Sub LoadGroups() ‘Declare variables Dim objListViewItem As ListViewItem ‘Turn the loading flag on so no items are processed blnLoading = True ‘Initialize a new instance of the data access base class Using objData As New WDABase . . . ‘Turn off loading switch blnLoading = False End Sub 8. You need to add a procedure for the cboGroups ComboBox control to handle the SelectedIndexChanged event. Click the Method Name combo box at the top of the Code Editor and select cboGroups; and in the Class Name combo box, select the SelectedIndexChanged event. Enter the following code in the cboGroups_SelectedIndexChanged procedure: SQL Server and Oracle Private Sub cboGroups_SelectedIndexChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles cboGroups.SelectedIndexChanged ‘Don’t process if the ComboBox is being loaded If blnLoading Then Exit Sub End If Using objData As New WDABase Try ‘Clear previous bindings lstGroupProjects.DataSource = Nothing lstGroupProjects.DisplayMember = String.Empty lstGroupProjects.ValueMember = String.Empty SQL Server ‘Get the specific Group Projects selected in the ComboBox control objData.SQL = “SELECT ProjectID, ProjectName “ & _ “FROM vw_SelectGroupProjects “ & _ “WHERE GroupID = @GroupID “ & _ “ORDER BY SequenceNumber” objData.InitializeCommand() objData.AddParameter(“@GroupID”, Data.SqlDbType.UniqueIdentifier, _ 16, cboGroups.SelectedItem.Item(“GroupID”)) Oracle ‘Get the specific Group Projects selected in the ComboBox control objData.SQL = “SELECT ProjectID, ProjectName “ & _ “FROM vw_SelectGroupProjects “ & _ “WHERE GroupID = :inGroupID “ & _ 217 Stored Procedures and Views for SQL Server and Oracle 12_58894x ch09.qxd 10/13/05 5:52 PM Page 217 “ORDER BY SequenceNumber” objData.InitializeCommand() objData.AddParameter(“inGroupID”, _ Data.OracleClient.OracleType.Char, _ 36, cboGroups.SelectedItem.Item(“GroupID”)) SQL Server and Oracle objGroupProjectsDS = New Data.DataSet Call objData.FillDataSet(objGroupProjectsDS, “GroupProjects”) ‘Rebind ListBox control lstGroupProjects.DataSource = _ objGroupProjectsDS.Tables(“GroupProjects”) lstGroupProjects.DisplayMember = “ProjectName” lstGroupProjects.ValueMember = “ProjectID” Catch ExceptionErr As Exception MessageBox.Show(ExceptionErr.Message, strAppTitle) End Try End Using End Sub 9. To implement drag-and-drop functionality, you need to implement some event procedures for the lstProjects and lstGroupProjects ListBox controls. Click the Class Name combo box in the Code Editor and select lstProjects, and in the Method Name combo box, select the MouseDown event. Add the following code to the lstProjects_MouseDown procedure: Private Sub lstProjects_MouseDown(ByVal sender As Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) _ Handles lstProjects.MouseDown If e.Button = MouseButtons.Left Then lstProjects.DoDragDrop(objProjectsDS.Tables(“Projects”).Rows( _ lstProjects.SelectedIndex)(“ProjectID”).ToString, _ DragDropEffects.Copy) End If End Sub 10. Now click the Class Name combo box and select lstGroupProjects, and in the Method Name combo box, select the DragEnter event. Add the following code to the lstGroupProjects_DragEnter procedure: Private Sub lstGroupProjects_DragEnter(ByVal sender As Object, _ ByVal e As System.Windows.Forms.DragEventArgs) _ Handles lstGroupProjects.DragEnter ‘Exit if nothing has been selected in the cboGroups ComboBox If cboGroups.SelectedIndex = -1 Then Exit Sub End If ‘Now ensure that the drag content is the correct type for this control If (e.Data.GetDataPresent(DataFormats.Text)) Then ‘If the item does not already exist then allow the copy Dim objDataView As Data.DataView = New _ 218 Chapter 9 12_58894x ch09.qxd 10/13/05 5:52 PM Page 218 Data.DataView(objGroupProjectsDS.Tables(“GroupProjects”)) objDataView.Sort = “ProjectID” intIndex = objDataView.Find(e.Data.GetData(DataFormats.Text)) If intIndex = -1 Then e.Effect = DragDropEffects.Copy Else e.Effect = DragDropEffects.None End If Else e.Effect = DragDropEffects.None End If End Sub 11. Click the Class Name combo box and select lstGroupProjects again, and in the Method Name combo, select the DragDrop event. Enter the following code in the lstGroupProjects_DragDrop procedure: Private Sub lstGroupProjects_DragDrop(ByVal sender As Object, _ ByVal e As System.Windows.Forms.DragEventArgs) _ Handles lstGroupProjects.DragDrop Dim objDataRow As Data.DataRow Dim objDataView As Data.DataView = New _ Data.DataView(objProjectsDS.Tables(“Projects”)) objDataView.Sort = “ProjectID” intIndex = objDataView.Find(e.Data.GetData(DataFormats.Text)) objDataRow = objGroupProjectsDS.Tables(“GroupProjects”).NewRow objDataRow.Item(“ProjectID”) = New _ Guid(e.Data.GetData(DataFormats.Text).ToString) objDataRow.Item(“ProjectName”) = _ objDataView.Item(intIndex).Item(“ProjectName”) objGroupProjectsDS.Tables(“GroupProjects”).Rows.Add(objDataRow) objGroupProjectsDS.AcceptChanges() End Sub 12. To be able to delete unwanted projects in the lstGroupProjects ListBox, you need to add code to handle the Delete key. Once again click the Class Name combo box and select lstGroupProjects , and in the Method Name combo box, select the KeyUp event. Add the following code to the lstGroupProjects_KeyUp procedure: Private Sub lstGroupProjects_KeyUp(ByVal sender As Object, _ ByVal e As System.Windows.Forms.KeyEventArgs) _ Handles lstGroupProjects.KeyUp If e.KeyCode = Keys.Delete Then objGroupProjectsDS.Tables(“GroupProjects”).Rows.RemoveAt( _ lstGroupProjects.SelectedIndex) objGroupProjectsDS.AcceptChanges() End If End Sub 219 Stored Procedures and Views for SQL Server and Oracle 12_58894x ch09.qxd 10/13/05 5:52 PM Page 219 That’s all the code you need to implement the new view and two new stored procedures. Start your project so you can test your changes. When your form displays, click Group Projects in the Navigation pane or navigate to the Group Projects screen. Select a group in the Groups combo box and then drag a project from the Available Projects list and drop it in the Group Projects list. Repeat this process for a few projects as shown in Figure 9-3. This will test the drag-and-drop functionality. To test the delete functionality of the Group Projects ListBox control, click a project in the Group Projects list and press the Delete key. The selected project will be deleted from the list box. Figure 9-3 To test the add functionality, click the Add button on the toolbar or click the Action menu and choose Add. The group projects are added to the selected group, the Groups combo box is cleared, the Group Projects list is cleared, and the message Record Added is displayed in the status bar. This test has exercised your usp_InsertGroupProject stored procedure. To exercise your vw_SelectGroupProjects view and to verify that the projects were added to the group, select the group name in the Groups combo box and the Group Projects list will be populated with the groups just added. Select another group name in the Groups combo box and the Group Projects list will be empty. To test your usp_DeleteGroupProject stored procedure, click the group name in the Groups combo box that contains group projects. Now add some more projects to the list, delete some projects, or do both. Then click the Update button on the toolbar or click the Action menu and choose Update. Remember that the code for an update will call the ActionDelete procedure, which executes the usp_DeleteGroupProjects stored procedure and then calls the ActionAdd procedure, which executes the usp_InsertGroupProject stored procedure. 220 Chapter 9 12_58894x ch09.qxd 10/13/05 5:52 PM Page 220 Finally, if you want to test the delete functionality, click the group name in the Groups combo box that contains group projects. When the group projects are displayed, click the Delete button on the toolbar or click the Action menu and choose Delete. Before you move on, populate a couple of groups with group projects in preparation for future exercises. How It Works You add three variables at the form level for this exercise. The first variable, blnLoading, is used when loading group data and prevents the combo box event procedure from executing when data is being loaded into the combo box. You saw this variable used in the various procedures that you added for this exercise. The next two variables are defined as a DataSet to hold the project and group project data retrieved from the database. Private blnLoading As Boolean Private objProjectsDS As DataSet Private objGroupProjectsDS As DataSet The first procedure that you modify is ActionAdd. You modified the Case “Group Projects” state- ment, adding the necessary code to add group projects. The first thing that you do in this procedure is set the blnLoading flag to True. I talked a little about this earlier but want to cover it again. Because you are dealing with a one-to-many relationship between a group and many projects, it is more efficient to simply delete any previously existing group projects and to add them again than to try to determine which projects exist, which projects need to be deleted, and which projects need to be added. Because this procedure is called from the ActionUpdate procedure, you have included a call to the ActionDelete procedure before adding any new group projects. Therefore, the next thing that you do is delete any existing group projects by calling the ActionDelete procedure. Then you can turn the loading flag off as it is not needed anymore: SQL Server and Oracle Case “Group Projects” ‘Turn the loading flag on so no items are processed blnLoading = True ‘Delete any previous projects Call ActionDelete() ‘Turn the loading flag off blnLoading = False Next, you set the SQL property to your usp_InsertGroupProject stored procedure. Then you open the database connection by calling the OpenConnection method on your objData object and initialize the Command object by calling the InitializeCommand method: ‘Set the SQL string objData.SQL = “usp_InsertGroupProject” ‘Open the database connection objData.OpenConnection() 221 Stored Procedures and Views for SQL Server and Oracle 12_58894x ch09.qxd 10/13/05 5:52 PM Page 221 ‘Initialize the Command object objData.InitializeCommand() You set up a For Next loop to process all data in the objGroupProjectsDS DataSet. The objGroupProjectsDS DataSet will be populated in two ways. First, when you select a group, the DataSet will be populated with any existing projects in that group. Then, when you drag and drop a project in the Group Projects list, the project will be added to the DataSet. The For Next loop uses the Count property of the Rows property to determine how many iterations it needs to process: For intIndex = 0 To _ objGroupProjectsDS.Tables( _ “GroupProjects”).Rows.Count - 1 Inside the loop for SQL Server, you add the parameters required by the usp_InsertGroupProject stored procedure. Three parameters are needed: a new GroupProjectID, the GroupID of an existing group, and the ProjectID of the project being added to this group. Because all of these parameters are defined as a UNIQUEIDENTIFIER data type in the stored procedure, you specify this data type in the AddParameter method. The data for the @GroupProjectID is set using the NewGuid method of the Guid structure, whereas the data for the @GroupID is retrieved from the selected group in the cboGroups combo box and the @ProjectID parameters are retrieved from the DataSet. SQL Server ‘Add the Parameters to the Parameters collection objData.AddParameter(“@GroupProjectID”, _ Data.SqlDbType.UniqueIdentifier, 16, _ Guid.NewGuid()) objData.AddParameter(“@GroupID”, _ Data.SqlDbType.UniqueIdentifier, 16, _ cboGroups.SelectedItem.Item(“GroupID”)) objData.AddParameter(“@ProjectID”, _ Data.SqlDbType.UniqueIdentifier, 16, _ objGroupProjectsDS.Tables( _ “GroupProjects”).Rows(intIndex).Item(“ProjectID”)) The same parameters apply for the Oracle version of this stored procedure except that the parameters for Oracle are defined as a CHAR data type. Also, the parameter names are prefixed with the word in as opposed to an at ( @) sign for SQL Server. Oracle ‘Add the Parameters to the Parameters collection objData.AddParameter(“inGroupProjectID”, _ Data.OracleClient.OracleType.Char, 36, _ Guid.NewGuid.ToString.ToUpper) objData.AddParameter(“inGroupID”, _ Data.OracleClient.OracleType.Char, 36, _ cboGroups.SelectedItem.Item(“GroupID”)) objData.AddParameter(“inProjectID”, _ Data.OracleClient.OracleType.Char, 36, _ objGroupProjectsDS.Tables( _ “GroupProjects”).Rows(intIndex).Item(“ProjectID”)) 222 Chapter 9 12_58894x ch09.qxd 10/13/05 5:52 PM Page 222 [...]... drag-and-drop functionality using this method However, you have bought this book to learn how to write database applications using VB 2005 and I would be remiss if I didn’t teach you as much as possible about VB 2005, ADO.NET, and processing and accessing data in your databases I have chosen to use bound ListBox controls because this gives you the opportunity to learn even more about DataSet objects... Procedures and Views for SQL Server and Oracle To summarize, you should know how to: ❑ Create a stored procedure in your database using Visual Studio 2005 ❑ Return data from a stored procedure using either SQL Server or Oracle ❑ Execute a stored procedure in your VB 2005 programs ❑ Create and select data from views ❑ Use a DataView object to find data in a DataSet ❑ Use a DataRow object to add a new... ‘Encrypt the byte array Dim objCryptoStream As New CryptoStream(objOutputStream, _ 241 Chapter 10 objTripleDES.CreateEncryptor(bytKey, bytIV), _ CryptoStreamMode.Write) objCryptoStream.Write(bytInput, 0, bytInput.Length) objCryptoStream.FlushFinalBlock() ‘Return the byte array as a Base 64 string Encrypt = Convert.ToBase64String(objOutputStream.ToArray()) End Using Catch ExceptionErr As Exception Throw... data type into another The following code uses the ToBase64String method to convert an array of bytes into a complete string The input to this method is a byte array so you use the ToArray function to convert the individual bytes in the objOutputStream object to a byte array ‘Return the byte array as a Base 64 string Encrypt = Convert.ToBase64String(objOutputStream.ToArray()) End Using The encrypted... doesn’t create registry keys; it merely reads the values from the registry to discover which database it should connect to Try It Out Creating Registry Keys To create this application: 1 Start Visual Studio 2005 and start a new project by clicking the Create Project link on the Recent Projects tab of the Start page or by selecting File ➪ New ➪ Project 2 In the New Project dialog box, select a Windows... process the data returned from those stored procedures In your examination of views, you learned how a view is constructed in both SQL Server and Oracle and how you execute a view from your VB 2005 code Fortunately, both databases handle views in the same manner, and selecting data from a view in your code is handled in the same manner, by specifying a SELECT statement In the implementation of the drag-and-drop... Microsoft.Win32 14 Click the Class Name combo box and select btnCreate In the Method Name combo box select the Click event Add the following code to the btnCreate_Click procedure: Private Sub btnCreate_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles btnCreate.Click ‘Declare variables Dim objReg As RegistryKey ‘Key size must be 128 bits to 192 bits in increments of 64 bits Dim bytKey()... ‘Private variables and objects Private bytKey() As Byte Private bytIV() As Byte Private bytInput() As Byte Private objTripleDES As TripleDESCryptoServiceProvider Private objOutputStream As MemoryStream 244 Building Business Logic and Data Access Components The constructor for this class accepts the key and initialization vector as input and sets the variables for this class with the data being passed... research the available technologies and determine which technology is best suited for your business needs The MSDN Library that is installed with 236 Building Business Logic and Data Access Components Visual Studio 2005 has a wealth of information about architecture and design patterns for distributed applications You would be wise to spend some time reviewing this material before implementing a production... Convert.ToBase64String method You can see that the last method will return normal characters that do not need any special encoding when used in an XML document The Catch block handles an exception if thrown and then throws a new exception to the caller when an error occurs: Catch ExceptionErr As Exception Throw New System.Exception(ExceptionErr.Message, _ ExceptionErr.InnerException) End Try End Function 246 Building . Out Implementing Views and Stored Procedures in VB 2005 To implement this functionality: 1. Open your Time Tracker project in Visual Studio 2005 and view the code for the Admin form. 2. Add the. flag on so no items are processed blnLoading = True Call ActionAdd() 2 14 Chapter 9 12_58894x ch09.qxd 10/13/05 5:52 PM Page 2 14 5. Edit the ActionDelete procedure and add the following code to the. String.Empty lstGroupProjects.Items.Clear() blnLoading = True cboGroups.SelectedIndex = -1 blnLoading = False End If 2 24 Chapter 9 12_58894x ch09.qxd 10/13/05 5:52 PM Page 2 24 Given that you want to load a list of projects in the Available Projects

Ngày đăng: 12/08/2014, 10:21