Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | REST-Based Web Services in ASP.NET

Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Server Technologies - Web Services

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

REST-Based Web Services in ASP.NET

we discuss how to build ASP.NET REST-based web services. Representational State Transfer (REST) (originally proposed in Roy Thomas Fielding’s doctoral dissertation) refers to an architectural style for implementing web services.

REST-Based Web Services in ASP.NET

 

[Note: This section assumes you already know ASP.NET (Chapter 25).] In this section,

 

we discuss how to build ASP.NET REST-based web services. Representational State Transfer (REST) (originally proposed in Roy Thomas Fielding’s doctoral dissertation) refers to an architectural style for implementing web services. Though REST is not a stan-dard, RESTful web services are implemented using web standards, such as HTTP, XML and JSON. Each operation in a RESTful web service is easily identified by a unique URL. So, when the server receives a request, it immediately knows what operation to perform. Such web services can be invoked from a program or directly from a web browser by en-tering the URL in the browser’s address field. In some cases, the results of a particular operation may be cached locally by the browser. This can make subsequent requests for the same operation faster by loading the result directly from the browser’s cache.2 Many Web 2.0 web services provide RESTful interfaces.

We use ASP.NET here because it provides a simple way to build REST-based web services. We take advantage of the tools provided in Microsoft’s Visual Web Developer 2005 Express, which you can download from msdn.microsoft.com/vstudio/express.

 

The example in this section is the web service that we consumed in our Calendar applica-tion from Fig. 15.11 in the Ajax chapter.

 

1. REST-Based Web Service Functionality

 

Figure 28.23 presents the code-behind file for the CalendarSevice web service that you’ll build in Section 28.9.2. When creating a web service in Visual Web Developer, you work almost exclusively in the code-behind file. This web service is designed to give the client access to a database of events. A client can access all events that occur on a specific day us-ing the getItemsByDate method or request a specific event using the getItemById meth-od. In addition, the client can modify an event by calling the Save method.

 

29' Fig. 28.23 CalendarService.vb

 

30' REST-based event web service.

 

31Imports System.Web

 

32Imports System.Web.Services

 

33Imports System.Web.Services.Protocols

 

34Imports System.Data ' Used to access a database

 

35Imports System.Web.Script.Serialization ' Used to return JSON

36          

34<WebService(Namespace:="http://www.deitel.com/")> _

 

35  <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

 

36  <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _

 

37  Public Class CalendarService

 

38         Inherits System.Web.Services.WebService

14

1            ' variables used to access the database

 

2            Private calendarDataSet As New CalendarDataSet()

 

3            Private eventsTableAdapter As _

 

4                   New CalendarDataSetTableAdapters.EventsTableAdapter()

5              

15         ' retrieve the event from the database given an id

 

16         <WebMethod(Description:="Gets a list of events for a given id.")> _

 

17         Public Sub getItemById(ByVal id As Integer)

 

18             ' set up the data set

 

19               eventsTableAdapter.FillById(calendarDataSet.Events, id)

25

19               ' insert the data into an Item object.

 

20               Dim identification As String = calendarDataSet.Events(0).ID

 

21               Dim description As String = calendarDataSet.Events(0).Description

 

22               Dim itemObject As New Item(identification, description)

30

24               ' convert the data to JSON and send it back to the client

 

25               Dim serializer As JavaScriptSerializer = New JavaScriptSerializer()

 

26               Dim response As String = serializer.Serialize(itemObject)

 

27               HttpContext.Current.Response.Write(response) ' send to client

 

28         End Sub ' getItemById

36

1             ' retrieve the list of events that occur on a specific date

 

2             <WebMethod(Description:="Gets a list of events for a given date.")> _

 

3             Public Sub getItemsByDate(ByVal eventDate As String)

 

4                   eventsTableAdapter.FillByDate(calendarDataSet.Events, eventDate)

 

5                   Dim identification As String ' string used to store the id

 

6                   Dim description As String ' string used to store the description

 

7                   Dim eventRow As DataRow ' used to iterate over the DataSet

 

8                   Dim length As Integer = calendarDataSet.Events.Rows.Count

 

