DPS907 WSA500 Assignment 1

Creating a simple web service for one entity.

Read/skim all of this document before you begin work.

Note: If you need a refresher about modern AutoMapper use, read this document.

 

Due date

Monday, September 11, 2017, at 11:00pm ET

Grade value: 5% of your final course grade

If you wish to submit the assignment before the due date and time, you can do that.

 

Objective(s)

Create a simple web service that works with one entity collection.

 

Introduction to the problem to be solved

We need a simple web service that will deliver data about smartphones. The web service will support fetch all, fetch one, and add new scenarios. Data will be persisted in a standard database store.

 

Specifications overview and work plan

Here’s a brief list of specifications that you must implement:

  • Follows best practices
  • Implements the recommended system design guidance
  • Customized appearance on the landing web page
  • Uses Entity Framework and Code First technology
  • Supports HTTP GET, for get all and get one use cases
  • Supports HTTP POST, for the add new use case
  • Includes a Fiddler log file that shows complete coverage of tests

 

During the class/session, your professor will help you get started and make progress on this assignment.

Every week, in the computer-lab class/session, your teacher will record a grade when you complete a specific small portion of the assignment. We call this “in-class grading“.

The in-class grading will be announced in-class by your professor.

 

Review some ASP.NET MVC web app notes

Whether you have been away from ASP.NET MVC web app programming for one or two academic terms, you should review some notes, to ensure that you use best practices and efficient design and coding techniques.

The January 18 2017 web app notes covers these topics:

  • Persistent data storage, in a database
  • Facade service, with Entity Framework
  • Design model classes
  • Manager class, for app and business logic
  • View model classes – which we refer to as “resource model classes” in web service apps
  • The AutoMapper tool for easy conversion between design model and resource model objects

The March 8 2017 web app notes covers these topics:

  • Understanding a project template that includes authentication
  • Defining and creating a new persistent store

 

Reminder / refresher about app design and architecture

If you have been away from ASP.NET MVC web apps for awhile, you may need a reminder, or refresher, on some of the app design and architecture features.

 

Controller design

Each controller has a private field that declares a new instance of the Manager class. For example, line 12 of this code example.

private Manager m = new Manager();

 

The purpose of the Manager class is to provide common operations for the app’s data. All controllers will use the manager object. For example, in the code example linked above, the controller will call a manager method to fetch all customers:

var c = m.CustomerGetAll();

 

Manager design

The manager has a private field that declares a new instance of the data context. For example, line 14 of this code example:

// In this Assignment 1 app...
private ApplicationDbContext ds = new ApplicationDbContext();
// In an app that does NOT use "individual user accounts" authentication...
private DataContext ds = new DataContext();

 

The purpose of the data context class is to be the gateway or interface to the app’s persistent store. In our apps, Entity Framework classes work with the Microsoft SQL Server relational database management system.

The data context has properties for each entity collection in the data store, exposed as properties. Each entity collection exposes a large number of methods that enable us to do common data operations – fetch, add, edit, order/sort, filter, etc. For example, line 37 of the code example fetches and returns a collection of all customer objects; this method was called by the controller method. AutoMapper transforms the fetched design model objects to a collection of resource/view model objects.

return Mapper.Map<IEnumerable<CustomerBase>>(ds.Customers);

 

Data context design

The data context has DbSet<TEntity> properties for each entity collection in the data store.

In the data context class, after the constructor, add properties for each, as you will see in lines 29 to 31 in this code example:

public DbSet<Country> Countries { get; set; }
public DbSet<Manufacturer> Manufacturers { get; set; }
public DbSet<Vehicle> Vehicles { get; set; }

 

Summary

In summary, the call chain looks like this:

1. Incoming request (from a browser to a web app, or from an HTTP client to a web service)

2. Controller method begins execution. Controller has a reference to the manager object.

3. Controller calls the manager object. It may pass data to it. It may expect data to be returned.

4. Manager method begins execution. Manager has a reference to the data context. Manager uses AutoMapper to transform resource/view model objects to-and-from design model objects.

