or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

73
EVALUATION COPY ASP.NET WEB API ESSENTIALS USING C# Unauthorized Reproduction or Distribution Prohibited

Transcript of or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

Page 1: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY ASP.NET WEB APIESSENTIALS USING C#

Unauthorized Reproduction or Distribution Prohibited

Page 2: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

Object Innovations Course 4147

Student Guide Revision 4.7

ASP.NET Web API Essentials Using C#

Unauthorized Reproduction or Distribution Prohibited

Page 3: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC ii All Rights Reserved

ASP.NET Web API Essentials Using C# Rev. 4.7 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Object Innovations. Product and company names mentioned herein are the trademarks or registered trademarks of their respective owners.

™ is a trademark of Object Innovations. Author: Robert J. Oberg Copyright ©2016 Object Innovations Enterprises, LLC All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Printed in the United States of America.

Unauthorized Reproduction or Distribution Prohibited

Page 4: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC iii All Rights Reserved

Table of Contents (Overview) Chapter 1 Introduction to ASP.NET Web API Chapter 2 Web API and HTTP Chapter 3 Media Formatters and Content Negotiation Chapter 4 JavaScript Clients Chapter 5 Binding, Validation and Routing Chapter 6 .NET Clients Appendix A Learning Resources

Unauthorized Reproduction or Distribution Prohibited

Page 5: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC iv All Rights Reserved

Directory Structure

The course software installs to the root directory C:\OIC\WebApiCs.

Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on.

The Labs directory contains one subdirectory for each lab, named after the lab number. Starter code is frequently supplied, and answers are provided in the chapter directories.

The Demos directory is provided for doing in-class demonstrations led by the instructor.

Unauthorized Reproduction or Distribution Prohibited

Page 6: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC v All Rights Reserved

Table of Contents (Detailed)

Chapter 1: Introduction to ASP.NET Web API ................................................................ 1 ASP.NET Web API ............................................................................................................ 3 REST................................................................................................................................... 4 Representation, State and Transfer ..................................................................................... 5 Collections and Elements.................................................................................................... 6 Web API Demo................................................................................................................... 7 Specifying a Start Page ..................................................................................................... 11 Implementing PUT Verb................................................................................................... 12 Using Fiddler .................................................................................................................... 13 Composing a Request ....................................................................................................... 15 ASP.NET MVC and Web API.......................................................................................... 17 String API Demo............................................................................................................... 18 Route Registration ............................................................................................................ 20 Lab 1 ................................................................................................................................. 23 Summary ........................................................................................................................... 24

Chapter 2: Web API and HTTP........................................................................................ 29 HTTP Response Codes ..................................................................................................... 31 POST Response Code ....................................................................................................... 32 HttpResponseException.................................................................................................... 33 Performing CRUD Operations.......................................................................................... 34 Books API Example.......................................................................................................... 35 Server Code: Model .......................................................................................................... 36 Book Repository ............................................................................................................... 37 BooksController................................................................................................................ 39 Exercise the Server Using Fiddler .................................................................................... 41 Exercise PUT .................................................................................................................... 42 Exercise POST.................................................................................................................. 43 Exercise GET Again ......................................................................................................... 44 Lab 2 ................................................................................................................................. 45 Summary ........................................................................................................................... 46

Chapter 3: Media Formatters and Content Negotiation................................................. 55 Internet Media Types ........................................................................................................ 57 Media Type in HTTP........................................................................................................ 58 Media Type Demo ............................................................................................................ 59 MediaFmtDemo Code....................................................................................................... 62 Exercising PUT................................................................................................................. 63 Exercising POST............................................................................................................... 64 HTTP Content Negotiation............................................................................................... 65 Media Range and Quality Factors .................................................................................... 66 Web API Content Negotiation .......................................................................................... 67 Default Content Negotiator............................................................................................... 68

Unauthorized Reproduction or Distribution Prohibited

Page 7: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC vi All Rights Reserved

Media Type Mappings ...................................................................................................... 69 Query String Mapping ...................................................................................................... 70 Request Header Mapping.................................................................................................. 71 Content Negotiation Priority............................................................................................. 72 Info about Media Type Formatters ................................................................................... 73 Serialization ...................................................................................................................... 74 Serialization in .NET ........................................................................................................ 75 JavaScript Object Notation ............................................................................................... 76 JSON Data Types.............................................................................................................. 77 Comparing JSON and XML ............................................................................................. 78 XML Serialization ............................................................................................................ 79 BSON................................................................................................................................ 80 Lab 3 ................................................................................................................................. 81 Summary ........................................................................................................................... 82

Chapter 4: JavaScript Clients ........................................................................................... 91 What is DHTML? ............................................................................................................. 93 DHTML Components ....................................................................................................... 94 Document Object Model................................................................................................... 95 Browser Objects................................................................................................................ 96 Accessing DOM Nodes..................................................................................................... 97 Demo: Using the DOM..................................................................................................... 98 Using jQuery................................................................................................................... 101 CSS (Cascading Style Sheets) ........................................................................................ 103 CSS Syntax ..................................................................................................................... 104 Style Sheets..................................................................................................................... 105 jQuery Library ................................................................................................................ 107 jQuery and Visual Studio................................................................................................ 108 Selectors.......................................................................................................................... 109 jQuery Wrapper .............................................................................................................. 110 Selector and Wrapper Example ...................................................................................... 111 Example Script................................................................................................................ 112 jQuery Ajax Methods...................................................................................................... 114 Shorthand Methods ......................................................................................................... 115 jQueryHouses Example .................................................................................................. 116 Using getJSON()............................................................................................................. 117 Handling Errors............................................................................................................... 118 Low Level Interface........................................................................................................ 119 HouseDemo Example ..................................................................................................... 120 Invoking POST ............................................................................................................... 121 Lab 4 ............................................................................................................................... 122 Summary ......................................................................................................................... 123