9                   Dim itemObject As = New Item(0 To length - 1) {} ' initialize array

 

10                Dim count As Integer = 0

47

5                   ' insert the data into an array of Item objects

 

6                   For Each eventRow In calendarDataSet.Events.Rows

 

7                         identification = eventRow.Item("ID")

 

8                         description = eventRow.Item("Description")

 

9                         itemObject(count) = New Item(identification, description)

 

10                      count += 1

11                Next

55

9                   ' convert the data to JSON and send it back to the client

 

10                Dim serializer As New JavaScriptSerializer()

 

11                Dim response As String = serializer.Serialize(itemObject)

 

12                HttpContext.Current.Response.Write(response)

 

13         End Sub ' getItemsByDate

61

1             ' modify the description of the event with the given id

 

2             <WebMethod(Description:="Updates an event’s description.")> _

 

3             Public Sub Save(ByVal id As String, ByVal descr As String)

 

4                   eventsTableAdapter.UpdateDescription(descr, id)

 

5                   getItemById(id)

 

6             End Sub ' Save

 

7      End Class ' CalendarService

 

Fig. 28.23 | REST-based event web service.

Lines 3–7 import all the necessary libraries for b. Lines 3–5 are generated by Visual Web Developer for every web service. Line 6 enables us to use capabilities for interacting with databases. Line 7 imports the System.Web.Script.Serialization namespace, which provides tools to convert .NET objects into JSON strings.

 

Line 9 contains a WebService attribute. Attaching this attribute to a web service class indicates that the class implements a web service and allows you to specify the web service’s namespace. We specify  http://www.deitel.com as the web service’s namespace using the WebService attribute’s Namespace property.

 

Visual Web Developer places line 10 in all newly created web services. This line indi-cates that the web service conforms to the Basic Profile 1.1 (BP 1.1) developed by the Web Services Interoperability Organization (WS-I), a group dedicated to promoting interoper-ability among web services developed on different platforms with different programming languages. BP 1.1 is a document that defines best practices for various aspects of web service creation and consumption ( www.WS-I.org). Setting the WebServiceBinding attribute’s ConformsTo property to WsiProfiles.BasicProfile1_1 instructs Visual Web Developer to perform its “behind-the-scenes” work, such as generating WSDL file and the ASMX file (which provides access to the web service) in conformance with the guidelines laid out in BP 1.1. For more information on web services interoperability and the Basic Profile 1.1, visit the WS-I web site at  www.ws-i.org.

 

By default, each new web service class created in Visual Web Developer inherits from class System.Web.Services.WebService (line 13). Although a web service need not do this, class WebService provides members that are useful in determining information about the client and the web service itself. All methods in class CalendarService are tagged with the WebMethod attribute (lines 21, 38 and 63), which exposes a method so that it can be called remotely (similar to Java’s @WebMethod annotation that you learned earlier in this chapter).

 

Accessing the Database

 

Lines 16–18 create the calendarDataSet and eventsTableAdapter objects that are used to access the database. The classes CalendarDataSet and CalendarDataSetTableAdapter.EventsTableAdapter are created for you when you use Visual Web Developer’s DataSet Designer to add a DataSet to a project. Section 28.9.3 discusses the steps for this.

Our database has one table called Events containing three columns—the numeric ID of an event, the Date on which the event occurs and the event’s Description. Line 24 calls the method FillById, which fills the calendarDataSet with results of the query


The parameter @id is replaced with the id that was passed from the client, which we pass as an argument to the FillById method. Lines 27–29 store the results of the query in the variable of class Item, which will be defined shortly. An Item object stores the id and the description of an event. The id and description are obtained by accessing the ID and Description values of the first row of the calendarDataSet.

 

Line 40 calls the method FillByDate which fills the CalendarDataSet with results of the query

 

SELECT ID, Description

 

FROM   Events

 

WHERE  (Date = @date)

 

The parameter @date is replaced with the eventDate that was passed from the client, which we pass as an argument to the FillByDate method. Lines 49–54 iterate over the rows in the calendarDataSet and store the ID and Description values in an array of Items.

 

Line 65 calls method UpdateDescription which modifies the database with the

 

UPDATE statement.

 

UPDATE Events

 

SET     Description = @descr

 

WHERE  (ID = @id)

 

The parameters @descr and @id are replaced with arguments passed from the client to the updateDescription method.

 

Responses Formatted as JSON

 

The web service uses JSON (discussed in Section 15.7) to pass data to the client. To return JSON data, we must first create a class to define objects which will be converted into JSON format. Figure 28.24 defines a simple Item class that contains Description and ID members, and two constructors. The Description and ID are declared as Public members so that Item objects can be properly converted to JSON.

5    ' Fig. 28.24 Item.vb

 

6    ' A simple class to create objects to be converted into JSON format.

 

7    Imports Microsoft.VisualBasic

 

8    Public Class Item

 

9          Private descriptionValue As String ' the item’s description

 

10       Private idValue As String ' the item’s id

7

1          ' Default constructor

 

2          Public Sub New()

 

3            End Sub 'New

11

5            ' constructor that initializes id and description

 

6            Public Sub New(ByVal ident As String, ByVal descr As String)

 

7                   id = ident

 

8                   description = descr

 

9            End Sub 'New

17

14         ' property that encapsulates the description

 

15         Public Property description() As String

16               Get

 

17                      Return descriptionValue

 

18               End Get

 

19               Set(ByVal value As String)

 

20                      descriptionValue = value

 

21               End Set

 

22         End Property ' description

27

19         ' Property that encapsulates the id

 

20         Public Property id() As String

21               Get

 

22                      Return idValue

 

23               End Get

 

24               Set(ByVal value As String)

 

25                      idValue = value

 

26               End Set

 

27         End Property ' id.

 

28  End Class ' Item


 

Fig. 28.24 | A simple class to create objects to be converted into JSON format.

 

vert the objects into JSON strings. Then, lines 34 and 59 obtain a response object for the current client, using the Current property of the HttpContext object. Then we use this object to write the newly constructed JSON string as part of the response attribute, initi-ating the server response to the Ajax application in Fig. 15.11. To learn more about JSON

visit our JSON Resource Center at  www.deitel.com/JSON.

 

2. Creating an ASP.NET REST-Based Web Service

 

We now show you how to create the CalendarService web service in Visual Web Devel-oper. In the following steps, you’ll create an ASP.NET Web Service project that executes on your computer’s local IIS web server. Note that when you run this web service on your local computer the Ajax application from Fig. 15.11 can interact with the service only if it is served from your local computer. We discuss this at the end of this section. To create the CalendarService web service in Visual Web Developer, perform the following steps:

 

Step 1: Creating the Project

To begin, use Visual Web Developer create a project of type ASP.NET Web Service. Select File > New Web Site… to display the New Web Site dialog (Fig. 28.25). Select ASP.NET Web Service in the Templates pane. Select HTTP from the Location drop-down list to indicate that the files should be placed on a web server. By default, Visual Web Developer indicates that it will place the files on the local machine’s IIS web server in a virtual directory named WebSite ( http://localhost/WebSite). Replace the name WebSite with CalendarService for this example. Next, select Visual Basic from the Language drop-down list to in-dicate that you will use Visual Basic to build this web service.


 

Step 2: Examining the Newly Created Project

 

After you create the project, you should see the code-behind file Service.vb, which con-tains code for a simple web service (Fig. 28.26). If the code-behind file is not open, it can be opened by double clicking the file in the App_Code directory from the Solution Explor-er. Visual Web Developer includes three Imports statements that are helpful for develop-ing web services (lines 1–3). By default, a new code-behind file defines a class named Service that is marked with the WebService and WebServiceBinding attributes (lines 5–6). The class contains a sample web method named HelloWorld (lines 11–14). This meth-od is a placeholder that you will replace with your own method(s).



Step 3: Modifying and Renaming the Code-Behind File

To create the CalendarService web service developed in this section, modify Service.vb by replacing the sample code provided by Visual Web Developer with the code from the CalendarService code-behind file (Fig. 28.23). Then rename the file CalendarSer-vice.vb (by right clicking the file in the Solution Explorer and choosing Rename). This code is provided in the examples directory for this chapter. You can download the exam-

ples from  www.deitel.com/books/iw3htp4/.

 

Step 4 Creating an Item Class

Select File > New File… to display the Add New Item dialog. Select Class in the Templates pane and change the name of the file to Item.vb. Then paste the code for Item.vb (Fig. 28.24) into the file.

Step 5: Examining the ASMX File

 

The Solution Explorer lists a Service.asmx file in addition to the code-behind file. A web service’s ASMX page, when accessed through a web browser, displays information about the web service’s methods and provides access to the web service’s WSDL information. However, if you open the ASMX file on disk, you will see that it actually contains only

 

<%@ WebService Language="vb" CodeBehind="~/App_Code/Service.vb" Class="Service" %>

 

to indicate the programming language in which the web service’s code-behind file is writ-ten, the code-behind file’s location and the class that defines the web service. When you request the ASMX page through IIS, ASP.NET uses this information to generate the con-tent displayed in the web browser (i.e., the list of web methods and their descriptions).

 

Step 6: Modifying the ASMX File

Whenever you change the name of the code-behind file or the name of the class that de-fines the web service, you must modify the ASMX file accordingly. Thus, after defining class CalendarService in the code-behind file CalendarService.vb, modify the ASMX file to contain the lines

 

<%@ WebService Language="vb" CodeBehind= "~/App_Code/CalendarService.vb" Class="CalendarService" %>

 

Step 7: Renaming the ASMX File

The final step in creating the CalendarService web service is to rename the ASMX file

 

CalendarService.asmx.

 

Step 8: Changing the Web.Config File to allow REST requests.

By default ASP.NET web services communicate with the client using SOAP. To make this service REST-based, we must change web.config file to allow REST requests. Open the web.config file from the Solution Explorer and paste the following code as a new element in the system.web element.

 

<webServices>

 

<protocols>

 

<add name="HttpGet"/> <add name="HttpPost"/>

 

</protocols>

 

</webServices>

 

Step 9: Adding the System.Web.Extensions Reference

The JavaScriptSerializer class that we use to generate JSON strings, is part of the Ajax Extensions package. You can find information on installing and downloading ASP.NET Ajax in Section 25.9. After you have installed ASP.NET Ajax, right click the project name in the solution explorer and select Add Reference... to display the Add Reference window.

Select System.Web.Extensions from the .NET tab and click OK.

3. Adding Data Components to a Web Service

 

Next, you’ll use Visual Web Developer’s tools to configure a DataSet that allows our Web service to interact with the Calendar.mdf SQL Server 2005 Express database file. You can download Calendar.mdf with the rest of the code for this example at  www.deitel.com/  books/iw3htp4. You’ll add a new DataSet to the project, then configure the DataSet’s TableAdapter using the TableAdapter Configuration Wizard. The wizard allows you to se-lect the data source (Calendar.mdf) and to create the SQL statements necessary to support the database operations discussed in Fig. 28.23’s description.

 

Step 1: Adding a DataSet to the Project

 

Add a DataSet named CalendarDataSet to the project. Right click the App_Code folder in the Solution Explorer and select Add New Item… from the pop-up menu. In the Add New Item dialog, select DataSet, specify CalendarDataSet.xsd in the Name field and click Add. This displays the CalendarDataSet in design view and opens the TableAdapter Configura-tion Wizard. When you add a DataSet to a project, the IDE creates appropriate Table-Adapter classes for interacting with the database tables.

 

Step 2: Selecting the Data Source and Creating a Connection

You’ll use the TableAdapter Configuration Wizard in the next several steps to configure a

 

TableAdapter for manipulating the Events table in the Calendar.mdf database. Now, you must select the database. In the TableAdapter Configuration Wizard, click the New Connection… button to display the Add Connection dialog. In this dialog, specify Microsoft SQL Server Database File as the Data source, then click the Browse… button to display the Select SQL Server Database File dialog. Locate Calendar.mdf on your computer, select it and click the Open button to return to the Add Connection dialog. Click the Test Connec-tion button to test the database connection, then click OK to return to the TableAdapter Configuration Wizard. Click Next >, then click Yes when you are asked whether you would like to add the file to your project and modify the connection. Click Next > to save the connection string in the application configuration file.

 

Step 3: Opening the Query Builder and Adding the Events Table from Calendar.mdf

 

You must specify how the TableAdapter will access the database. In this example, you’ll use SQL statements, so choose Use SQL Statements, then click Next >. Click Query Build-er… to display the Query Builder and Add Table dialogs. Before building a SQL query, you must specify the table(s) to use in the query. The Calendar.mdf database contains only one table, named Events. Select this table from the Tables tab and click Add. Click Close to close the Add Table dialog.

 

Step 4: Configuring a SELECT Query to Obtain a Specific Event

Now let’s create a query which selects an event with a particular ID. Select ID and Descrip-tion from the Events table at the top of the Query Builder dialog. Next, specify the criteria for selecting seats. In the Filter column of the ID row specify =@id to indicate that this filter value also will be specified as a method argument. The Query Builder dialog should now appear as shown in Fig. 28.27. Click OK to close the Query Builder dialog. Click Next > to choose the names of the methods to generate. Name the Fill method FillById. Click the Finish button to generate this method.


Step 5: Adding Another Query to the EventsTableAdapter for the CalendarDataSet

 

Now, you’ll create an UPDATE query that modifies a description of a specific event. In the design area for the CalendarDataSet, click EventsTableAdapter to select it, then right click it and select Add Query… to display the TableAdapter Query Configuration Wizard. Select Use SQL Statements and click Next >. Select Update as the query type and click Next >. Clear the text field and click Query Builder… to display the Query Builder and Add Table dialogs. Then add the Events table as you did in Step 3 and click Close to return to the Query Builder dialog.

 

Step 6: Configuring an UPDATE Statement to Modify a Description of a Specific Event

 

In the Query Builder dialog, select the Description column from the Events table at the top of the dialog. In the middle of the dialog, place the @descr in the New Value column for the Description row to indicate that the new description will be specified as an argument to the method that implements this query. In the row below Description, select ID and specify @id as the Filter value to indicate that the ID will be specified as an argument to the method that implements this query. The Query Builder dialog should now appear as shown in Fig. 28.28. Click OK to return to the TableAdapter Query Configuration Wizard. Then click Next > to choose the name of the update method. Name the method UpdateDescription, then click Finish to close the TableAdapter Query Configuration Wizard.

 

Step 7: Adding a getItemsByDate Query

 

Using similar techniques to Steps 5–6, add a query that selects all events that have a spec-ified date. Name the query FillByDate.


Step 8: Testing the Web Service

At this point, you can use the CalendarService.asmx page to test the web service’s meth-ods. To do so, select Start Without Debugging from the Debug menu. Figure 28.29 shows the test page that is displayed for this web service when you run the web service applica-tion.



Calling a REST-based web service is simpler than calling SOAP web services demon-strated earlier. Fig. 28.29 shows that you can invoke the web service directly from your browser. For example, if you type the URL  http://localhost/calendarService/ calendarService.asmx/getItemById?id=1 the browser will invoke the method get-ItemById and retrieve the event with the id value 1.

 

The client side interface for this application is implemented in the Ajax chapter, in Fig 15.11. Because our Calendar application uses the Dojo Toolkit, you must have Dojo installed on your computer. Download Dojo 0.4.3 from dojotoolkit.org/downloads, extract the Dojo directory and rename it to dojo043. Then place the CalendarService folder that contains your web service, the dojo043 folder that contains the Dojo toolkit and the Calendar.html file in the same directory in the root directory of your web server.

 

Run the web service and direct your browser to the location of the Calendar.html file. We populated the database only with events for July 2007, so the calendar is coded to always display July 2007 when the application is loaded. To test whether the web service works click a few dates like the fourth of July, the sixth of July or the twentieth of July for which events exist in the Calendar database


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.