DPS907 WSA500 Tests and Sample Answers

Sample answers for the weekly tests for the Fall 2017 term.

The most recent test is at the top of the page.

When your test is marked, we are looking for an answer that captures the essence of the example answers (in red, below). Your answer does not necessarily have to be exactly the same, and part marks are possible. You should strive to improve your explanations, as that will improve your academic and career prospects.

Most tests are worth 4% of your final course grade. Typically, there are about 7 questions on the test, and you will give answers to any 4 questions.

 

Test 5, October 5

1. Briefly explain the meaning of this statement: Modern web APIs must be hypermedia-driven.

Response includes data and links that enable the requestor to determine what to do next.
This is the plain-language way of saying that “hypermedia is the engine of application state”.

2. (WSA) Scenario: You are on a development team, creating a web service that will be used by the public, and by developers of other apps. Briefly explain whether a hypermedia-driven design should be used, or not.

Yes, should be used. For public consumption and use. Deliver information about resource and state changes in-band with the results.

2. (DPS) Roy Fielding published a document (blog post) titled “REST APIs must be hypertext-driven”. Briefly discuss any one of his rules, and why it was memorable to you.

Should not depend on a single communications protocol.
Should not change the selected communications protocol.
Should fully describe how to change application state, without out-of-band info.
Must not rely on fixed resource names, and instead use link relations.
Communicate only standardized media types and relations.
Can enter API with no knowledge other than root/entry-point URI, link relations used from there.

3. (DPS) Scenario: You are on a development team, creating a web service that will be used only by apps that are internal to the organization, and not by the public. Briefly explain whether a hypermedia-driven design should be used, or not.

No, does not have be used. In line with Ben Morris article. Some arguments included:
Complex to implement.
Clients/requestors will likely not use it, will use out-of-band knowledge instead.
Bloated response, no consensus on hypermedia representation format.
Does not do a good job at telling you about the context of the data and actions.

3. (WSA) and 4. (DPS) What is the purpose of the HTTP OPTIONS method? Why must we handle it in our app?

From RFC 7231:
The OPTIONS method requests information about the communication options available for the target resource… This method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action.

Other than the last sentence (above), it serves as documentation.

4. (WSA) and 5. (DPS) Briefly discuss any two “documentation” techniques that a web service programmer can implement, to make it easier for users/requestors.

Link relations – add link relations to objects or collections, to create a “hypermedia representation”.
Initial URI – add and configure a “root” controller, at the app’s entry URI, to notify users/requestors (using link relations) what resources are available, and for what purpose.
Help Page – activate and configure the “help page”, and use XML code comments to provide good descriptions.
“Add new” template – in certain responses (e.g. “get all”), notify users/requestors what data must be provided in an “add new” scenario.

6. (WSA) Briefly describe how to implement this Roy Fielding REST rule: Can enter and use the web API with no knowledge other than root/entry-point URI.

Create “Root” controller
Edit the default route in the WebApiConfig class
Manually code/add the link relations that will be visible/available

6. (DPS) Scenario: A “get one” controller method is returning a result, with link relations. You would like to notify the user/requestor that they can use two “commands” on the current resource URI. How would you do this? If it helps your answer, you can use sample code and comments.

Manually create and add two new links to the object’s “Links” collection. For example:
o.Links.Add(new Link { Href = “api/blurb/{id}/dosomething”, Rel = “command”, Method = “PUT” });

7. The topic is XML Documentation comments (triple slash). Briefly name and explain the two most visible benefits that this feature provides.

Two main benefits:
1. Web API Help Page
2. IntelliSense

 

Test 4, September 28

1. There are at least two important rules that you must follow when working with media items. Briefly state them.

Do not package bytes inside another container. Deliver the media as is.
When storing, must store bytes AND the internet media type name.

2. (WSA) Assume that you are writing a controller method that accepts a media item for the recently-learned “object with one media item” scenario. Name the method’s parameters, and their purpose.

Identifier, for the object.
Byte array, for the media item data.

2. (DPS) In the code examples, the books controller has a SetPhoto method. Is this an example of the command pattern? Explain.

Yes.
Uses HTTP PUT.
Also is idempotent. Can run it repeatedly with no ill effect.