Chapter 5: Binding, Validation and Routing ................................................................. 127 Binding Data from HTTP Requests................................................................................ 129 Reading a Raw HTTP Request ....................................................................................... 130

Unauthorized Reproduction or Distribution Prohibited

Page 8: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC vii All Rights Reserved

House Controller............................................................................................................. 131 Deserializing JSON......................................................................................................... 132 Client JavaScript Code.................................................................................................... 133 Reading HTTP Request into CLR .................................................................................. 134 Binding in ASP.NET Web API ...................................................................................... 135 Bind HTTP Request to Simple Types............................................................................. 136 Binding via Route Data................................................................................................... 137 Binding via Query String................................................................................................ 138 JavaScript Client ............................................................................................................. 139 Binding via Request Body .............................................................................................. 140 Client Code for Using Request Body ............................................................................. 141 Bind HTTP Request to Complex Type........................................................................... 142 Simple and Complex Types ............................................................................................ 143 Client Code for POST Request ....................................................................................... 144 Client Code for GET Request ......................................................................................... 145 Validation in Web API.................................................................................................... 146 Web API Validation Example ........................................................................................ 147 Validation Rules ............................................................................................................. 148 Running the Example...................................................................................................... 149 Controller Code............................................................................................................... 151 Lab 5A ............................................................................................................................ 152 ASP.NET Routing........................................................................................................... 153 Routing in ASP.NET Web API ...................................................................................... 154 Simple Route Example ................................................................................................... 155 Running the Example...................................................................................................... 156 Default Route Map.......................................................................................................... 157 Matching URLs to Route ................................................................................................ 158 Lab 5B............................................................................................................................. 159 Summary ......................................................................................................................... 160

Chapter 6: .NET Clients................................................................................................... 169 Web API Clients ............................................................................................................. 171 HttpClient........................................................................................................................ 172 Initializing HttpClient ..................................................................................................... 173 Issuing a GET Request ................................................................................................... 174 Issuing a POST Request ................................................................................................. 175 Web API Client Library Demo....................................................................................... 176 Adding a House............................................................................................................... 179 Update ............................................................................................................................. 181 Delete .............................................................................................................................. 182 Lab 6 ............................................................................................................................... 183 Summary ......................................................................................................................... 184

Appendix A Learning Resources................................................................................... 191

Unauthorized Reproduction or Distribution Prohibited

Page 9: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC viii All Rights Reserved

Unauthorized Reproduction or Distribution Prohibited

Page 10: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 1 All Rights Reserved

Chapter 1

Introduction to ASP.NET Web API

Unauthorized Reproduction or Distribution Prohibited

Page 11: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 2 All Rights Reserved

Introduction to ASP.NET Web API

Objectives

After completing this unit you will be able to:

Explain what ASP.NET Web API is and why it is useful.

Describe RESTful Web services, which can be created using Web API

Implement HTTP services using Web API with and without using ASP.NET MVC.

Use Fiddler to exercise HTTP requests while developing a Web API service

Unauthorized Reproduction or Distribution Prohibited

Page 12: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 3 All Rights Reserved

ASP.NET Web API

ASP.NET Web API is a framework for building and consuming HTTP services.

It is built into ASP.NET and can be used by both Web Forms and MVC applications, as well as used standalone.

Relying on standard HTTP, Web API facilitates creating services that can reach a wide variety of devices.

Visual Studio 2015 provides templates that facilitate creating Web API services.

Web API does not dictate a particular architectural style, but it is a great platform for implementing RESTful Web services.

Unauthorized Reproduction or Distribution Prohibited

Page 13: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 4 All Rights Reserved

REST

REST (Representational State Transfer) is an architectural style for designing distributed systems.

It is based on the architectural style of the Web.

It is not a protocol, like SOAP is.

Key features of Web architecture include:

Addressable resources specified by a URI (uniform resource identifier)

Standard resource formats such as HTML, XML, JSON, MIME, etc.

A uniform interface (HTTP) for interacting with these resources

Statelessness in interactions between clients and services

A RESTful Web service has a very simple structure.

A request is made through a URI.

A response is a message in a standard format, often XML.

Unauthorized Reproduction or Distribution Prohibited

Page 14: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 5 All Rights Reserved

Representation, State and Transfer

A resource is any entity that can be addressed (by a URI) on the Web.

A representation is typically a document, such as an XML document, that represents the resource.

When it receives a representation, a client application is in a state and will enter a new state when it traverses a hyperlink.

The client application transfers state with each resource representation: “representational state transfer”.

The concept of REST was developed by Roy Fielding1 in his Ph. D. dissertation. Here is Dr. Fielding’s explanation2 of “representation state transfer”:

"Representational State Transfer is intended to evoke an image of how a well-designed Web application behaves: a network of web pages (a virtual state-machine), where the user progresses through an application by selecting links (state transitions), resulting in the next page (representing the next state of the application) being transferred to the user and rendered for their use."