5. Manager calls methods on the entity collections in the data context. It may pass data. It may expect return data. Manager does not leak design model details to controllers.

6. Data context is configured with DbSet<TEntity> properties for each entity that it is working with. The data context is the Entity Framework gateway object to the data store, which is typically SQL Server in our situation.

 

Getting started

Create a new web service, named Assignment1:

  • Specify the Web API project type
  • Do NOT include “application insights”
  • Use “individual user accounts” authentication
  • Do NOT “host in the cloud”
  • No “unit tests”

Warning: Your professor believes that the best way to work through any assignment is to do it incrementally. Get one thing working correctly, before moving on to the next. Test each part.

This project will include the components needed to use a database, and Entity Framework Code First technology:

  • Its data context class is ApplicationDbContext, in the IdentityModels.cs source code file
  • You must add your own DbSet<TEntity> properties to this class

Update the project’s packages. In the NuGet package manager console, run the command “update-package”.

 

Add AutoMapper

Using the NuGet Package Manager, install the latest version of AutoMapper.

 

Add the source code files that define the app’s structure

Add the source code files that define the app’s structure. As suggested above, build/compile after you add new items and perform edits.

In the Models folder, add a source code file to hold your design model classes, named DesignModelClasses.cs.

In the Controllers folder, add a source code file to hold your data operations management methods, named Manager.cs.

In the Controllers folder, add a source code file to hold your resource model (i.e. view model) classes. Its name will be Smartphone_vm.cs.

In the Controllers folder, add a controller. Its type will be “Web API 2 Controller with read/write actions”. Its name will be SmartphonesController.cs.

 

Doing the work

Now that you have the app’s structure configured, you can circle back and do the programming work.

 

Design model classes

In the DesignModelClasses.cs source code file, create an entity class to describe a smartphone. The class name should be “Smartphone”. Write five or more properties (your choice, but use common sense). Use four or more different data types. For example:

  • Id (identifier)
  • Manufacturer name
  • Smartphone model name
  • Release date (date & time)
  • Screen size (double)
  • Sell price (integer)

Remember to use a default constructor whenever you have a DateTime property in a class. And, make sure that you use data annotations.

 

Data context and data storage (aka facade services)

The project will include an IdentityModels.cs source code file. You will remember that from your web apps course.

The ApplicationDbContext class is the app’s data context class. (It ultimately inherits from DbContext.)

Add a DbSet<TEntity> property for the app’s entity class.

 

Resource models (aka view models)

You know about “view models” from your web apps course. In web services, these classes are most often called “resource models“. They’re the same.

Earlier, you created a source code file named Smartphone_vm.cs. It will hold resource model classes for these use cases:

  • Add (i.e. SmartphoneAdd)
  • Base (i.e. SmartphoneBase)

Write these now.

Obviously, we need program code to map between design model and resource model classes. We will continue to use AutoMapper. We will add the AutoMapper initialization and map definition code to the Manager class, next.

 

Data operations management (the Manager class)

In the Controllers folder, the Manager.cs source code file holds the Manager class. As you remember from your web apps course, its purpose is to contain the methods that perform data service operations. Controllers will call into this manager class.

Like all manager classes, it needs a field for the facade reference (the data context).

 
private ApplicationDbContext ds = new ApplicationDbContext(); 

 

Next, AutoMapper fields are needed.

MapperConfiguration config;
public IMapper mapper;

 

Next, add a default constructor. Add code to configure AutoMapper. You will need two maps:

  1. One from design model to resource model, and
  2. Another to enable the “add” use case (resource model to design model).

 

// Configure the AutoMapper components
config = new MapperConfiguration(cfg =>
{
  // Define the mappings below, for example...
  // cfg.CreateMap<SourceType, DestinationType>();
  // cfg.CreateMap<Employee, EmployeeBase>();

  // Object mapper definitions (add them on the next few lines...)
});

mapper = config.CreateMapper();

 

Then, for this assignment, we will need methods for the following:

  • Fetch all objects in a collection (should they be ordered?)
  • Fetch a specific object based on its unique identifier (what happens if not found?)
  • Add a new object to the collection

Remember that all Manager class methods must accept and deliver resource model objects or collections. The Manager class must not leak design model class objects or collections.

The Manager class will also need using directives for the app’s Models namespace and the AutoMapper namespace.

 

Controller programming

The SmartphoneController class, like all controller classes, needs a field for the manager class reference.

Then, three of its methods need to be implemented:

  • Get all
  • Get one
  • Add new

You can comment out, or delete,  the Put and Delete methods; we will not use them in this assignment.

As a reminder (because it may have been awhile since you worked in web apps), here is pseudocode for the three methods.

 

Get all

Call the manager’s “get all” method
Return an Ok() result

 

Get one

Call the manager’s “get one” method
Test the result…
If null, return a NotFound() result
Otherwise, return an Ok() result

 

Add new

Ensure that there is an object in the entity body, if not, return a BadRequest() result
Ensure that a passed-in object is valid (using model state validation), if not, return a BadRequest() result
Attempt to add the new item
Test the result…
If the attempt was unsuccessful, return a BadRequest() result
Otherwise…
Construct a URI that will point to the new resource
Return the URI and the new object in a Created() result

 

Testing your work

Use Fiddler.

Ensure that it has been configured to save the message bodies in requests and responses. (A default installation does not do this.) If you are using a College computer, this should have been configured, but check anyway. If you installed Fiddler on your own computer, follow the instructions on this document.

Test all scenarios (use cases).

When testing the “add new” scenario, remember:

  • The HTTP method is POST
  • The target is the collection URI
  • The request needs a Content-Type header
  • The message body needs a JSON object that matches the “SmartphoneAdd” resource model

The date (i.e. DateTime type) property needs some explanation. The JSON serializer uses the ISO 8601 standard for dates and times. For example the due date and time of this assignment is expressed as a string, “2016-09-14T23:00:00”. In other words the date is in year-month-day format. Then there’s a letter “T”. Finally, the time is in hour-minute-second format.

Use that format when you enter the string for the date in your “add new” requests.

 

Saving – “exporting” – your tests

On the left side list of requests, you can delete items that you do not want included in the export.

When you’re ready to save, choose File > Export Sessions > All Sessions…

The export format will be “HTTPArchive v1.2”. Click the Next button to choose a save location (your project’s root, in the same folder level as the “packages” and “assign1” folder) and specify a filename. Name the file by using the project name (e.g. “assignment1.har”).

(You can test whether the export was successful. How? First, close then re-open Fiddler. Choose File > Import Sessions. Select “HTTPArchive” as the import format. Navigate to the folder that holds “assignment1.har”, and select it. Finally, browse through the request-response sessions.)

 

Reminder about academic honesty

You must comply with the College’s academic honesty policy.

Although you may interact and collaborate with others, you must submit your own work.

 

Submitting your work

Here’s how to submit your work, before the due date and time:

1. Locate the folder that holds your solution files. In Solution Explorer, right-click the “Solution” item, and choose “Open Folder in File Explorer”. It has three  (or more) items: a Visual Studio Solution file, a folder that has your project’s source code, and a “packages” folder. Go UP one level.

2. Make a copy of the folder. (You will be uploading a zipped version of the copy.)

3. Remove the “packages” folder from the copied folder; also, remove the “bin” and “obj” folders.

4. Compress/zip the copied folder. The zip file SHOULD be about 2MB or less in size. If it isn’t, you haven’t followed the instructions properly.

5. Login to My.Seneca/Blackboard. Open the Web Services course area. Click the “Assignments” link on the left-side navigator. Follow the link for this assignment. Submit/upload your zip file. The page will accept three submissions, so if you upload, then decide to fix something and upload again, you can do so.

 

 

 

 

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

Advertisements
%d bloggers like this: