Assignment 2 - Retail store with Entity Framework II
This week you will trap errors from duplicate product-category assignments, add authentication for the admin
pages, and add a front end to display your products.
To access the admin page on the sample site username is firstname.lastname@example.org and
password is Admin.1
- retail/admin - Trapping exceptions: the interface for assigning products to categories allows users
to select existing product-categories. The ProductCategory table contains a
constraint which throws an exception on duplicates. The user should never see yellow screens.
In this step you will
trap the exceptions and give the user an appropriate message.
- Throw the exception and note the line number where it occurred. Wrap the
offending statement and the existing return redirect statement inside
the try part of a try-catch
In the "catch" add an appropriate message about duplicate entries to ViewBag. Add code to
the view to display the ViewBag message.
Authentication: the admin pages need to be protected by authentication
so that unauthorized users cannot access it. Visual Studio's default
MVC site includes "ASP.NET Identity" authentication.
To confirm this in your project check your controllers folder
for the "Account" and "Manage" controllers.
Views folder will contain the corresponding views. If your project was not created with Identity authentication (see image on right) it can be added to an existing project, although it might be easier to create a new project and copy over your existing code.
- In a public web site it is important to use HTTPS throughout an authenticated session to prevent
session hijacking. We will not be adding HTTPS to this assignment because it requires several configuration changes within Visual Studio. If you do want to use HTTPS this article describes how to enable HTTPS in Visual Studio.
- Authentication and authorization: Best practice for securing an MVC site is to require authorization for the entire controller (all action methods) and make exceptions for anonymous access to specific action
methods. Add required authorization to four controllers involved in your admin pages. Do this by adding the following line of code to the controllers: RetailController, ProductsController, CategoriesController, and ProductCategoriesController.
[Authorize(Users = "email@example.com")]
public class ProductsController : Controller
- Rebuild your project and open a view. You should be prompted to login. Click "Register as a new user" and create a user firstname.lastname@example.org and password Admin.1 (for grading purposes please use this username/password.) This will add the new user to the database "DefaultConnection."
- retail/index -
Listing random products: this exercise creates a home page for the retail site that displays 4-6
random products from the database.
- Use your admin pages to add at least six products with images to your database. Add at least
four categories and assign product to categories.
- Add an index method to the RetailController and allow anonymous access by decorating its action method
with the AllowAnonymous Attribute.
- The index action method in the retail controller will retrieve N random records from the database, similar to the MIS 324 music store project. Since you already have an entity model use LINQ to retrieve the items. The syntax is quite simple. Look at the index method of the ProductController for how to use LINQ to retrieve products and pass them to the view. The answer by reach4thelasers shows the LINQ syntax for retrieving n random records.
- Improve the layout to display the product names and small images.
The images need to have the desired display size inserted into the file name.
Here is one way to do this using Razor:
string image = item.ImageName;
int dot = image.LastIndexOf(".");
string size = "." + "200";
image = image.Insert(dot, size);
<a href='@Url.Action("Detail/" + item.ProductID)'>
class='productImage' alt="@item.ItemName" title="@item.ItemName" />
- retail/details- Add
a details page that displays the medium or large size image and other product attributes.
- Controller: The details method in the ProductController shows the LINQ syntax for retrieving one item.
- View: The details view in the Products View folder is a good template. Cut and paste and modify view as needed.
- retail/index -
This exercise adds a layout view and category menu to the retail exercise.
- The index and _leftMenu views are public facing so their action methods should be decorated with [AllowAnonymous].
- Layout: The retail store
needs a layout view to display the header, left menu, and any other shared elements. The tutorial Layout View describes how to setup a layout page.
- CSS: Add a new stylesheet named retail.css and edit App_start/BundleConfig.cs to use it.
- Header: You can either create a custom header or modify the default navigation. The
navigation should at a minimum link to retail/index, retail/admin, and retail/about
_leftMenu - The left menu is generated from a query of the items in the database tables Category and ProductCategory. We have used LINQ for all the database queries in RetailStore so let's use it here. The query needs to return a list of categories (only those with associated products), categoryIDs and a count of products in each category. Steps:
- Model: A model is needed to pass the query results from the controller to the view. .NET does not allow entity models to
be used for this purpose. Create a new model named CategoryDTO, where DTO stands for Data Transfer Object. This is an object used for moving data from the controller to the view. The new model should have three properties: CategoryID, CatLabel, and Count (types int, string, and int respectively).
- Controller: The LINQ query is similar to a SQL query in the sense that it has a join, groupby, and count. The syntax is:
public ActionResult _leftMenu()
var categories = (from c in db.Categories
join pc in db.ProductCategories
on c.CategoryID equals pc.CategoryID
select new CategoryDTO
CategoryID = c.CategoryID,
CatLabel = c.CatLabel,
Count = categorygroup.Count()
- View: Add a new view _leftMenu.cshtml. Call it from the layout page with:
Test. If you get an error message "This site can’t be reached" you need to add @Layout = null; to _leftMenu. This error is
caused by a circular reference: _layout calls _leftmenu, causing _leftmenu to call _layout, etc. After fixing the code
you may need to close the browser tab.
Add formatting (you may copy styles from the sample).
- Publishing: By default VS publishes only files needed to execute the project. This compiles .cs files into a binary and omits
items in the content folder. Change this setting by right-clicking on your project folder and selecting "Properties." Select "Package/Publish Web" and change "Only files needed to run this application" to "All files in this project folder."
Submission instructions: Submit assignments via
the Canvas course management system.
Submit the full URL for each exercise in the assignment, listing the URLs
in the same order that they are listed in the assignment. To minimize typos in URLs
it is strongly recommended
that you copy the URLs from the address bar of the browser
rather than trying to type them. Incorrect URLs
will not be graded and no credit will be given.
When pages are connected via navigation it is only
necessary to submit the URL of the first page.