Practical Database Programming With Visual C#.NET- P15

50 544 0
Practical Database Programming With Visual C#.NET- P15

Đ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.2 Procedures to Build a Web Service 723 messages containing either document - oriented or procedure - oriented information. The operations and messages are described abstractly and then bound to a concrete network protocol and message format to defi ne an endpoint. UDDI is an XML - based directory for businesses that list themselves on the Internet. The goal of this directory is to enable companies to fi nd one another on the Web and make their systems interoperable for e - commerce. UDDI is often considered like a tele- phone book ’ s yellow and white pages. By using those pages, it allows businesses to list themselves by name, products, locations, or the Web services they offer. Thus, based on these components and their roles, we can conclude: • XML is used to tag data to be transferred between applications. • SOAP is used to wrap and pack the data tagged in the XML format into the messages represented in the SOAP protocol. • WSDL is used to map a concrete network protocol and message format to an abstract end- point, and describe the Web Services available in an WSDL document format. • UDDI is used to list all Web Services that are available to users and businesses. Figure 9.1 shows a diagram to illustrate these components and their roles in an ASP. NET Web Service process. By now we have obtained the fundamental knowledge about the ASP.NET Web Services and their components. Next let ’ s see how to build a Web Service project. 9.2 PROCEDURES TO BUILD A WEB SERVICE Different methods and languages can be used to develop different Web Services such as the C# Web Services, Java Web Services, and Perl Web Services. In this section we only concentrate on developing the ASP.NET Web Services using the Visual C#.NET 2008. Before we can start to build a real Web Service project, let ’ s fi rst take a closer look at the structure of a Web Service project. WSDL & UDDI Client Web S s erver Database Server Web Message in P Format ASP.NET Web Services SOA Services Request in XML tags Prepare Information Database Figure 9.1 Typical process of a Web Service. c09.indd 723c09.indd 723 2/11/2010 3:01:04 PM2/11/2010 3:01:04 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 724 Chapter 9 ASP.NET Web Services 9.2.1 Structure of a Typical Web Service Project A typical Web Service project contains the following components: 1. As a new Web Service project is created, two page fi les and two folders are created under this new project. The folder App_Code contains the code - behind page that has all real codes for a simple default Web Service and the Web Service to be created. The folder App_Data is used to store all project data. 2. The code - behind page Service.cs contains the real Visual C#.NET codes for a simple Web Service. Visual Web Developer includes three default namespace declarations to help users to develop Web Services on the top of this page, which are: using System.Web; using System.Web.Services; using System.Web.Services.Protocols; By default, a new code - behind fi le contains a class named Service that is defi ned with the WebService and WebServiceBinding attributes. The class defi ned a default Web method named HelloWorld that is a placeholder, and you can replace it with your own method or methods later when you develop your own Web Service project. 3. The main Web Service page fi le Service.asmx is used to display information about the Web Service ’ s methods and provide access to the Web Service ’ s WSDL information. The exten- sion .asmx means that this is an Active Service Method fi le, and the letter x is just a rotation of the attached symbol + after the keyword ASP since the ASP.NET was called ASP+ in the early days. If you open the ASMX fi le on a disk, you will see that it actually contains only one command line: < %@ WebService Language= " C# " CodeBehind= " ~ /App_Code/Service. cs " Class= " Service " % > It indicates the programming language in which the Web Service ’ s code - behind fi le is written, the code - behind fi le ’ s location, and the class that defi nes the Web Service. When you request the Active Server Method File (ASMX) page through the Internet Information Services (IIS), ASP.NET uses this information to generate the content displayed in the Web browser. 4. The confi guration fi le web.confi g , which is an XML - based fi le, is used to set up a confi gura- tion for the new created Web Service project, such as the namespaces for all kinds of Web components, Connection string, and default authentication mode. Each Web Service project has its own confi guration fi le. Of all the fi les and folders discussed above, the code - behind page is the most impor- tant fi le since all Visual C#.NET codes related to building a Web Service are located in this page, and our major coding development will be concentrated on this page, too. 9.2.2 Real Considerations When Building a Web Service Project Based on the structure of a typical Web Service project, some issues related to building an actual Web Service project are emphasized here, and these issues are very important and should be followed carefully to successfully create a Web Service project in the Visual Studio.NET environment. As a request is made and sent from a Windows or Web form client over the Internet to the server, the request is packed into a SOAP message and sent to the IIS on the client c09.indd 724c09.indd 724 2/11/2010 3:01:04 PM2/11/2010 3:01:04 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 9.2 Procedures to Build a Web Service 725 computer. Then the IIS will pass the request to the ASP.NET to get it processed in terms of the extension .asmx of the main service page. ASP.NET checks the page to make sure that the code - behind page contains the necessary codes to power the Web Service, that is, to trigger the associated Web methods to search, fi nd, and retrieve the information required by the client, pack it to the SOAP message, and return it to the client. During this process, the following detailed procedures must be performed: 1. When ASP.NET checks the received request represented in a SOAP message, the ASP. NET will make sure that the names and identifi ers used in the SOAP message are unique. In other words, those names and identifi ers cannot be confl icted with any name and identi- fi er used by any other message. To make names and identifi ers unique, we need to use our specifi c namespace to place and hold our SOAP message. 2. Generally, a request contains a set of information, not a single piece of information. To request those pieces of information, we need to create a Web Service proxy class to consume Web Services. In other words, we do not want to develop separate Web methods to query each piece of information, which would make our project ’ s size terribly large if we needed a lot of information. A good solution is to instantiate an object based on that class and integrate these pieces of information into that object. All information can be embedded into that object and can be returned if that object returns. Another choice is to design a Web method to make it return a DataSet, which is a convenient way to return all data. 3. As a professional application, we need to handle the exceptions to make our Web Service as perfect as possible. In that case, we need to create a base class to hold some error - checking codes to protect our real class, which will be instantiated to an object that contains all information we need. So this real class should be a child class inherited from the base class. 4. Since the Web Services do not provide any GUI, we need to develop some GUIs in either Windows - based or Web - based applications to interface to the Web Services to display returned information on GUIs. Keep these real issues in mind and now let ’ s begin to build a real Web Service project using an ASP.NET Web Service template. 9.2.3 Procedures to Build an ASP . NET Web Service As we mentioned in the last section, a Web Service is basically composed of a set of Web methods that can be called by the computer programs by the client. To build these methods, generally one needs to perform the following steps: 1. Create a new ASP.NET Web Service project. 2. Create a base class to handle the error checking to protect our real class. 3. Create our real Web Service class to hold all Web methods and codes to response to requests. 4. Add all Web methods into our Web Service class. 5. Develop the detail codes for those Web methods to perform the Web Services. 6. Build a Windows - based and Web - based project to consume the Web Service to pick up and display the required information on the GUI. 7. Store our ASP.NET Web Service project fi les in a safe location. c09.indd 725c09.indd 725 2/11/2010 3:01:04 PM2/11/2010 3:01:04 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 726 Chapter 9 ASP.NET Web Services In this chapter, we try to develop the following projects to illustrate the building and implementation process of a Web Services project: • Build a professional ASP.NET Web Service project to access the SQL Server database to obtain required information. • Build client applications to provide GUIs to consume a Web Service. • Build a professional ASP.NET Web Service project to insert new information into the SQL Server database. • Build a professional ASP.NET Web Service project to update and delete information against the SQL Server database. • Build a professional ASP.NET Web Service project to access the Oracle database to obtain required information. • Build a professional ASP.NET Web Service project to insert new information into the Oracle database. • Build a professional ASP.NET Web Service project to update and delete information against the Oracle database. Based on these procedures, we can start to build our fi rst Web Service project. 9.3 BUILD ASP.NET WEB SERVICE PROJECTS TO ACCESS SQL SERVER DATABASE To create a new ASP.NET Web Service project, open the Visual Studio.NET 2008, and then go to the File|New Web Site item. On the opened New Web Site dialog box, select the ASP.NET Web Service item from the Templates list and enter our Web Service project name WebServiceSQLSelect into the box that is next to the Location box, which is shown in Figure 9.2 . Also select the Visual C# from the Language box since we need to develop a Visual C# Web Service project in this chapter. Note that Visual Studio.NET 2008 introduced a Web project model that can use either IIS or the Local File System to develop Web applications. This model is good only when developing ASP.NET Web Services and Web pages that are running locally on a pseudo - Web server. This is our situation since we will run our Web Service in our local machine and use it as a development server, so the File System is used for our server location, which is shown in Figure 9.2 . Click on the OK button to create this new project in our default folder C:\Chapter 9. 9.3.1 Files and Items Created in the New Web Service Project After this new Web Service project is created, four items are produced in our new project in the Solution Explorer window. As we discussed in the last section, the main service page fi le Service.asmx , which is used to display information about the Web Service ’ s methods and provide access to the Web Service ’ s WSDL information, and the confi gura- tion fi le web.confi g , which is used to set up a confi guration for our new Web Service project, such as the namespaces for all kinds of Web components, connection strings for c09.indd 726c09.indd 726 2/11/2010 3:01:04 PM2/11/2010 3:01:04 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 9.3 Build ASP.NET Web Service Projects to Access SQL Server Database 727 data components, and Web Services and Windows authentication mode, are automati- cally created and added into our new project. More important, the page fi le Service.asmx is designed to automatically create extensible WSDL, dispatch Web methods, serialize and deserialize parameters, and provide hooks for message interception within our appli- cations. However, our default fi le Service.asmx only contains a compile directive as this new Web Service project is created and opened from the File System. Two folders, named App_Code , which is used to store our code - behind page Service. cs , and App_Data , which is used to save the project data, are also created. The code - behind page Service.cs is the place we need to create and develop the codes for our Web Services. This page contains a default class named Service that is defi ned with the WebService and WebServiceBinding attributes. The class defi ned as a default Web method named HelloWorld is a placeholder, and we can replace it with our own method or methods later based on the requirement of our Web Service project. Now double - click on this code - behind page Service.cs , which is shown in Figure 9.3 , and let ’ s take a closer look at the code in this page. A. The Web Services – related namespaces that contain the Web Service components are added into this page to allow us to access and use those service - related components to build our Web Service project. A detailed description about those namespaces and their functions is shown in Table 9.1 . B. Some WebService attributes are defi ned in this part. Generally, WebService attributes are used to identify additional descriptive information about deployed Web Services. The namespace attribute is one of examples. As we discussed in the last section, we need to use our own namespace to store and hold names and identifi ers used in our SOAP messages to distinguish them from any other SOAP messages used by other Web Services. Here, in this new project, Microsoft provided a default namespace " http://tempuri.org/ " , which is a temporary system - defi ned namespace to identify all Web Services code generated Figure 9.2 Create a new Web Service project. c09.indd 727c09.indd 727 2/11/2010 3:01:04 PM2/11/2010 3:01:04 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 728 Chapter 9 ASP.NET Web Services by the .NET framework, to store this default Web method. We need to use our own namespace to store our Web methods later when we deploy our Web Services in a real application. C. This Web Service Binding attribute indicates that the current Web Service complies with the Web Services Interoperability Organization (WS - I.org) Basic Provide 1.1. Here, basi- cally, a binding is equivalent to an interface in which it defi nes a set of concrete operations. D. This commented attribute indicates that if this Web Service is called from any script lan- guage, such as ASP.NET AJAX, the associated namespace ScriptService should be used, and this coding line should be uncommented. E. Our Web Service class Service is a child class derived from the parent class WebService located in the namespace System.Web.Services. F. The constructor of our Service class contains an InitializeComponent() method used to initialize all user - defi ned components used in this Web Service project. Generally, we do not need to create any specifi c components for most of our Web Service projects, therefore we keep the comment for this method. using System; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class Service : System.Web.Services.WebService { public Service () { //Uncomment the following line if using designed components //InitializeComponent(); [WebMethod] public string HelloWorld() { return "Hello World"; } } A B C D E F G Service Service() } Figure 9.3 Default coding for the code - behind page Service.cs. Table 9.1 Web Service Namespaces Namespace Functionality System.Web Enable browser and server communication using the .Net Framework System.Web.Services Enable creations of XML Web services using ASP.NET System.Web.Services.Protocol Define the protocol used to transmit data across the wire during the communication between the Web Service clients and servers c09.indd 728c09.indd 728 2/11/2010 3:01:06 PM2/11/2010 3:01:06 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 9.3 Build ASP.NET Web Service Projects to Access SQL Server Database 729 G. The default Web method HelloWorld is defi ned as a global function and this function returns a string “ Hello World ” when it is returned to the client. Next let ’ s double - click on the main service page fi le Service.asmx, which is the entry point of our project to open it. This one line code contains only a compile directive shown below since this project is created and opened using a File System: < %@ WebService Language= " C# " CodeBehind= " ~ /App_Code/Service. cs " Class= " Service " % > As we mentioned in the last section, this code indicates the programming language in which the Web Service ’ s code - behind fi le is written, the code - behind fi le ’ s name and location, and the class that defi nes the Web Service. In a real application, both the code - behind fi le name and the class name should be renamed to match our fi le and class names used in our project, respectively. We will do those renames later in the following sections. However, fi rst let ’ s run the default HelloWorld Web Service project to get a feeling about what it looks like and how it works. 9.3.2 Feeling of Hello World Web Service Project as It Runs Click on the Start Debugging button to run the default HelloWorld project. After the project is running, a message box is displayed with a warning message displayed, which is shown in Figure 9.4 . Generally, a Web Service project should not be debugged when it is deployed, and this is defi ned in the web.confi g fi le with a control of disabling the debugging. However, the debugging can be enabled during the development process by modifying the web. confi g fi le. To do that, keep the default radio button selected in this warning message box and click on OK to continue to run our project. Our Service.asmx page should be the starting page and the following IE page is displayed as shown in Figure 9.5 . This page displays the Web Service class named Service and all Web methods or operations developed in this project. By default, only one method HelloWorld is created and used in this project. Figure 9.4 Debugging Not Enabled message box . c09.indd 729c09.indd 729 2/11/2010 3:01:07 PM2/11/2010 3:01:07 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 730 Chapter 9 ASP.NET Web Services Below the method, the default namespace in which the current method or operation is located is shown, and a recommendation that suggests that we create our own namespace to store our Web Service project is displayed. Following this recommendation, some example namespaces used in C#, Visual Basic, and C++ are listed. Now let ’ s access our Web Service by clicking on the HelloWorld method. The test method page appears, which is shown in Figure 9.6 . The Invoke button is used to test our HelloWorld method using the HTTP Protocol. Below the Invoke button, some message examples created by using the different proto- cols are displayed. These include the requesting message and responding message created in SOAP 1.1, SOAP 1.2, and HTTP Post. The placeholder located at the default namespace "http://tempuri.org/" should be replaced by the actual namespace when this project is modifi ed to a real application. Now click on the Invoke button to run and test the default method HelloWorld . As the Invoke button is clicked on, a URL that contains the default namespace and the default HelloWorld method ’ s name is activated, and a new browser window, shown in Figure 9.7 , is displayed. When the default method HelloWorld is executed, the main service page Service.asmx sends a request to the IIS. Furthermore, the IIS sends it to the ASP.NET runtime to process this request based on that URL. The ASP.NET runtime will execute the HelloWorld method and pack the return data as a SOAP message, and send it back to the client. The returned message contains only a string object, that is, a string of “ Hello World ” for this default method. Figure 9.5 Running status of the default Web service project. c09.indd 730c09.indd 730 2/11/2010 3:01:07 PM2/11/2010 3:01:07 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 9.3 Build ASP.NET Web Service Projects to Access SQL Server Database 731 In this returned result, the version and the encoding of the used XML code is indi- cated fi rst. The xmlns attribute is used to indicate the namespace used by this string object that contains only a string of “ Hello World ” . As we discussed in the previous section, ASP.NET Web Service did not provide any GUI, so the running result of this default project is represented using the XML codes in some Web interfaces we have seen. This is because those Web interfaces are only pro- vided and used for the testing purpose for the default Web Service. In a real application, no such Web interface will be provided and displayed. Figure 9.6 Test method page. Figure 9.7 Running status of the default method. c09.indd 731c09.indd 731 2/11/2010 3:01:10 PM2/11/2010 3:01:10 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 732 Chapter 9 ASP.NET Web Services Click on the Close button located on the upper - right corner of the browser for two browser pages to close them. At this point, we should have a basic understanding and feeling about a typical Web Service project and its structure as well as its operation process. Next we will create our own Web Service project by modifying this default project to perform the request to our sample database, that is, to the Faculty table, to get the desired faculty information. We will develop our Web Service project in the following sequence: 1. Modify the default Web Service project to make it our new Web Service project. 2. Create a base class to handle error - checking codes to protect our real Web Service class. 3. Create our real Web Service class to hold all Web methods and codes to respond to requests to pick up desired faculty information. 4. Add Web methods into our Web Service class to access our sample database. 5. Develop the detail codes for those Web methods to perform the Web Services. 6. Build a Windows - based and a Web - based project to consume the Web Service to pick up and display the required information on the GUI. 7. Deploy our completed Web Service to Internet Information Service (IIS). The modifi cations defi ned in step 1 include the rename of the main service page ’ s name, the code - behind page ’ s name, the class name, and the namespace defi ned in the code - behind page and the main service page. Let ’ s start with the step 1. 9.3.3 Modify Default Web Service Project We will modify a default Web Service project to make it our new Web Service project and allow it to access our sample SQL Server database to pick up the desired faculty information. The following modifi cations must be made to this default project: • Rename the main service page from the default name Service to our new name WebServiceSQLSelect . • Rename the code - behind page ’ s name from Service.cs to our new name WebServiceSQLSelect.cs . • Modify the code - behind page ’ s name and class name in the main service page. • Rename the namespace defi ned in the code - behind page. • Add both reference and namespace System.Windows.Forms to this Web Service project since we need to test our project using the MessageBox() method, and this method is involved in that namespace. • Add some other namespaces related to the System Data components and SQL Server Data Provider since we need to use them to perform data actions in our sample database. Let ’ s start these modifi cations from step 1 listed above. c09.indd 732c09.indd 732 2/11/2010 3:01:11 PM2/11/2010 3:01:11 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... require a database connection in this project use SQL Server authentication with a login ID and password for a user account However, because we used Windows Authentication Mode when we created our sample database in Chapter 2, we do not need any login ID and password for the database connection in our application One important issue is the database we are using is not a real SQL Server 2005 database. .. process, Visual Studio.NET 2008 will try to find all Web Services available to our applications The following operations will be performed by Visual Studio.NET 2008 during this process: 1 When looking for Web Services from local computers, Visual Studio.NET 2008 will check all files that include a Web Service main page with a asmx extension, a WSDL file with a wsdl extension, or a Discovery file with a disco... StoredProcedure1 menu item to save this new stored procedure with a name of dbo.WebSelectFacultySP We can run this stored procedure in the Visual Studio.NET environment to confirm that it works fine Right-click on this new created stored procedure from the Server Explorer window and select the Execute item 9.3 Build ASP.NET Web Service Projects to Access SQL Server Database Figure 9.21 747 Running result of the stored... WebServiceSQLSelect that contains three Web methods can be found at the folder DBProjects\Chapter 9 located at the ftp://ftp wiley.com/public/sci_tech_med /practical_ database site Next we want to develop some professional Windows-based or Web-based applications with beautiful graphic user interfaces to use or to consume the Web Service application we developed in the previous sections Those Windows-based or... initialized with the connection string we obtained above D The Open() method of the SQL Connection object is executed to try to open our sample database and set up a valid connection E By checking the State property of the Connection object, we can determine whether this connection is successful or not If the State property is not equal to the ConnectionState Open, which means that a valid database connection... and data actions against our sample database via this Web Service project B The ConnectionStrings property of the ConfigurationManager class is used to pick up the connection string we defined in the web.config file, which can be considered as a default connection configuration The connection name sql_conn works as an argument for this property and must be identical with the name we defined for the connection... allow the Web method to return that DataSet as a whole package for those pieces of faculty information However, that better option is relatively complicated compared with our current class Therefore at this moment we prefer to start our project with an easier method Later on we can discuss how to use the DataSet to return our desired information As we mentioned before, this class is a child class of our... sqlConnection = new SqlConnection(); sqlConnection.ConnectionString = cmdString; sqlConnection.Open(); if (sqlConnection.State != System.Data.ConnectionState.Open) MessageBox.Show( "Database Open is failed"); else { MessageBox.Show( "Database Open is successful"); sqlConnection.Close(); } return "Hello World"; } B C D E F } Figure 9.12 Modified coding to test the connection string Now you can run the project... the Invoke button to execute that method to test our database connection A successful message should be displayed if this connection is fine Click on the OK button on the message box, and you can get the returned result from the execution of the method HelloWorld An issue is that when you run this project, it may take a little while to complete this database connection The reason for that is because the... conn.ConnectionString = cmdString; conn.Open(); if (conn.State != System.Data.ConnectionState.Open) { MessageBox.Show( "Database Open is failed"); conn = null; } return conn; } Figure 9.13 Modified Web method—GetSQLSelect 9.3 Build ASP.NET Web Service Projects to Access SQL Server Database 741 Let’s take a closer look at this piece of modified code to see how it works A Modification steps 1, 2, and 3 . . Also select the Visual C# from the Language box since we need to develop a Visual C# Web Service project in this chapter. Note that Visual Studio.NET. The code - behind page Service.cs contains the real Visual C#. NET codes for a simple Web Service. Visual Web Developer includes three default namespace

Ngày đăng: 07/11/2013, 11:15

Từ khóa liên quan

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

  • Đang cập nhật ...

Tài liệu liên quan