1 Roy Fielding is one of the principal architects of the Web standards of HTTP and URI, and he co-founded the Apache HTTP Server project. 2 Quoted in “Building Web Services the REST Way” by Roger Costello (http://www.xfront.com/REST-Web-Services.html).

Unauthorized Reproduction or Distribution Prohibited

Page 15: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 6 All Rights Reserved

Collections and Elements

A resource is typically a collection or an element in the collection.

A resource is retrieved using the HTTP GET verb.

Collection:

GET http://example.com/resources

Element in collection:

GET http://example.com/resources/101

A new element is created in a collection by using the POST verb.

A representation of the new element is passed in the body of the POST request.

An element in a collection is updated by using the PUT verb.

A representation of the updated element is passed in the body of the PUT request.

An element is removed from a collection by using the DELETE verb.

Unauthorized Reproduction or Distribution Prohibited

Page 16: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 7 All Rights Reserved

Web API Demo

To get started with Web API, let’s create a simple demo.

To illustrate a minimal application, we will start with an empty ASP.NET project and only get the folders and core references for Web API, not using MVC.

1. Create in the Demos directory a new empty ASP.NET Web Application called WebApiDemo.

2. In the second screen, choose the Empty template and add folders and core references for Web API. Click OK.

Unauthorized Reproduction or Distribution Prohibited

Page 17: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 8 All Rights Reserved

Web API Demo (Cont’d)

3. Examine the files and folders in the new project.

4. Delete the folders App_Data, App_Start, Controllers and Models. Delete the file Global.asax.

5. Add a new class DemoController to your new project.

6. Make it derive from ApiController, which will require you to import System.Web.Http.

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; namespace WebApiDemo { public class DemoController : ApiController { } }

Unauthorized Reproduction or Distribution Prohibited

Page 18: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 9 All Rights Reserved

Web API Demo (Cont’d)

7. Declare a private static variable message initialized in a static constructor.

public class DemoController : ApiController { private static string message; static DemoController() { message = "Hello Web API"; } } 8. Implement a public method Get() that returns message.

public string Get() { return message; } 9. Add a Global Application Class. In the Application_Start()

method provide code to add a route to the configuration.

protected void Application_Start(object sender, EventArgs e) { GlobalConfiguration.Configuration.Routes.Add( "Default", new HttpRoute("api/{controller}")); } 10. You will need to import the namespaces System.Web.Http

and System.Web.Http.Routing,

11. Build and run. You will get an HTTP 403 “Forbidden” error.

Unauthorized Reproduction or Distribution Prohibited

Page 19: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 10 All Rights Reserved

Web API Demo (Cont’d)

12. Append api/demo to the URI (not case sensitive), which will look like this (port number varies):

http://localhost:51168/api/demo 13. Click Open in the dialog that comes up. 3

14. The file demo.json will open in Visual Studio. (You could also have clicked Save and examine the file in any editor, including Notepad.)

15. You will now see the message displayed.

3 This demo assumes you are using Internet Explorer. Other browsers will exhibit different behavior. For example, Firefox will return XML rather than JSON. This chapter illustrates IE. You can use another browser, but you will need to allow for the browser’s different behavior.

Unauthorized Reproduction or Distribution Prohibited

Page 20: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 11 All Rights Reserved

Specifying a Start Page

We can make it a little easier to run this example by specifying a start page in the project properties.

Choose Specific Page for Start Action with api/demo as the address.

Now when you run the program you don’t get an error message at first but immediately have useful output.

Unauthorized Reproduction or Distribution Prohibited

Page 21: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 12 All Rights Reserved

Implementing PUT Verb

Web API uses convention to associate controller actions with HTTP verbs.

Get corresponds to GET, Post corresponds to POST and so on.

To indicate that an input parameter in a controller action comes from the body of an HTTP request, use the [FromBody] attribute.

Here is code for a Put() method that will change the message to be delivered.

public void Put([FromBody]string value) { message = value; }

Unauthorized Reproduction or Distribution Prohibited

Page 22: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 13 All Rights Reserved

Using Fiddler

Fiddler is an invaluable tool in working with HTTP.

You can see requests and responses in a variety of formats.

You can compose requests to test your operations.

In particular, you can test POST, PUT and DELETE.

If Fiddler is not already installed on your system, download it from here (choose Fiddler for .NET4):

http://www.telerik.com/download/fiddler

Bring up Fiddler4 and clear clutter from the Edit menu (Edit | Remove | All Session). Run the program again.

4 For convenience you may wish to pin Fiddler to your Start menu.

Unauthorized Reproduction or Distribution Prohibited

Page 23: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 14 All Rights Reserved

Using Fiddler (Cont’d)

In the Web Sessions pane on the left, double-click on the session you wish to examine. Make sure the “Inspectors” tab is selected.

The request is shown on top-right pane.

The response is shown on bottom-right pane.

There are various formats you can choose for viewing request and response.

Here is the response in Raw format, showing both the header and the body of the response.

HTTP/1.1 200 OK Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Server: Microsoft-IIS/10.0 X-AspNet-Version: 4.0.30319 X-SourceFiles: =?UTF-DXE12Y0NzXERlbFdlYkFwapRGVt... X-Powered-By: ASP.NET Date: Tue, 12 Jan 2016 15:13:43 GMT Content-Length: 15 "Hello Web API"

Unauthorized Reproduction or Distribution Prohibited

Page 24: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 15 All Rights Reserved

Composing a Request

We can test the PUT verb by selecting the “Composer” tab in the Request pane.

To get starter HTTP, drag the GET request we used from the Web Sessions pane.

Select the PUT verb from the dropdown.

Add specification of Content-Type to the Request Headers, since there will be a body to a PUT request.

Accept: image/jpeg, application/x-ms-application,.. Accept-Language: en-US Content-Type: application/json User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; ... Accept-Encoding: gzip, deflate Connection: Keep-Alive Host: localhost:52827

In the Request Body, enter a quoted string for the desired message.

"Goodbye"

Unauthorized Reproduction or Distribution Prohibited

Page 25: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 16 All Rights Reserved

Composing a Request (Cont’d)

Click the Execute button. You should receive an HTTP 204 (No Content) response code.

To view the results of the operation, perform a GET again. Drag the original GET into the Composer window. Here is the response in WebView.

Unauthorized Reproduction or Distribution Prohibited

Page 26: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 17 All Rights Reserved

ASP.NET MVC and Web API

ASP.NET provides a useful template for creating HTTP services with Web API.

Notice that folders and core references for both MVC5 and Web API are automatically provided.

We illustrate by creating a simple API to maintain a list of strings.

The completed demo is in MvcStringApi\Step1 in the chapter folder.

5 Don’t worry if you are not familiar with MVC. We use the template that works with MVC as well as Web API for the convenience of being able to look at some sample code that is automatically generated.

Unauthorized Reproduction or Distribution Prohibited

Page 27: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 18 All Rights Reserved

String API Demo

1. Create a new ASP.NET Web Application MvcStringApi using the Web API template.

2. Examine the starter code, beginning with the ValuesController class (in the Controllers folder). Comment out the [Authorize] attribute.

public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody]string value) { } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 public void Delete(int id) { } }

Unauthorized Reproduction or Distribution Prohibited

Page 28: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 19 All Rights Reserved

String API Demo (Cont’d)

3. Build and run, supplying this relative URI as the Specific Page for Start Action in the project properties:

api/values 4. Examine the output in Visual Studio.

5. If you desire, you can perform more experiments using Fiddler.

6. Examine the routing code, which is called from Global.asax.cs.

protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure( WebApiConfig.Register); FilterConfig.RegisterGlobalFilters( GlobalFilters.Filters); RouteConfig.RegisterRoutes( RouteTable.Routes); BundleConfig.RegisterBundles( BundleTable.Bundles); }

Unauthorized Reproduction or Distribution Prohibited

Page 29: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 20 All Rights Reserved

Route Registration

Examine WebApiConfig.cs in the App_Start folder.

public static void Register(HttpConfiguration config) { ... // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional ); }

The default route template has an optional id parameter.

Also, the route is added using the MapHttpRoute() extension method.

Unauthorized Reproduction or Distribution Prohibited

Page 30: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 21 All Rights Reserved

String API Demo (Cont’d)

7. Add a new controller. Use the Web API 2 – Empty controller as the template in the scaffolding options.

8. Call your new controller StringsController.

Unauthorized Reproduction or Distribution Prohibited

Page 31: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 22 All Rights Reserved

String API Demo (Cont’d)

9. Provide code to define a static data member info of type List<string>, initialized in a static constructor.

public class StringsController : ApiController { private static List<string> info = new List<string>(); static StringsController() { info.Add("alpha"); info.Add("beta"); info.Add("gamma"); } } 10. Provide the following code to implement a Get() method.

// GET api/strings public IEnumerable<string> Get() { return info; } 11. Specify api/strings as the Start Action.

12. Build and run. Examine the output in Visual Studio.

13. This completes the demo. You will finish implementing the example in the lab.

Unauthorized Reproduction or Distribution Prohibited

Page 32: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 23 All Rights Reserved

Lab 1

Implementing and Testing a String API

In this lab you will finish the example we started to implement a string API that manages a list of strings. You will be able to retrieve an individual string, add a new string, update a string and delete a string. You will use Fiddler for testing.

Detailed instructions are contained in the Lab 1 write-up at the end of the chapter.

Suggested time: 30 minutes

Unauthorized Reproduction or Distribution Prohibited

Page 33: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 24 All Rights Reserved

Summary

ASP.NET Web API is a framework for building and consuming HTTP services.

REST (Representational State Transfer) is an architectural style for designing distributed systems.

Web API does not dictate a particular architectural style, but it is a great platform for implementing RESTful Web services.

You can implement HTTP services using Web API with and without using ASP.NET MVC.

You can use Fiddler to exercise HTTP requests while developing a Web API service

Unauthorized Reproduction or Distribution Prohibited

Page 34: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 25 All Rights Reserved

Lab 1

Implementing and Testing a String API

Introduction In this lab you will finish the example we started to implement a string API that manages a list of strings. You will be able to retrieve an individual string, add a new string, update a string and delete a string. You will use Fiddler for testing. Suggested Time: 30 minutes Root Directory: C:\OIC\WebApiCs Directories: Labs\Lab1 (do your work here) Chap01\MvcStringApi\Step1 (starter code) Chap01\MvcStringApi\Step2 (solution) Instructions 1. Build and run the starter code. It’s what we created in the demo, except we replaced

the home page (Index.cshtml) with a simple page documenting the operations that can be performed in the browser, and we restored the default Start Action in the project properties.

2. Provide the following code to retrieve an individual string at a specified index position in the list. Make use of the id parameter.

// GET api/strings/5 public string Get(int id) { return info[id]; }

Unauthorized Reproduction or Distribution Prohibited

Page 35: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 26 All Rights Reserved

3. Build and run. Try out the following relative URI:

api/strings/1 4. Examine the output in Visual Studio.

5. Provide the following code to add a new string to the list.

// POST api/strings public void Post([FromBody]string value) { info.Add(value); } 6. Build and run. Start Fiddler. Exercise a GET request, and view the response in

Fiddler in JSON format.

7. Open the Composer and drag the GET request from the Web Sessions window to the Composer’s window. Execute this request and verify you get the same response.

8. Edit the Request Headers to add a Content-Type of application/json.

Accept: image/jpeg, application/x-ms-application, image/gif... Accept-Language: en-US Content-Type: application/json User-Agent: Mozilla/4.0 (compatible; MSIE 7.0;... 9. Change the verb to POST. The window for the Request Body will now be enabled.

Enter the quoted string “delta”.

Unauthorized Reproduction or Distribution Prohibited

Page 36: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 27 All Rights Reserved

10. Execute. Perform a GET request again and examine the response in JSON format.

11. Terminate the application. Provide code to implement PUT.

// PUT api/strings/5 public void Put(int id, [FromBody]string value) { info[id] = value; } 12. Build and run. Use Fiddler to exercise PUT with an index of 1 and a new string

“beetle”.

Unauthorized Reproduction or Distribution Prohibited

Page 37: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 1

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 28 All Rights Reserved

13. Execute a GET request and examine the response in JSON format.

14. Terminate the application. Provide code to implement DELETE.

// DELETE api/strings/5 public void Delete(int id) { info.RemoveAt(id); } 15. Use Fiddler to test deleting the string at index 1. The list should now consist of

“alpha”, “gamma” and “delta”. You’re done!

Unauthorized Reproduction or Distribution Prohibited

Page 38: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 91 All Rights Reserved

Chapter 4

JavaScript Clients

Unauthorized Reproduction or Distribution Prohibited

Page 39: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 92 All Rights Reserved

JavaScript Clients

Objectives

After completing this unit you will be able to:

Use the Document Object Model (DOM) along with JavaScript to dynamically alter the contents of an HTML page.

Describe the jQuery JavaScript library.

Use the JQuery library to send AJAX requests to a server, enabling you to invoke Web API from an HTML page.

Implement JavaScript clients of Web API applications.

Unauthorized Reproduction or Distribution Prohibited

Page 40: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 93 All Rights Reserved

What is DHTML?

DHTML stands for “Dynamic Hypertext Markup Language” or “Dynamic HTML”.

It is not a W3C (World Wide Web Consortium) standard.

It is not a programming language.

DHTML was a marketing term used by Netscape and Microsoft to describe the new technologies their version 4 browsers would support.

DHTML is a combination of technologies:

JavaScript

HTML/XHTML

CSS (Cascading Style Sheets)

DOM (Document Object Model)

These technologies working together allow you to create dynamic Web sites using client-side coding.

Unauthorized Reproduction or Distribution Prohibited

Page 41: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 94 All Rights Reserved

DHTML Components

JavaScript

Allows writing code to control HTML/xHTML elements in the web pages. JavaScript was discussed in Chapter 2.

HTML/XHTML

DHTML pages are written in standard HTML/XHTML.

Starting from HTML 4.0 the presentation of the document is separated from its structure and moved into a style sheet.

Document Object Model (DOM)

The DOM is a W3C standard that specifies an API to locate and manipulate objects in HTML and XML documents within a web page.

The DOM is platform and language independent. It can be used by any programming or script language (for example: Java, JavaScript, and VBScript)

Cascading Style Sheets (CSS)

CSS provides a central document to control appearance, style and layout of objects of multiple Web pages all at once.

Unauthorized Reproduction or Distribution Prohibited

Page 42: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 95 All Rights Reserved

Document Object Model

The rules of XHTML and HTML 5 ensure that the document has a hierarchical structure, enabling the Document Object Model (DOM) to work correctly.

The DOM provides a browser-independent way of representing a document.

The user can access the document via a common set of objects, properties, methods, and events.

The user can also alter the contents of a Web page dynamically using scripts.

There are three base DOM objects.

Node Every node in the document has a Node object

NodeList A NodeList is a list of Node objects

NameNodeMap This map provides access to Node objects by name instead of by index

Unauthorized Reproduction or Distribution Prohibited

Page 43: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 96 All Rights Reserved

Browser Objects

There are also standard objects that are common to all modern browsers.

The window object represents the browser’s window, which contains the HTML page, represented by the document object.

The document object in turn contains the collections (arrays in JavaScript) forms, images and links.

The window object is a global object, so you can access its properties and methods without using its name.

The following two JavaScript statements are equivalent:

alert("Hello there!"); window.alert("Hello there!");

Unauthorized Reproduction or Distribution Prohibited

Page 44: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 97 All Rights Reserved

Accessing DOM Nodes

Main Methods

document.getElementById(id)

Returns a reference to a single Element Node on the page via its ID attribute

// script var element = document.getElementById("txtTag") ... // HTML markup <input id="txtTag" type="text" />

document.getElementsByTagName(tagname)

Returns an array of nodes whose tag name matches the parameter

var elements = document.getElementsByTagName("p");

Unauthorized Reproduction or Distribution Prohibited

Page 45: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 98 All Rights Reserved

Demo: Using the DOM

We’ll illustrate a few key features of the DOM with a simple program that will count the number of HTML elements with a given tag.

Starter code is in the website DomStats in the Demos folder, backed up in DomStats\Step0.

1. Open the website and examine the file Default.html.

<script type="text/javascript"> var count = document.getElementsByTagName("p").length; alert(count + " 'p' elements"); function showcount() { var tag = document.getElementById("txtTag").value; var count = document.getElementsByTagName(tag).length; document.getElementById("result").innerHTML = count + " '" + tag + "' elements"; } </script> ... <input id="btnCount" type="button" value="Count" onclick="showcount()" /> Tag: <input id="txtTag" type="text" value="li" /> <div id="result" /> </body> </html> 2. The method call getElementsByTagName("p") will return an

array of elements with tag <p>, and the length property obtains a count. Build and run (or right-click on Default.html). What do you think will be displayed in the alert box?

Unauthorized Reproduction or Distribution Prohibited

Page 46: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 99 All Rights Reserved

Demo: Using the DOM (Cont’d)

3. Examining the complete file, we see that there are four paragraphs, so we might expect the count to be 4. But this is what is displayed. What do you think the problem is?

4. The problem is that the global JavaScript executes before the document has been fully loaded. One solution is to implement an onload handler, which will not execute until the DOM elements of the page are fully realized. First, specify the handler in the <body> element.

<body onload="domready()"> 5. Second, place what had been the global code in this handler.

<script type="text/javascript"> function domready() { var count = document.getElementsByTagName("p").length; alert(count + " 'p' elements"); }

Unauthorized Reproduction or Distribution Prohibited

Page 47: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 100 All Rights Reserved

Demo: Using the DOM (Cont’d)

6. Build and run. Now we get the expected count of 4 paragraphs.

7. Click the Count button. We’ll see displayed a count of the number of <li> elements.

8. You can experiment with other tags, such as “ul”, “div”, and so on. The completed demo is in DomStats\Step1.

Unauthorized Reproduction or Distribution Prohibited

Page 48: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 101 All Rights Reserved

Using jQuery

We will cover the jQuery Library in more detail after our discussion of Cascading Style Sheets.

As a preview, consider the jQueryStats program, which has exactly the same functionality as DomStats.

We’ve placed the .js code file of the library in a Scripts folder, which is used as an external source for Javacode.

<script type="text/javascript" src="Scripts/jquery-1.10.2.js"></script>

In place of using a handler of onload we use the jQuery ready() method.

An issue with handling onload is that there is a wait not only for the document elements to be loaded but also for external resources, such as images, videos, and so on. This can result in a significant delay before the onload script executes.

We use $() as an alias for the jQuery() function, which has several uses in the jQuery Library.

<script type="text/javascript"> $(document).ready(function () { var count = $("p").length; alert(count + " 'p' elements"); });

The second use of $() provides a much more concise alternative to document.getElementsByTagName().

Unauthorized Reproduction or Distribution Prohibited

Page 49: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 102 All Rights Reserved

Using jQuery (Cont’d)

Our implementation of showcount() is much more concise.

function showcount() { var tag = $("#txtTag").val(); var count = $(tag).length; $("#result").html(count + " '" + tag + "' elements"); }

Our first code example obtained a count of the hardcoded ‘p’ elements. Now we want the user to be able to specify a tag, which is done via an <input> element.

<input id="txtTag" type="text" value="li" />

The $() function can obtain either all elements of a certain kind, or a specific element identified by its id. In the latter case we use a # character as a prefix in the string. The val() function obtains the value of this element.

var tag = $("#txtTag").val();

Finally, we can use the html() function to assign the innerHtml of an element.

$("#result").html(count + " '" + tag + "' elements");

Unauthorized Reproduction or Distribution Prohibited

Page 50: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 103 All Rights Reserved

CSS (Cascading Style Sheets)

Styles can be defined:

Inside a single HTML element

Inside the <head> element of the HTML page

In an external CSS file

It is called Cascading Style Sheets because if there is more than one style specified for elements in the HTML page, the styles will “cascade” down a hierarchy.

The rule of precedence for this hierarchy is as follows, from highest priority to lowest priority:

Inline style (inside an HTML element)

Internal style sheet (inside the <head> tag)

External style sheet

Browser default

External style sheets allow changing the style of multiple HTML documents all at once.

Unauthorized Reproduction or Distribution Prohibited

Page 51: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 104 All Rights Reserved

CSS Syntax

CSS Syntax has three parts: a selector, a property and a value

selector {property: value}

selector is the HTML tag for which style is being defined

property is the attribute to be changed

value is the new value for the attribute

For specifying more than one property, separate them with a semicolon

For grouping selectors, separate them with a comma

Comments begin with “/*” and end with “*/”

p, table, li, h1 /* multiple selectors are defined */ { /* multiple properties are being modified */ font-family: Verdana, Arial, Sans-Serif; margin-left: 10pt; color: Red; }

Unauthorized Reproduction or Distribution Prohibited

Page 52: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 105 All Rights Reserved

Style Sheets

External Style Sheets

Used when the style should be used by multiple pages. All style rules are in an external file saved with a .css extension

Each page must have a link to the style sheet in the head section as shown below:

<head> <link rel="stylesheet" type="text/css" href="StyleSheet1.css"> </head>

Internal style sheets

Used when the style should be applied in a single document.

Internal styles are defined in the head section as shown below:

<head> <style type=”text/css”> p,li,h1 { font-family: Verdana, Arial; color: Red;} body { background-color: Navy;} </style> </head>

Unauthorized Reproduction or Distribution Prohibited

Page 53: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 106 All Rights Reserved

Style Sheets (Cont’d)

Inline Styles

Used when the style should be applied to a single occurrence of an element.

Not recommended, as it mixes presentation with content, very hard to maintain.

Inline Styles are defined in the relevant tag as shown below:

<p style=”color: Blue; font-family: Verdana” This paragraph is written using Verdana </p>

Unauthorized Reproduction or Distribution Prohibited

Page 54: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 107 All Rights Reserved

jQuery Library

jQuery is an open-source1 JavaScript library that is designed to simplify client-side scripting of HTML.

It works with multiple browsers, hiding browser differences from the programmer.

The original release was in 2006, and it is now the most popular JavaScript library.

The official jQuery website is:

http://jquery.com/

Microsoft includes jQuery with Visual Studio 2010 and above.

jQuery supports the following features:

Selecting DOM elements

Modifying DOM elements and the DOM tree

CSS manipulation

Animation

Events

Ajax

Extensibility through plug-ins

1 It is dual-licensed under the MIT License and the GNU General Public License.

Unauthorized Reproduction or Distribution Prohibited

Page 55: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 108 All Rights Reserved

jQuery and Visual Studio

When you create an ASP.NET Web Application or Web Site (either Web Forms or Razor, not an Empty one) using Visual Studio 2015, the project contains a Scripts folder that includes a number of jQuery JavaScript files.

jQuery-1.10.2.js is the source code in a readable format.

jquery-1.10.2.min.js is a “minified” version of the source code with whitespaces eliminated. It is unreadable by a human but is much smaller in size and can be processed efficiently by the browser.

jquery-1.10.2.intellisense.js is a special version whose presence supports Intellisense completion for jQuery within Visual Studio.

Unauthorized Reproduction or Distribution Prohibited

Page 56: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 109 All Rights Reserved

Selectors

jQuery enables you to work with DOM elements.

The first thing you need to do is select the elements to which you will apply some operation.

You select elements by means of a selector.

jQuery selectors include all the common CSS selectors and many more.

Here are some examples of common selectors:

Selector Result

(blank) none

* all

p all <p> elements

p input all <input> elements nested within a <p>

#identifer the single element with specified id

Unauthorized Reproduction or Distribution Prohibited

Page 57: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 110 All Rights Reserved

jQuery Wrapper

You obtain a collection of elements by the jQuery() function.

jQuery(selector)

More concisely, you may use the $() alias.

$(selector)

The $() function returns a JavaScript object, which is an array of DOM elements with augmented pre-defined methods.

The object that is returned is called a wrapper because it wraps the selected elements with augmented functionality. These added methods are sometimes called wrapper methods.

Many wrapper methods have the characteristic that when they are done with their action (such as hide or show), they return the same set of elements.

The new set of elements is ready for another action.

This concatenation of methods is called chaining.

$(selector).hide().size()

Unauthorized Reproduction or Distribution Prohibited

Page 58: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 111 All Rights Reserved

Selector and Wrapper Example

We illustrate working with selectors and wrappers.

See jQueryWrapper in the chapter folder.

Clicking the Count button shows that there are 9 <li> elements.

Unauthorized Reproduction or Distribution Prohibited

Page 59: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 112 All Rights Reserved

Example Script

<script type="text/javascript" src="Scripts/jquery-1.10.2.js"></script> <script type="text/javascript"> function count() { var selector = $('#txtSel').val(); alert($(selector).size()); } function hideElements() { var selector = $('#txtSel').val(); alert( $(selector).hide().size() + " elements hidden"); } function showElements() { var selector = $('#txtSel').val(); $(selector).show(); } </script>

First consider the count() function.

Select the single element whose id is ‘txtSel’ and determine the value by using the val() method.

var selector = $('#txtSel').val();

Determine how many elements are selected by using the size() method. (Since the object is a JavaScript array, you could also determine the count from the length property.)

$(selector).size()

Unauthorized Reproduction or Distribution Prohibited

Page 60: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 113 All Rights Reserved

Example Script (Cont’d)

In the hideElements() function, we find the selector in the same way.

var selector = $('#txtSel').val();

We find the wrapped set of elements:

$(selector)

We apply the hide() method to each element in the set, obtaining another wrapped set of the same size.

$(selector).hide()

We determine the size by applying the size() method.

$(selector).hide().size()

This is an example of chaining.

You can experiment using various selectors.

Unauthorized Reproduction or Distribution Prohibited

Page 61: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 114 All Rights Reserved

jQuery Ajax Methods

The jQuery library provides a complete set of methods for using Ajax from an HTML page.

See documentation: https://api.jquery.com/category/ajax/.

We will illustrate use of a few methods.

Unauthorized Reproduction or Distribution Prohibited

Page 62: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 115 All Rights Reserved

Shorthand Methods

The easiest way to invoke Ajax with jQuery is to use shorthand methods.

These enable you to invoke common Ajax operations with less code.

We’ll illustrate the use of jQuery.getJSON().

Unauthorized Reproduction or Distribution Prohibited

Page 63: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 116 All Rights Reserved

jQueryHouses Example

See jQueryHouses in the chapter folder.

The HTML page index.html provides a user interface to show a list of houses and to find a single house, using the Web API application ApiHouses that we previously developed.

Unauthorized Reproduction or Distribution Prohibited

Page 64: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 117 All Rights Reserved

Using getJSON()

Here is the JavaScript code that will run after the document has been loaded.

var uri = 'api/houses'; $(document).ready(function () { // Send an AJAX request $.getJSON(uri) .done(function (data) { // On success, 'data' contains a list of houses. $.each(data, function (key, item) { // Add a list item for the product. $('<li>', { text: formatItem(item) }).appendTo($('#houses')); }); }); });

formatItem() is a helper method to format a House object as a string to be displayed in the list.

function formatItem(item) { return '[' + item.Id + '] ' + item.City + ': $' + item.Price; }

Unauthorized Reproduction or Distribution Prohibited

Page 65: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 118 All Rights Reserved

Handling Errors

If the ID submitted by the user is not found, an error message is displayed.

Run the example without debugging. (When debugging, there will be a break when an exception is thrown.)

function find() { var id = $('#houseId').val(); $.getJSON(uri + '/' + id) .done(function (data) { $('#house').text(formatItem(data)); }) .fail(function (jqXHR, textStatus, err) { $('#house').text('Error: ' + err); }); }

Unauthorized Reproduction or Distribution Prohibited

Page 66: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 119 All Rights Reserved

Low Level Interface

The shorthand methods work great for invoking HTTP GET, but for POST and other methods you will need to use the low level interface.

The principal method of the low-level interface is jQuery.Ajax().

It is illustrated in the HouseDemo example.

Here is the low-level code to get a single house, which we did more easily before using a shorthand method.

function find() { var id = $('#houseId').val(); $.ajax({ url: 'api/houses' + '/' + id, type: 'GET', dataType: 'json', success: function (data) { $('#house').text(formatItem(data)); }, error: function (jqXHR, textStatus, err) { $('#house').text('Error: ' + err); } }); }

Note use of the type parameter to specify the HTTP method GET (we could have left it out, as it is the default).

We can also specify other HTTP methods, such as POST, PUT, and DELETE.

Unauthorized Reproduction or Distribution Prohibited

Page 67: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 120 All Rights Reserved

HouseDemo Example

The HouseDemo example illustrates invoking GET, POST, PUT and DELETE from JavaScript.

The example starts in HouseDemo\Step1 in the chapter folder, and will be completed in the lab.

New houses are not shown in the list until you click Refresh.

Unauthorized Reproduction or Distribution Prohibited

Page 68: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 121 All Rights Reserved

Invoking POST

function add() { var house = { Id: 0, City: $('#txtCity').val(), Price: $('#txtPrice').val() }; $.ajax({ url: 'api/houses', type: 'POST', data: JSON.stringify(house), contentType: "application/json;charset=utf-8", success: function (data) { alert(JSON.stringify(data)); }, error: function (jqXHR, textStatus, err) { alert(jqXHR + '\n' + textStatus + '\n' + err); } }); }

With POST we have to specify the data we are sending as well as the Content-Type.

The helper method JSON.stringify() makes it easy to convert a JavaScript object into a string to be placed in the HTTP request header.

We obtain data for the JavaScript object from text boxes on the HTML form. Note that the Id is assigned on the server.

Unauthorized Reproduction or Distribution Prohibited

Page 69: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 122 All Rights Reserved

Lab 4

Ajax Requests for PUT and DELETE

In this lab you will study sample JavaScript code using jQuery to send Ajax requests to a Web API application. You will then enhance the example to illustrate sending requests for PUT and DELETE operations.

Detailed instructions are contained in the Lab 4 write-up at the end of the chapter.

Suggested time: 30 minutes

Unauthorized Reproduction or Distribution Prohibited

Page 70: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 123 All Rights Reserved

Summary

With the Document Object Model (DOM) along with JavaScript you can dynamically alter the contents of an HTML page.

jQuery is an open-source JavaScript library that simplifies client-side scripting of HTML.

You can use the jQuery library to send Ajax requests to a server, enabling you to invoke Web API from an HTML page.

Unauthorized Reproduction or Distribution Prohibited

Page 71: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 124 All Rights Reserved

Lab 4

Ajax Requests for PUT and DELETE

Introduction In this lab you will study sample JavaScript code using jQuery to send Ajax requests to a Web API application. You will then enhance the example to illustrate sending requests for PUT and DELETE operations. Suggested Time: 30 minutes Root Directory: C:\OIC\WebApiCs Directories: Labs\Lab4 (do your work here) Chap04\HouseDemo\Step1 (starting code) Chap04\HouseDemo\Step2 (solution) Instructions 1. Examine the code of the starter program. The handler for $(document).ready sends an

Ajax request using the $.getJSON() shortcut method. The code for refresh() implements the same functionality (adding an error handler) using the low-level $.ajax() method. The code for find() also uses $.ajax(). Finally, the add() function uses $.ajax() to send a POST request. Also, examine the project properties. Observe that index.html has been set as the specific start page.

2. Build and run the starter program without debugging. The Find, Refresh, and Add buttons all work. Exercise them by adding a couple of houses, doing a refresh, and finding a house on the list and searching for a house not on the list.

3. Add a JavaScript function updateHouse() that for now simply displays an alert message.

function updateHouse() { alert("updateHouse()"); } 4. Modify the markup for the Update button so that onclick points to the new function.

<input type="button" value="Update" onclick="updateHouse();" />

Unauthorized Reproduction or Distribution Prohibited

Page 72: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 125 All Rights Reserved

5. Build and run. If you don’t see your changes having effect, view the source in the browser. If it is an old page, click the browser’s refresh button.

6. Add code to updateHouse() to obtain the value of the Id submitted by the user. Show this in the call to alert().

function updateHouse() { var id = $('#houseId').val() alert("id = " + id); } 7. Add code to initialize a House object with this id and values of City and Price submitted

by the user. Show this house in the alert, making use of the formatItem() helper method.

function updateHouse() { var id = $('#houseId').val() var house = { Id: id, City: $('#txtCity').val(), Price: $('#txtPrice').val() }; alert(formatItem(house)); } 8. Add code to issue a PUT Ajax request, sending the house data in the request body. Model

your code on that for POST. Call refresh() if the house has been successfully updated.

$.ajax({ url: 'api/houses/' + id, type: 'PUT', contentType: "application/json;charset=utf-8", data: JSON.stringify(house), success: function (data) { alert('House upadated'); refresh(); }, error: function (jqXHR, textStatus, err) { $('#house').text('Error: ' + err); } }); 9. Build and run, testing the update functionality.

10. Finally, implement a handler for the Delete button.

function deleteHouse() { var id = $('#houseId').val(); $.ajax({ url: 'api/houses/' + id, type: 'DELETE', contentType: "application/json;charset=utf-8", success: function (data) { alert('House deleted'); refresh();

Unauthorized Reproduction or Distribution Prohibited

Page 73: or COPY ASP.NET W API E U C# and Elements ... DHTML Components ... Document Object Model ...

EVALUATION COPY

WebApiCs Chapter 4

Rev. 4.7 Copyright © 2016 Object Innovations Enterprises, LLC 126 All Rights Reserved

}, error: function (jqXHR, textStatus, err) { $('#house').text('Error: ' + err); } }); } 11. Build and exercise thoroughly. You are now at Step 2.

Unauthorized Reproduction or Distribution Prohibited