3. Assume that a client (smartphone) app wants to use a web service that delivers media items. For a specific entity object, you want both data and a media item. How do you request what you need?

This must be done with two separate requests.
One request for the object’s data.
The other request for the media item.

4. Briefly explain how a media type formatter class works, by discussing its methods. (The explanation should not be too general, and not too technical. In other words, no syntax.)

The constructor declares the internet media types that it will handle.
A Reader transforms data coming in from a request.
A Writer transforms data that’s returned in a response.

5. (WSA) A custom media type formatter is initialized somewhere. Name the source code file, and/or class, and/or method that has the initialization code.

In WebApiConfig.cs, in the WebApiConfig class, in the Register method.

5. (DPS) Draw a simple diagram that shows the location of a media type formatter relative to other components in the message-handling pipeline.

See the diagrams from the class notes; here’s a description for an incoming request:
1. Router selects the controller and action (method)
2. Model binding happens, media formatter is used to unpack data
3. Method begins execution
The method return value goes through the media formatter too.

6. (WSA) Write a brief definition of content negotiation.

The process used to determine the media type of the requested representation.
The requestor submits a preferred media type (or a list), and the server attempts to comply.

6. (DPS) In which code file / class is content negotiation done? In the controller, or the manager? Explain why.

Done in the controller.
Closest to the requestor and use case.
Response can be shaped to meet the needs of the use case.

7. In the code examples, the Book with media info resource model classes included a PhotoLength integer property. Its value does not appear to be explicitly set anywhere. How does it get its value?

In BookWithMediaInfo, the Photo property is an object with a Length property.
AutoMapper flattening fills in this value. Auto-magically.

 

Test 3, September 21

1. Reach-back question. Assume that you are working with an object that has a to-one association with another object. You could either add a reference to the other object in full, or you could add one or more references to properties in the other object. Briefly discuss the benefit of each approach.

Other object in full: Includes all the properties available for rendering or manipulation.
One or more properties: Can focus on the properties that add value to the use case, ignoring the others.

2. Question about the manager class: Assume that you want to fetch one object, with an associated collection. What is your coding strategy? If you wish, you can write a line of code to supplement your answer.

Use the Include() method, with the name of the navigation property as the argument. For example:
var fetchedObject = ds.Suppliers.Include(“Products”).SingleOrDefault(p => p.Id == id);

3. The topic is errors and exception-handling. Briefly define the meaning of any two of the following HTTP status codes: 400, 401, 403, 415, 500, 501

400 Bad request, syntax is not correct
401 Unauthorized, request must include authentication data
403 Forbidden, authentication was successful, but request fails authorization
415 Unsupported media type, entity body format
500 Internal server error, unhandled exception at runtime
501 Not implemented, method is not implemented

4. A manager method can return data, or null. Null is often used to indicate there’s no data, or an error. Briefly explain how a controller could interpret a null return from a controller method. To clarify, in a controller, does null always indicate no data? An error? Both? Neither?

It depends.
Scenario 1 – call manager’s get one, which is not found. Controller must interpret that as “not found”, and return NotFound().
Scenario 2 – call manager’s edit existing, which returns null. Controller must interpret that as a problem with the data in the request. Could return BadRequest() (or StatusCode()).

5. Name and briefly describe two examples of real-life entities that can be modeled with an association that we are covering this week. (For example, many-to-many, one-to-one, self-referencing to-one and to-many.) We already know and use the Chinook entities and associations, so do not name any of those as your answer.

Self-referencing to-many: Person, a collection of Children.
Self-referencing to-one: Person, a Mother or Father.
Many-to-many: School of ICT academic Program and Course
One-to-one: User Account and preferred Credit Card

6. Briefly discuss the reasons for using the command pattern, as you learned in this week’s topic notes. Assume that you are attempting to explain “why” to use this pattern to your team.

Higher level of abstraction, higher than thinking about atomic data tasks
Do a task that does not naturally map to a CRUD task on a resource
Encapsulate functionality in a container

7. Briefly discuss the technical design features of the command pattern, as you learned in this week’s topic notes. Assume that you are attempting to show your team “how” to use this pattern.

