C# Bible 2002 phần 9 pptx

63 265 0
C# Bible 2002 phần 9 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

In the Web service that you create in this chapter, you use an SQL Server database. Before you create the SQL Server database and tables for the Web service, quickly review important Relational Database Management Systems (RDBMS) concepts. Relational Database Management Systems concepts A Relational Database Management System (RDBMS) is best suited for enterprise business solutions. An RDBMS, such as Microsoft SQL Server, Oracle, and DB2, enables the creation, updating, and administration of relational databases. A relational database is a collection of data organized in the form of tables. Applications can access data in tables using the Structured Query Language (SQL) statements. In an RDBMS, you can access data and reorganize data without reorganizing the entire database. This improves the performance of the database considerably. In addition, you can easily apply business rules, validations, and constraints to the data in the tables of an RDBMS. Business rules and validations ensure data integrity. For example, when you book a passenger on a flight in an airway reservation system, the flight number should exist. You can determine the flight number by establishing a business rule and using it while booking a ticket. SQL Server data types Data in a database is stored in tables, as rows and columns. The columns of a table store categorized information, such as product identification number, product name, and quantity available. The rows of a table store specific records. Each column in a table has a specific data type. Table 28-1 describes some of the common SQL Server data types. Table 28-1: SQL Data Types Data type Description Integer Used to store whole numbers. Float Used to store decimal numbers. char(n) Used to store character data that can be alphabetical, numerical, special characters, such as #, %, or $, or a combination of letters and characters. A char data type stores a single character. To store more than one charac- ter, you use char(n), where n refers to the number of characters that you want to store varchar(n) Used to store character data, where n refers to the number of characters you want to store. A varchar data type is different from a char data type because the memory allotted to a varchar data type depends upon the size of data, unlike the char data type, in which allocated memory is predefined. Datetime Used to store date and time data. Money Used to store currency-related data values that demand high precision. Tip Each table must have at least one column that uniquely identifies a row (referred to as a record) in the table. Such a column is the primary key of the table. For example, the ProductID column in a Products table identifies each row uniquely and is therefore a p rimary key. No two values in a primary key can be i d entical. Creating databases and tables In Microsoft SQL Server, you can create databases, tables, stored procedures, and queries by using Transact-SQL (T-SQL). Tip You can also use SQL Server Enterprise Manager to create a database and tables. SQL Server Enterprise Manager provides a graphical interface to perform the same steps that are performed by using T-SQL statements. To create a database or a table using T-SQL, you use the Create statement. For example, to create a database Sales, you write the following code in the query analyzer window: Create Database Sales After creating the database, you can add tables to it. Add the Products table to the Sales database by using the following syntax: Create Table Products ( ProductID VarChar (4) Primary Key, ProductName VarChar (20), UnitPrice Integer, QtyAvailable Integer ) Retrieving data You can retrieve information stored in tables by using the Select statement. For example, to retrieve all the records from the Products table of the Sales database, you use the following statements: Use Sales Select * From Products Inserting, updating, and deleting data You can add, update, and delete data from an SQL Server database by using the steps outlined in the following list: • Add a record: To add a new row to an SQL Server table, you use the Insert statement. For example, to add a new record to the Products table, you use the following statement: • Insert Into Products (ProductID, ProductName, UnitPrice, • QtyAvailable) Values ('P001', 'Baby Food', 2.5, 12000) Caution In order for the insert operation to be successful, the column values must be supplied in the same order as the columns in the table. In addition, if the data type of a column is char, varchar, or datetime, you need to specify values in quotes. • Modify a record: To modify a record in an SQL Server table, you use the Update statement: • Update Products • Set UnitPrice=75 Where ProductID="P010" The preceding code updates the unit price of the record whose product ID is P010 to 75. • Delete a record: To delete a record from a table, you use the Delete statement. For example, to delete a record from the Products table with the Product ID of P011, you specify the following statement: Delete From Products where ProductID="P011" Using stored procedures A stored procedure is a set of SQL statements used to perform specific tasks. A stored procedure resides on the SQL Server and can be executed by any user who has the appropriate permissions. You can create a stored procedure by using the Create Procedure statement. Create a stored procedure that accepts the ProductID as a parameter and returns the unit price of the record matching the ProductID by using the following code: Create Procedure ProductPrice (@id char (4)) As Select UnitPrice From Products Where ProductID=@id Return The preceding procedure requires a parameter, @id, at the time of execution. Stored procedures are particularly useful when you need to perform a number of tasks on a database one after the other. For example, when you want to cancel the reservation of a passenger, you might need to calculate the fare that needs to be refunded to the customer and delete the reservation of the customer from a reservations table. At the same time, you might also need to update the status of other passengers who might be overbooked on the flight. Instead of specifying SQL queries each time you want to cancel a reservation, you can use a stored procedure to cancel the reservation of a passenger. Caution Each stored procedure must end with a Return statement. To execute the preceding procedure to display the price of the product with the ID P010, use the following code: Execute ProductPrice "P010" Creating the database structure In this chapter, you need to create a Sales database for your Web service. After creating the Sales database, you add a Products table to the database. To create the Sales database and add the Products table to it, follow these steps: 1. Select Start → Programs → Microsoft SQL Server → Query Analyzer to open Query Analyzer. The Connect to SQL Server dialog box opens. 2. In the Connect to SQL Server dialog box, type the name of the SQL Server in the SQL Server text box, specify a login name in the Login Name text box, and specify the password for the login name in the Password text box. 3. Click OK to connect to the SQL Server and open the query editor. 4. In the query editor, enter the following statements to create the Sales database and add the Products table to the database: 5. Create database Sales 6. GO 7. Use Sales 8. Create Table Products 9. ( 10. ProductID VarChar (4) Primary Key, 11. ProductName VarChar (20), 12. UnitPrice Integer, 13. QtyAvailable Integer 14. ) GO 15. Select Query → Execute to execute the query. After you execute the query, the database structure is in place. You are now ready to create the Web service - the first of the ASP.NET applications that you create in this chapter. The Web service that is created in this chapter adds records to the Products table of the Sales database that you created in this section. Using the ASP.NET Web service template You need to use the ASP.NET Web Service project template to create a Web service. This project serves as a Web-based template for creating the Web service components. To create a Web service, perform the following steps: 1. Select File → New → Project to open the New Project dialog box. Tip You can also press Ctrl+Shift+N simultaneously to open the New Project dialog box. 2. From the Project Types list, select Visual C# Projects. 3. From the Templates pane on the right side of the dialog box, select ASP.NET Web Service. 4. In the Name box, type OrdersWebService. In the Location box, and enter the name of your Web server as http://<servername>. Click OK. Tip You can also type localhost in the Location box if the Web server is installed on the computer on which you are creating the Web service. N ote You may have to wait for some time while Visual Studio .NET creates the Web service. After Visual Studio .NET creates the Web service, you can configure the Web service to manage data in SQL Server. You do that in the next section. Adding data controls to the Web service You need to add data controls to your Web service to enable communication with the Sales database that you created in the previous section. To communicate with the party database, you need to add the following controls to your Web service: • SqlDataAdapter: You use the SqlDataAdapter control to transfer data between data sources. • SqlConnection and SqlDataAdapter: You use the SqlDataAdapter and SqlConnection controls to connect to the data source. • SqlCommand: After connecting to the data source, you use the OleDbCommand control to access data. • DataSet: You store data in a DataSet control. The steps to add the SqlDataAdapter control are as follows: 1. Select View → Toolbox to open the toolbox. 2. In the toolbox, click Data to activate the Data tab. 3. Drag the SqlDataAdapter control from the toolbox to the Component Designer. 4. When you drag the SqlDataAdapter control from the toolbox, the Data Adapter Configuration wizard launches. On the Welcome screen of the wizard, click Next. 5. The Choose Your Data Connection dialog box of the wizard, shown in Figure 28-1 appears. Click New Connection to create a new connection by using the OleDbDataAdapter control. Figure 28-1: The Choose Your Data Connection dialog box 6. The Data Link Properties dialog box opens. By default, the Connection tab of this dialog box is selected. Specify the name of the SQL Server on the Select or Enter a Server Name dialog box. 7. Select the user name and password to connect to the SQL Server, and select the Sales database from the Select the Database on the Server drop-down list. The completed Data Link Properties screen is shown in Figure 28-2 . Click OK. Figure 28-2: Connect to the data source by using the Data Link Properties dialog box. 8. The data adapter that you configured appears in the Choose Your Data Connection dialog box. Click Next to continue. 9. The Choose a Query Type dialog box opens. To use an SQL query for retrieving data from the database, retain the default option, Use SQL Statements, and click Next. 10. The Generate the SQL Statements dialog box opens. In this dialog box, type the query Select * from Products and click Next. 11. The View Wizard Results dialog box opens. This dialog box summarizes the options that you selected in the preceding dialog boxes of the wizard. Click Finish to complete the Data Adapter Configuration Wizard. After you complete the Data Adapter Configuration Wizard, the SqlDataAdapter control is configured for your application. As shown in Figure 28-3, the sqlDataAdapter1 and sqlConnection1 controls are added to your application. Figure 28-3: The sqlDataAdapter1 and sqlConnection1 controls are added to your application. Next, add the SqlCommand control to the Web service. The SqlCommand control is used to specify commands that need to be executed on the data source. Follow these steps to add an SqlCommand control to your application: 1. Drag the SqlCommand control from the toolbox to the Component Designer. 2. Open the Properties window and select sqlConnection1 for the Connection property of the SqlCommand control. Next, you need to generate a dataset for storing data that is retrieved by the data controls: 1. To generate the dataset, select the SqlCommand1 control that you added in the preceding steps, and select the Data → Generate Dataset menu option. 2. The Generate Dataset dialog box opens. In this dialog box, the Products table of the Sales database is already selected. Select the Add This Dataset to the Designer check box, and click OK to generate the dataset and add it to the Component Designer. The four controls that you added to the Web service are now visible in the Component Designer. You now need to code the methods of the Web service, which you do in the next section. Coding the Web service After you add the data controls to the Web service, you need to code the methods of the Web service. This chapter demonstrates how you can code a method to add products to the Products database by using the Web service. Before you code the methods of the Web service, add a description to and change the default namespace of the Web service. The description and the namespace of the Web service enable a Web service client developer to understand the usage of the Web service. To add a description and change the default namespace associated with the Web service, follow these steps: 1. Double-click the Component Designer to open the Code Editor. 2. In the Code Editor, locate the statement public class Service1. 3. Add the following code before the statement that you located in Step 2: 4. [WebService(Namespace="http://ServiceURL.com/products/", 5. Description="Use the Web service to add products to the 6. Sales database.")] After you enter the preceding line of code, the namespace of the Web service is http://ServiceURL.com/products/, and a description is added to the Web service. Next, write the code for adding products to the Products table. This code needs to be written immediately below the declaration of the Web service. The code for the AddProduct method, which adds product details to the Products table, is as follows: [WebMethod(Description="Specify the product ID, product name, unit price, and quantity to add it to the Sales catalog")] public string AddProduct(string PID, string ProductName, int Price, int Qty) { try { ProductName=ProductName.Trim(); if (Price<0) return "Please specify a valid value for price"; if (Qty<0) return "Please specify a valid value for quantity"; sqlConnection1.Open(); sqlCommand1.CommandText="INSERT INTO Products(ProductID, ProductName, UnitPrice, QtyAvailable) VALUES ('" + PID + "', '" + ProductName + "', '" + Price + "', '" + Qty + "')"; sqlCommand1.ExecuteNonQuery(); sqlConnection1.Close(); return "Record updated successfully"; } catch(Exception e) { return e.Message; } } The preceding code uses the sqlConnection1 control to add a record to the Products table. When you add records to the Web service, you use the values that are supplied to the AddProduct function as parameters. As you code the AddProduct method of the Web service, you can code other methods to retrieve product details in the Products database or perform other custom actions. To test the Web service after you add the methods to it, follow these steps: 1. Select Build → Build Solution to build the Web service. 2. To start debugging the Web service, select the Debug → Start menu option. The Web service opens in Internet Explorer. The first dialog box displays the methods that you coded for your Web service. To test the AddProduct method, follow these steps: 1. Click AddProduct on the Service1 Web Service dialog box. 2. The AddProduct dialog box opens, as shown in Figure 28-4. In this dialog box, you can invoke the AddProduct function after supplying the required parameters to test its output. Figure 28-4: Specify the parameters for the AddProduct function in order to test it. 3. Type the parameters for PID, ProductName, Price, and Qty as P002, PDA, 100, 200, respectively, and click Invoke to test its output. 4. When the record is added successfully to the Web service, you see the output displayed in Figure 28-5. Figure 28-5: Output such as this appears when a record is successfully added to the Web service. After you successfully test your Web service, you can create a Web service client to access the Web service. Creating a Web Service Client A Web service client in ASP.NET is a Web application that comprises one or more WebForms. In this section, you create an ASP.NET Web application that accesses the Web service you created in the previous section . Cross-Reference For more information on WebForms, see Chapter 22, "Creating Web Applications with WebForms." To create a Web service client, you need to follow these steps: 1. Create a new ASP.NET Web Application project. 2. Add a Web reference to the Web application. 3. Implement the methods of the Web service in the Web application. The following section examines each of these steps in detail. Creating a new ASP.NET Web application project To create a Web application project, follow these steps: 1. Select the File → New → Project menu option. The New Project dialog box opens. 2. In the New Project dialog box, select the ASP.NET Web Application project template from the Visual C# Projects list. 3. Enter OrdersWebApplication as the name of the project and click OK to create the Web application. Adding a Web reference After you create the Web service, you need to add a Web reference to the Web service that you created in the preceding section. When you add a Web reference, the Web service client downloads the description of the Web service and creates a proxy class for the Web service. A proxy class includes proxy functions for methods of the Web service. To add a Web reference to the Web service, follow these steps: 1. Select the WebForm1.aspx Web form and then Select the Project → Add Web Reference menu option. The Add Web Reference menu option opens. 2. In the Add Web Reference dialog box, click the Web References on Local Web Server link. The Web services available on the local Web server appear in the Available references list, as shown in Figure 28-6. Figure 28-6: Available Web services are displayed in the Add Web Reference dialog box. [...]... Right-click; select Add, and then select Add Method The C# Method Wizard opens, as shown in Figure 29- 5 Figure 29- 5: The C# Method Wizard 10 Name this new method Start and ensure that it is a public method You can leave all the other settings at their default After you create the new method, add the code shown in Listing 29- 3 to the method's code listing Listing 29- 3: Start Method public void Start() { timer1.Interval... control in one of two ways You can use the C# Method Wizard, accessible through the Solution Explorer while in Class view, or you can simply add a public function to your project The C# Method Wizard, shown in Figure 29- 2 enables you to specify the method name, return type, access method, and parameter information in a very straightforward manner Figure 29- 2: The C# Method Wizard creates the skeleton code... to stop the Countdown control Arrange and set the text properties as shown in Figure 29- 7 Figure 29- 7: The main interface for your CountDown harness application 9 Double-click the Start button within your application so you can begin coding Add the code in Listing 29- 6 to the Click event of the Start button Listing 29- 6: Start Your Control private void button1_Click(object sender, System.EventArgs e)... will count down from You create a property much as you create a method 1 From Class view in the Solution Explorer, right-click and choose Add and then Add Property The C# Property Wizard, shown in Figure 29- 6 opens Figure 29- 6: In the C# Property Wizard, name this property Seconds Ensure that this property has public access and that the property type is set to Int 2 You want the controls container... categories, Conversion and Calculation, you are going to include two separate classes Create a new class library project and name it Temperature Visual Studio creates the skeleton code shown in Listing 29- 9 Listing 29- 9: Code Created for a Class Library by Visual Studio using System; namespace TmpTure { } /// /// Summary description for Class1 /// public class Class1 { public Class1() {... with the code shown in Listing 29- 10 Listing 29- 10: The Calc Class and Constructor public class Calc { public Calc() { } } 2 The Calc class is where you place your windchill calculation method This ensures that your windchill calculation is separated from the conversion methods that you will soon add Paste the code shown in Listing 29- 11 into the Calc class Listing 29- 11: Calculate the Current Windchill... Listing 29- 13 contains the function listing in its entirety Add this code to the Conversion class Listing 29- 13: Celsius to Fahrenheit Conversion public double CelcToFahr(double Celsius) { return (9/ 5) * (Celsius + 32); } 5 Because you have included a Celsius to Fahrenheit conversion function, it is only logical to include a conversion in the opposite direction Add the method shown in Listing 29- 14 to... container application to be able to assign a value to this property or read the value from this property Therefore, you want the accessor set to get/set Add the code in Listing 29- 5 to the code created by the C# Property Wizard Listing 29- 5: Seconds Property public int Seconds { get { return m_Seconds; } set { m_Seconds = value; } } Pay special attention to the value keyword When a value is passed in to a... to start the control on its journey to counting seconds Listing 29- 3 defines the interval of the Timer control (in milliseconds) and then starts the Timer control After the timer has been started, you must update the Label control because it won't be get updated until 1 second later when the timer fires the Tick event for the first time 9 To add a method to the control, switch the Solution Explorer to... copied to the destination that you specified in Step 3 After you copy the project, you can run the project from the new location Summary The role of C# in ASP.NET pertains to Web services and Web applications You can create a Web service by using the C# language syntax in ASP.NET You can also create a Web application that accesses the Web service and builds upon its functionality When you create an . use the C# Method Wizard, accessible through the Solution Explorer while in Class view, or you can simply add a public function to your project. The C# Method Wizard, shown in Figure 29- 2 enables. from the new location. Summary The role of C# in ASP.NET pertains to Web services and Web applications. You can create a Web service by using the C# language syntax in ASP.NET. You can also. wizard, shown in Figure 29- 1, enables you to set the type of access, the property type (int, bool, and so on), the property name, accessors, and modifiers. Figure 29- 1: The Add Property Wizard

Ngày đăng: 05/08/2014, 10:20

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

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

Tài liệu liên quan