Tài liệu Practical Database Programming With Visual C#.NET- P16 pptx

50 583 1
Tài liệu Practical Database Programming With Visual C#.NET- P16 pptx

Đ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

9.4 Build ASP.NET Web Service Project to Insert Data into SQL Server Database 773 To save time and space, we can copy and modify an existing Web Service project WebServiceSQLSelect we developed in the previous section as our new Web Service project WebServiceSQLInsert. 9.4.1 Modify Existing Web Service Project First, let ’ s create a new folder such as Chapter 9 in our root directory using Windows Explorer, and then copy the WebServiceSQLSelect project from the folder DBProjects\ Chapter 9 located at the accompanying ftp site (see Chapter 1 ), and paste it into our new created folder C:\Chapter 9 . Rename it to WebServiceSQLInsert and open this new project to perform the following modifi cations to this project: 1. Change the main Web Service page from WebServiceSQLSelect.asmx to WebServiceSQLInsert.asmx in the Solution Explorer window. 2. Change the name of our base class from SQLSelectBase , which is located in the folder App_Code, to SQLInsertBase in the Solution Explorer window. 3. Open Visual Studio.NET and our new project WebServiceSQLInsert, and then open our entry page WebServiceSQLInsert.asmx by double - clicking on it, and change the compiler directive from CodeBehind= " ~ /App_Code/WebServiceSQLSelect.cs " to CodeBehind= " ~ /App_Code/WebServiceSQLInsert.cs " Also change the class name from Class= " WebServiceSQLSelect " to Class= " WebServiceSQLInsert " 4. Remove the child class SQLSelectResult from this project since the data insertion has no data to be returned. 5. Change the name of our code - behind page from WebServiceSQLSelect.cs to WebServiceSQLInsert.cs. 6. Open the base class SQLInsertBase and perform the following modifi cations: a. Change the class name from SQLSelectBase to SQLInsertBase . b. Change two member data from SQLRequestOK to SQLInsertOK and from SQLRequest Error to SQLInsertError . c. Add the following seven member data into this class: i. public string FacultyID; ii. public string[] CourseID = new string[10]; iii. public string Course; iv. public string Schedule; v. public string Classroom; vi. public int Credit; vii. public int Enrollment; Go to the File|Save All menu item to save these modifi cations. c09.indd 773c09.indd 773 2/11/2010 3:01:30 PM2/11/2010 3:01:30 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 774 Chapter 9 ASP.NET Web Services 9.4.2 Web Service Project Development Procedure We try to develop four Web methods in this Web Service project; two of them are used to insert the desired course information into our sample database and two of them are used to retrieve the new inserted course information from the database to test the data insertion. The fourth Web method is used to retrieve the detailed course information based on the course_id . These methods are listed below: 1. Develop a Web method SetSQLInsertSP() to call a stored procedure to perform this new course insertion. 2. Develop a Web method GetSQLInsert() to retrieve the new inserted course information from the database using a joined table query. 3. Develop a Web method SQLInsertDataSet() to perform the data insertion by using multi- query and return a DataSet that contains the updated Course table. 4. Develop a Web method GetSQLInsertCourse() to retrieve the detailed course information based on the input course_id . The reason we use two different methods to perform this data insertion is to try to compare them. As you know, there is no faculty name column in the Course table, and each course is related to a faculty member identifi ed by the faculty_id column in the Course table. In order to insert a new course into the Course table, you must fi rst perform a query to the Faculty table to get the desired faculty_id based on the selected faculty name, and then you can perform another insertion query to insert a new course based on that faculty_id obtained from the fi rst query. The fi rst Web method combines those two queries into a stored procedure, and the third method uses a DataSet to return the whole Course table to make this data insertion more convenient to the user. The main code developments and modifi cations are performed in our code - behind page WebServiceSQLInsert.cs, that is, the most modifi cations will be performed on the codes in four Web methods listed above. 9.4.3 Develop and Modify Codes for Code -Behind Page Open our new project WebServiceSQLInsert if it has not been opened, and then open the code window of our code - behind page WebServiceSQLInsert.cs . Change the names of our main Web service class and constructor from WebServiceSQLSelect to WebServiceSQLInsert. Another modifi cation is to remove the user - defi ned method FillFacultyReader() since we do not need to return any data for this data insertion operation. The last modi- fi cation to this page is to modify the codes of the method ReportError(). Perform the following modifi cations to this method: 1. Change the data type of the passed argument from SQLSelectResult to SQLInsertBase. 2. Change the member data in the fi rst coding line from SQLRequestOK to SQLInsertOK. 3. Change the member data in the second coding line from SQLRequestError to SQLInsertError. Now let ’ s start our modifi cation to the fi rst Web method. c09.indd 774c09.indd 774 2/11/2010 3:01:30 PM2/11/2010 3:01:30 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 9.4 Build ASP.NET Web Service Project to Insert Data into SQL Server Database 775 9.4.3.1 Develop and Modify First Web Method Set SQLI nsert SP Perform the following modifi cations to the Web method GetSQLSelect(), as shown in Figure 9.43 , to get our new Web method SetSQLInsertSP. This Web method uses a stored procedure to perform data insertion. Recall that in Section 6.10.1.2 in Chapter 6 , we developed a stored procedure dbo.InsertFacultyCourse in the SQL Server database and used it to insert a new course into the Course table. We will use this stored procedure in this Web method to reduce our coding load. Refer to that section to get more detailed information in how to develop this stored procedure. Seven input parameters are used for this stored procedure: @FacultyName, @CourseID, @Course, @Schedule, @Classroom, publ { ic class WebServiceSQLInsert : System.Web.Services.WebService public WebServiceSQLInsert() { //Uncomment the following line if using designed components //InitializeComponent(); } [WebMethod] public SQLInsertBase SetSQLInsertSP(string FacultyName, string CourseID, string Course, string Schedule, string Classroom, int Credit, int Enroll) { string cmdString = "dbo.InsertFacultyCourse"; SqlConnection sqlConnection = new SqlConnection(); SQLInsertBase SetSQLResult = new SQLInsertBase(); SqlCommand sqlCommand = new SqlCommand(); int intInsert = 0; SetSQLResult.SQLInsertOK = true; sqlConnection = SQLConn(); if (sqlConnection == null) { SetSQLResult.SQLInsertError = "Database connection is failed"; ReportError(SetSQLResult); return null; } sqlCommand.Connection = sqlConnection; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.CommandText = cmdString; sqlCommand.Parameters.Add("@FacultyName", SqlDbType.Text).Value = FacultyName; sqlCommand.Parameters.Add("@CourseID", SqlDbType.Char).Value = CourseID; sqlCommand.Parameters.Add("@Course", SqlDbType.Text).Value = Course; sqlCommand.Parameters.Add("@Schedule", SqlDbType.Char).Value = Schedule; sqlCommand.Parameters.Add("@Classroom", SqlDbType.Text).Value = Classroom; sqlCommand.Parameters.Add("@Credit", SqlDbType.Int).Value = Credit; sqlCommand.Parameters.Add("@Enroll", SqlDbType.Int).Value = Enroll; intInsert = sqlCommand.ExecuteNonQuery(); sqlConnection.Close(); sqlCommand.Dispose(); if (intInsert == 0) { SetSQLResult.SQLInsertError = "Data insertion is failed"; ReportError(SetSQLResult); } Return SetSQLResult; } A B C D E F G H I J K L M WebServiceSQLInsert SetSQLInsertSP() Figure 9.43 Modifi cation to the fi rst Web method. c09.indd 775c09.indd 775 2/11/2010 3:01:30 PM2/11/2010 3:01:30 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 776 Chapter 9 ASP.NET Web Services @Credit, and @Enroll. All of these parameters will be input by the user as this Web Service project runs. Let ’ s take a closer look at these codes to see how they work. A. The name of our Web Service class and the constructor of this class is changed to WebServiceSQLInsert to distinguish it from the original items. B. The Web method ’ s name is also changed to SetSQLInsertSP, which means that this Web method will call a stored procedure to perform the data insertion action. Seven input parameters are passed into this method as the new data for a new inserted course record. The returned object should be an instance of our modifi ed base class SQLInsertBase. C. The content of the query string must be equal to the name of the stored procedure we developed in Section 6.10.1.2 in Chapter 6 . Otherwise a possible running error may be encountered as this Web Service is executed since the stored procedure is identifi ed by its name when it is called. D. A returned object SetSQLResult is created based on our modifi ed base class SQLInsert Base; that is, no data is supposed to be returned for this data insertion action. However, in order to enable our client project to get a clear feedback from executing this Web Service, we prefer to return an object that contains the information indicating whether this Web Service is executed successfully or not. E. A local integer variable intInsert is declared, and this variable is used to stop the returned value from calling the ExecuteNonQuery() method of the Command class, and that method will run the stored procedure to perform the data insertion action. This returned value is equal to the number of rows that have been successfully inserted into our database. F. Initially we set the member data SQLInsertOK that is located in our modifi ed base class SQLInsertBase to true to indicate our Web service running status is good. G. If the connection to our sample database has failed, which is indicated by a returned Connection object containing a null , an error message is assigned to another member data SQLInsertError that is also located in our modifi ed base class SQLInsertBase to log on this error, and the user - defi ned method ReportError() is called to report this error. H. The property value CommandType.StoredProcedure must be assigned to the Command Type property of the Command object to tell the project that a stored procedure should be called as this Command object is executed. I. Seven input parameters are assigned to the Parameters collection property of the Command object, and the last six parameters work as the new course data to be inserted into the Course table. One important point to be note is that these input parameters ’ names must be identical with those names defi ned in the stored procedure dbo.InsertFacultyCourse developed in Section 6.10.1.2 . Refer to that section to get a detailed description of those parameters ’ names defi ned in that stored procedure. J. The ExecuteNonQuery() method is called to run the stored procedure to perform this data insertion. This method returns an integer that is stored in our local variable intInsert . K. A cleaning job is performed to release data objects used in this method. L. The returned value from calling of the ExecuteNonQuery() method, which is stored in the variable intInsert , is equal to the number of rows that have been successfully inserted into the Course table. If this value is zero, which means that no row has been inserted into our database and this data insertion has failed, a warning message is assigned to the member data SQLInsertError that will be reported by using our user - defi ned ReportError() method later. c09.indd 776c09.indd 776 2/11/2010 3:01:30 PM2/11/2010 3:01:30 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 9.4 Build ASP.NET Web Service Project to Insert Data into SQL Server Database 777 M. Finally the instance of our base class, SetSQLResult, is returned to the calling procedure to indicate the running result of this Web method. At this point we have fi nished the coding development and modifi cation to this Web method. Now we can run this Web Service project to test inserting new course informa- tion to our sample database via this Web Service. However, before we can build and run this project, we have to comment out all other Web methods we created in the project WebServiceSQLSelect we developed in the previous sections since we have modifi ed some user - defi ned classes such as SQLSelectBase that are still used in those Web methods in this project. The Web methods to be commented out are: • GetSQLSelectSP() • GetSQLSelectDataSet() After comment out these Web methods, now we can build and run this project to test the data insertion action. Click on the Start Debugging button to run the project. The built - in Web interface is shown in Figure 9.44 . Click on the Web method SetSQLInsertSP to select it to open another built - in Web interface to display input parameters window, which is shown in Figure 9.45 . Enter the following parameters to this Web method: • FacultyName Ying Bai • CourseID CSE - 556 • Course Advanced Fuzzy Systems • Schedule M - W - F: 1:00 - 1:55 PM • Classroom TC - 315 • Credit 3 • Enroll 28 Figure 9.44 Running built - in Web interface. c09.indd 777c09.indd 777 2/11/2010 3:01:30 PM2/11/2010 3:01:30 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 778 Chapter 9 ASP.NET Web Services Click on the Invoke button to run this Web method to call the stored procedure to perform this data insertion. The running result is displayed in the built - in Web interface, which is shown in Figure 9.46 . Based on the returned member data SQLInsertOK = true , it indicates that our data insertion is successful. To confi rm this, fi rst click on the Close button located at the upper - right corner of this Web interface to terminate our Web Service, and then you can open our sample database CSE_DEPT using the SQL Server Management Studio to check this new inserted course. It can be found from this running result that the values for both attributes < Credit > and < Enrollment > are zero. This makes sense since we did not query any data from our Course table and assign any returned course information to them, and the default value is zero for any created integer variable. Ten string variables belong to the string array CourseID[] that is used to store course_id . A default value true is assigned to each of them since we did not need to return them in this application. Next let ’ s develop the second Web method GetSQLInsert() to retrieve all courses taught by the selected faculty member, that is, all course_id , to confi rm our data inser- tion action. Figure 9.45 Input parameter interface. c09.indd 778c09.indd 778 2/11/2010 3:01:32 PM2/11/2010 3:01:32 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 9.4 Build ASP.NET Web Service Project to Insert Data into SQL Server Database 779 9.4.3.2 Develop Second Web Method Get SQLI nsert The function of this Web method is to retrieve all course_id , which includes the original and the new inserted course_id , from the Course table based on the input faculty name. This Web method will be called or consumed by a client project later to get back and display all course_id in a listbox control in the client project. Recall that in Section 5.19.2.5 in Chapter 5 , we developed a joined - table query to perform the data query from the Course table to get all course_id based on the faculty name. The reason for that is because there is no faculty name column available in the Course table, and each course or course_id is related to a faculty_id in the Course table. In order to get the faculty_id that is associated with the selected faculty name, one must fi rst go to the Faculty table to perform a query to obtain it. In this situation, a join query is a desired method to complete this function. We will use the same strategy to perform this data query in this section. Open the code window of our code - behind page WebServiceSQLInsert.cs and enter the codes shown in Figure 9.47 into this page to create our new Web method GetSQLInsert(). Let ’ s take a closer look at the codes in this Web method to see how they work. A. The returning data type for this Web method is our modifi ed base class SQLInsertBase, and all course information is stored in the different member data in this class. The input parameter to this Web method is a selected faculty name. B. The joined - table query string is defi ned here, and an ANSI92 standard, which is an up - to - date standard, is used for the syntax of this query string. The ANSI 89, which is an out - of - date syntax standard, can still be used for this query string defi nition. However, the Figure 9.46 Running result of the fi rst Web method. c09.indd 779c09.indd 779 2/11/2010 3:01:34 PM2/11/2010 3:01:34 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 780 Chapter 9 ASP.NET Web Services up - to - date standard is recommended. Refer to Section 5.19.2.5 to get more detailed dis- cussions for this topic. The nominal name of the input dynamic parameter to this query is @name . C. All used data objects are declared here, such as the Connection, Command, and DataReader objects. A returned object GetSQLResult that is instantiated from our base class SQLInsertBase is also created, and it will be returned to the calling procedure to send back the queried course information. D. Initially we set the running status of our Web method to OK. E. The user - defi ned method SQLConn() is called to connect to our sample database. A warning message is assigned to the member data in our returned object and the user - defi ned method ReportError() is executed to report this error if an error occurs for this connection. F. The Command object is initialized with appropriate properties such as the Connection object, Command type, and Command text. G. The real input parameter FacultyName is assigned to the dynamic parameter @name using the Add() method. [WebMethod] public SQLInsertBase GetSQLInsert(string FacultyName) { string cmdString = "SELECT Course.course_id FROM Course JOIN Faculty " + "ON (Course.faculty_id LIKE Faculty.faculty_id) AND (Faculty.faculty_name LIKE @name)"; SqlConnection sqlConnection = new SqlConnection(); SQLInsertBase GetSQLResult = new SQLInsertBase(); SqlCommand sqlCommand = new SqlCommand(); SqlDataReader sqlReader; GetSQLResult.SQLInsertOK = true; sqlConnection = SQLConn(); if (sqlConnection == null) { GetSQLResult.SQLInsertError = "Database connection is failed"; ReportError(GetSQLResult); return null; } sqlCommand.Connection = sqlConnection; sqlCommand.CommandType = CommandType.Text; sqlCommand.CommandText = cmdString; sqlCommand.Parameters.Add("@name", SqlDbType.Text).Value = FacultyName; sqlReader = sqlCommand.ExecuteReader(); if (sqlReader.HasRows == true) FillCourseReader(ref GetSQLResult, sqlReader); else { GetSQLResult.SQLInsertError = "No matched course found"; ReportError(GetSQLResult); } sqlReader.Close(); sqlConnection.Close(); sqlCommand.Dispose(); return GetSQLResult; } A B C D E F G H I J K L WebServiceSQLInsert GetSQLInsert() Figure 9.47 Codes for our second Web GetSQLInsert method. c09.indd 780c09.indd 780 2/11/2010 3:01:34 PM2/11/2010 3:01:34 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 9.4 Build ASP.NET Web Service Project to Insert Data into SQL Server Database 781 H. The ExecuteReader() method is called to trigger the DataReader and perform the data query. This method is a read - only method and the returned reading result is assigned to the DataReader object sqlReader . I. By checking the HasRows property of the DataReader, we can determine whether this reading is successful or not. If this reading is successful ( HasRows = true ), the user - defi ned FillCourseReader() method, whose detailed codes will be discussed in Figure 9.48 , is called to assign the returned course_id to each associated member data in our returned object GetSQLResult. J. Otherwise if this reading has failed, a warning message is assigned to our member data SQLInsertError in our returned object and this error is reported by calling the user - defi ned ReportError() method. K. A cleaning job is performed to release all data objects used in this Web method. L. The returned object that contains all queried course_id is returned to the calling procedure. The detailed codes for our user - defi ned FillCourseReader() method are shown in Figure 9.48 . The function of this piece of code is straightforward and without tricks. A while loop is used to continuously pick up each course_id whose column index is zero from the Course table, convert it to a string, and assign it to the CourseID string array defi ned in our base class SQLInsertBase. Now let ’ s test this Web method by running this project. Build this project and click on the Start Debugging button to run our project. The built - in Web interface is displayed in Figure 9.49 . Click on the fi rst Web method GetSQLInsert and enter the faculty name Ying Bai into the FacultyName box in the next built - in Web interface, which is shown in Figure 9.50 . Click on the Invoke button to execute this Web method, and the running result of this method is shown in Figure 9.51 . It can be seen that all courses (that is, all course_ id ), including our new inserted course CSE - 556, taught by the selected faculty Ying Bai are listed in an XML format. Our second Web method is successful, too. Click on the Close button located at the upper - right corner of this page to terminate our Web Service project. Also go to File|Save All to save all methods we have developed. protected void FillCourseReader(ref SQLInsertBase sResult, SqlDataReader sReader) { int pos = 0; while (sReader.Read()) { sResult.CourseID[pos] = Convert.ToString(sReader.GetSqlString(0)); //the 1st column is course_id pos++; } } WebServiceSQLInsert FillCourseReader() Figure 9.48 Codes for the FillCourseReader method. c09.indd 781c09.indd 781 2/11/2010 3:01:34 PM2/11/2010 3:01:34 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 782 Chapter 9 ASP.NET Web Services 9.4.3.3 Develop and Modify Third Web Method SQLInsertDataSet The function of this Web method is similar to the fi rst one: to insert a new course into the Course table based on the selected faculty member. The difference is that this Web method uses multiquery to insert a new course record into the Course table and uses a DataSet as the returned object. The returned DataSet contains the updated Course table Figure 9.49 Running status of our Web Service project. Figure 9.50 Running status of our Web Service project. c09.indd 782c09.indd 782 2/11/2010 3:01:35 PM2/11/2010 3:01:35 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... to Insert Data into SQL Server Database Figure 9.51 783 Running result of our Web method GetSQLInsert that includes the new inserted data The advantages of using a DataSet as the returned object are: 1 Unlike Web methods 1 and 2, which are a pair of methods with the first used to insert data into the database and the second used to retrieve the new inserted data from the database to confirm the data insertion,... box A point to note is that you can only insert this new course record into the database once, which means that after this new course has been inserted into the database, you cannot continue to click on the Invoke button to perform another insertion with the same course information since the data to be inserted into the database must be unique Click on the Close button located at the upper-right corner... identical with those we developed in the last Windows-based Web Service client project WinClientSQLInsert One can copy and paste them into our new project with a few modifications e Modify the codes in the SelectedIndexChanged event method f Modify the codes in the Back button’s Click method Now let’s start with the first step listed above 9.4.5.1 Create a New Website Project and Add Existing Web Page Open Visual. .. 9.56 One row is found and returned from the Course table in our sample database To view all returned columns, move the horizontal bar at the bottom of this dialog box to the right Our stored procedure works fine Right-click on our database folder CSE_DEPT.mdf and select the item Close Connection from the pop-up menu to close this database connection Figure 9.55 Codes for the stored procedure WebSelectCourseSP... WinClientSQLInsert to consume our Web Service project WebServiceSQLInsert, have been moved to the accompanying ftp site with a file named WinClientSQLInsert.pdf that can be found from the folder DBProjects\Chapter 9\Doc that is located at the site ftp:// ftp.wiley.com/public/sci_tech_med /practical_ database For your convenience, a completed Windows-based client project, WinClientSQLInsert, has also been developed... this data insertion query to insert a new course record into the Course table in our sample database This method will return an integer to indicate the number of rows that have been successfully inserted into the database N If this returned integer is zero, which means that no row has been inserted into the database and this insertion has failed, a warning message is assigned to the member data SQLInsertError,... course record that is stored in six textboxes in the Web page into the database as this Insert button is clicked This coding is basically identical with that in the same method of the Windows-based client project we developed in the last section Therefore we can copy those codes, from that method and paste them into our current method with a few modifications Open our Windows-based client project WinClientSQLInsert... DELETE DATA FOR SQL SERVER DATABASE In this section we discuss how to update and delete a record in the Course table in our sample database via the Web Services Two major Web methods are developed in this Web Service project: SQLUpdateSP() and SQLDeleteSP() Both methods call the associated stored procedure to perform the data updating and deleting operations in our sample database CSE_DEPT.mdf 806... third one is used to retrieve the new inserted data from the database to validate the data insertion For the data insertion, first we need to perform a query to the Faculty table to get the matched faculty_id based on the input faculty name since there is no faculty name 9.4 Build ASP.NET Web Service Project to Insert Data into SQL Server Database 785 column available in the Course table and each course... exactly identical with the name of the stored procedure we developed, otherwise a running error may be encountered since the stored procedure is identified by its name when the project runs C Some data objects such as the Connection and the DataReader are created here Also a returned instance of our base class is also created D The user-defined SQLConn() method is called to perform the database connection . a pair of methods with the fi rst used to insert data into the database and the second used to retrieve the new inserted data from the database to confi rm. course information into our sample database and two of them are used to retrieve the new inserted course information from the database to test the data insertion.

Ngày đăng: 14/12/2013, 15:15

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan