Syllabus Schedule Project Canvas Assignment 1 Assignment 2 Assignment 3 Assignment 4

Assignment 1 - Entity Framework

Many e-commerce sites need a convenient and reliable method for non-technical people to maintain product and customer information. Providing clients with direct access to the database is risky since it allows them to inadvertently delete data, change settings, modify key fields, enter invalid data, etc. A better approach is to provide a web interface that validates inputs, allows access to only the fields that are needed to maintain the content, maintains referential integrity between database tables and provides a convenient way to upload product images. In this exercise you will construct administration pages for maintaining the product descriptions in simple e-commerce site.

An admin backend requires CRUD functionality for adding product information, categories, customer information, ect. Hand coding controllers and views would be very time consuming so we will utilize Microsoft's Entity Framework (EF) and the model and view building wizards in Visual Studio (VS). EF is Microsoft's object-relation mapping (ORM) framework for ADO.NET. Visual Studio include wizards that use EF to generate models from a database, generate databases from models, and create controllers and views with CRUD functionality. In this exercise you will complete a Microsoft tutorial that creates models and views from a database. You will then repeat the process using a simple retail store database.

These assignments are brand new. If you notice a significant problem or error please notify Professor Sandvig.

The username/password is "" and "Admin.1". You will be

  1. StudentEnrollment This exercies uses EF to generate models, controller, and views from a database. The database has three entities: students, courses, and enrollments. There is a many-to-many relationship between students and courses with enrollments as the associative table. Steps:
    1. You will create a database named ContosoUniversityData as described in this tutorial Getting ​Started with ​Entity ​Framework 6 ​Database ​First using ​MV​C 5 The tutorial uses a "Sql Server Database Project" to create the database. I could not get this method to work (even after reinstalling Sql Server Data Tools). Fortunately the database is very easy to create within a standard MVC project, as described in the following steps.
    2. Use Visual Studio 2013 to create a new MVC project named mis424Assignments. The first step of the tutorial Creating the Web Application and Data Models describes how. Stop after creating the project (before "Generate the models").
    3. Add Entity Framework 6 to your project. From the Visual Studio's Tools menu click NuGet Package Manager and then click Package Manager Console. In the Package Manager Console window enter the following command:

      Install-Package EntityFramework

    4. Create a new database named ContosoUniversityData. Right-click on the database in Server Explorer and select "New Query." In the tutorial Getting ​Started with ​Entity ​Framework 6 ​Database ​First using ​MV​C 5 are four Sql statements (three that create tables and one that adds data). Cut-and-paste each of the sql statements into the query designer and execute them. Check to make sure that the data was added correctly.
    5. Generate the models as described in this article
    6. Generate the views as described in EF Database First with ASP.NET MVC: Generating Views
    7. Done!
  2. retail/admin - In this exercise you will create the database for a simple retail store and administrative pages for adding and editing product information and product categories. Steps:
    1. Using the same project "mis424Assignments" that you created in the previous tutorial create a new database named "RetailStore" with three tables:Product, Category, ProductCategory. The fields for Product and Category are shown in the images. Use the following SQL code for ProductCategory. Note that it has an identity field Id rather than a composite key consisting of ProductID and CategoryID. The ID field is needed for EF to create a model for this table.
      CREATE TABLE [dbo].[ProductCategory] (
          [ID]         INT IDENTITY (1, 1) NOT NULL,
          [ProductID]  INT NOT NULL,
          [CategoryID] INT NOT NULL,
          UNIQUE NONCLUSTERED ([ProductID] ASC, [CategoryID] ASC),
          CONSTRAINT [FK_dbo.ProductCategory_dbo.Product_ProductID] FOREIGN KEY ([ProductID]) REFERENCES [dbo].[Product] ([ProductID]) ON DELETE CASCADE,
          CONSTRAINT [FK_dbo.ProductCategory_dbo.Category_CategoryID] FOREIGN KEY ([CategoryID]) REFERENCES [dbo].[Category] ([CategoryID]) ON DELETE CASCADE
    2. entity framework retail model Create a ADO.NET Entity Data Model named "RetailStoreModel" as in the previous exercise. Compile your project. Use use VS's scaffolding feature to create CRUD controllers and views using Entity Framework for the three tables.
    3. Create a new empty controller named "RetailController" and add an action method and view named "Admin". Add links to the admin pages created in the previous step.
    4. The admin pages needs navigation. We will put links to all asssignments on the default home page. Add the following code to Views/Home/index.cshtml.

      <li>@Html.ActionLink("Admin", "Admin", "Retail") </<li>

    5. Test by adding a couple of products, categories, and product categories. The products sold by your store can be anything you like as long as they are legal, tasteful and images are available. The products can be CD's, which will make it easier to recycle code from MIS 324. The sample site sells photographs.

  3. retail/admin -- Many e-commerce sites need a convenient method for uploading and resizing product images. In this exercise you are provided with a simple image upload and resize utility. You will modify it to save each image in three different sizes.
    1. The first answer to File Upload ASP.NET MVC describes how to upload files. Add the code for the HTML form to Views/Retail/Admin.cshtml which you created previously. We want the form to post to the admin action result of our RetailController so change "Index", "Home" to "Admin", "Retail"
    2. The code for writing the file to the server will be located in the RetailContoller. Copy the code snippet from the answer starting at [HttpPost]. Change its name from Index to Admin (since it is handling the post from Admin.cshtml). A better location for the files would be /content/ProductImages so modify the path in the MapPath statement. Also add a folder named ProductImages to the content folder. Change the redirectToAction from "Index" to "Admin". This code requires the System.IO namespace to add "using System.IO;" to the directives at the top of the page.
    3. Test by uploading an image. Note: to see the uploaded file in solution explorer you will need to click the "show all files" icon at the top of the window.
    4. For security we want to limit upload to images only. Add the following snippet inside the "if" statement before the file is written:
         string extension = Path.GetExtension(file.FileName).ToLower();
         if (!(extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".gif"))
             ViewBag.message = "Invalid image extension: " + extension;
             return View();
    5. Add @ViewBag.message to admin.cshtml to output the message.
    6. Give the user confirmation that their file has uploaded by adding:

      ViewBag.message = "Image successfully uploaded: " + fileName;

    7. The user needs to view the files that have been uploaded. The first answer to How to show images from a folder using Razor MVC? show how. Copy the code to admin.cshtml. His code shows only .jpg. Change "*.jpg" to "*.*" to show all files.
    8. The next step is to resize the images. We will follow Amazon's example and create three sizes for each file. The first answer How to resize and save an image which uploaded using file upload control in c# provides the code. In the Admin action method replace "file.SaveAs(path);" with the code from the solution. Remove the quotes around "path". The code uses the namespace WebHelpers so add "using System.Web.Helpers;" to the page directives.
    9. Test
    10. Repeat sizing and saving three times at sizes of approximately 200, 400, 600. The following code snippet shows one way this could be done:
         int[] sizes = { 600, 400, 200 };
         foreach (int size in sizes)
             img.Resize(size, size);
             int dot = path.LastIndexOf(".");
             string path2 = path.Insert(dot, "." + size);
    11. The user should be warned when the uploaded image is too small, something like this:
             if (img.Width < 600 && img.Height < 600)
                 ViewBag.message = "Please use a larger image. Should have one dimension >= 600px. ";
                 return View();
    12. Finally, we need a way for the user to delete files. In the admin view add hyperlinks under each image that point to an action method named "DeleteImage" and pass the image name as a parameter. In the retail controller add code similar to the first answer in ASP NET MVC 5 Delete File From Server. Improve the display of the images in the admin view by adding some styling and layout (see the sample site for ideas).
    13. The default publish configuration in VS is to publish only files needed to run the application. You also need it to publish your ProductImages folder. Go to application properties and change the Package/Publish Web deploy setting to "All files in this project folder."
    14. Finished for this week. Next week you will add security to the admin pages, an improved interface for assigning productCategories, and a retail front end.

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.

Regular Expressions HTML Color Names Color Picker ASCII Character Codes Unicode Character Codes