Design a resource model for the data needed by the use case
Write a controller method, for HTTP PUT, a void return type, and a custom route
Write a manager method that does the work
Also, try to design the command to be idempotent

 

Test 2, September 14

1. The request-handling pipeline concept is important for any web app, and especially for a web service. Using a numbered list, or a simple diagram, name and/or describe the notable components in the pipeline.

Incoming request…
1. Operating system listener on TCP port 80 and 443
2. Web server 
3. ASP.NET runtime, with front controller, router, and deserializer (model binder)
4. Request-handling controller
5. Typically, manager and data persistence
6. Response serializer (media formatter)

2. Consider this scenario: A web service controller method returns a result that has an associated object or collection. Is the coding any different from a result that does not include an associated object or collection? Explain.

No.
The response serializer (media formatter) simply accepts and works on the object graph, without regard to its shape (however, the object graph must not contain any circular references).

3. Assume that you are writing the classes for two associated entities. It is possible to configure a navigation property as “required”. Why would you do that? What effect does it have on your coding task, and/or on the stored object?

Why? To prevent an object that depends upon another from being created if you do not have a reference to the associated object. 
Or, when you must have a reference to the “required” associated object. 
For example, adding an object on the “to many” side needs a reference to the “to one” object. 
Effect? In the data store, the foreign key property constraint gets configured by the EF façade and manager.

4. Explain or discuss the role of attribute routing for controller methods; can use/contrast the code example’s methods that return results with/without associated object(s).

Typically used to add features to a controller’s resource URIs. 
Base URI often designed to return a base or typical representation.
Additional URI often used to return an enhanced version of the base or typical representation.

5. A controller’s get all or get one method usually returns the Ok() extension method. However, an add new method returns the Created() extension method. Why? What benefit or value does it provide?

The response pipeline configures the HTTP status code to 201.
And it configures a Location response header.
The requestor now has a richer response, with helpful metadata.

6. Assume you are writing a design model class that has a to-one navigation property. What code is added for that nav property, and why? Be as specific and correct as you can.

Data annotation, [Required].
Property type is the associated class, and name is singular.

7. Assume that you are writing a resource model class that has a to-many navigation property. What code is added for that nav property, and why? Be as specific and correct as you can.

Property type is an IEnumerable<T> of the associated class, and name is plural.
No data annotation, but the collection is initialized in the default constructor.

 

Test 1, September 7

1. Briefly explain the value proposition (i.e. what makes it attractive) of the IHttpActionResult type, when compared to simply returning an object or collection.

The request-handling pipeline configures the response with the correct HTTP status code.
Or, coding consistency. The helper methods (OK, NotFound, etc.) are more expressive.

2. Briefly describe how request routing works in Web API. (Or put another way, how does ASP.NET Web API route HTTP requests to controllers?)

App domain uses the front controller pattern to receive the request.
Front controller inspects the URI, and compares it to routes defined by the app (and also by convention in the runtime).
Then, it attempts to locate a matching route, based on reflection over all the controller types found in the app.
The matching controller is initialized, and the matching method is called with the request’s data.

3. Scenario: A user agent requests (GET) a collection resource. There are no items in the collection. What is the correct response, and why?

HTTP 200 OK
The data package will be an empty container.
The absence of objects in the collection does not imply an error condition. It simply means that the collection resource is empty.

4. Write a brief and clear definition any two of the following:
Web service, Request, Response, Resource, Representation, Internet Media Type, JSON, XML.

See the “terminology” section of the notes.

5. Briefly describe the purpose of content negotiation, and briefly describe how it works.

The process of requesting the desired representation for a response, in situations where there are multiple representations available.
The request includes an “Accept” header.
If the requested representation is available, the server prepares and sends the response.
The response includes a “Content-Type” header.

6. Briefly explain the difference (or relationship) between resource and representation.

Resource is a digital asset.
Representation is a digital asset that is formatted as a specific internet media type.

7. Briefly explain the purpose of HTTP response status codes 200, 201, and 204.

200 – successful request, almost always with an entity body. Most often used with GET.
201 – resource was successfully created, includes an entity body. Most often used with POST.
204 – successful request (but no entity body)

 

 

 

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

Advertisements
%d bloggers like this: