Jump Start to be Software Developer (Session-5)

Hands on Training on  “ASP.NET MVC with Entity Framework” .

Topic: Develop a POS system from scratch by ASP.NET MVC with Entity Framework
Technical Speaker: Md. Mahedee Hasan
Venue: Microsoft Bangladesh
Organized by: Microsoft Bangladesh & Tech Forum
Date: 23 August, 2014

A simple application with ASP.NET MVC 4 with EF 6 Code first and Scaffolding

Introduction
Before going to the details of article, I think you already know what MVC is and how ASP.NET MVC Works. If you don’t have any idea, you are requested to read the following article.

  1. Introduction to ASP.NET MVC
  2. How to create first Application by ASP.NET MVC
  3. Uses of ViewBag and Model in ASP.NET MVC
  4. Routes and Controllers in ASP.NET MVC

Project description
In this article I will develop a simple application with ASP.NET MVC 4 with Entity Framework 6 code first approach and scaffolding. I will also use MvcScaffold for quick develop of controllers, context and views. For your kind information, here I used visual studio 2012. Here I will develop two functionalities of an application “Training Management system” – Trainer Information and Training Information. User can view, save, edit and delete Trainer information and training information can be viewed, saved, edit and deleted same way. Both trainer and training information will show in simple grid. Trainer can be assigned to the training information

Entity Framework – code first
Entity Framework (EF) is an object-relational mapper (ORM) that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.

Three approach of entity framework are Model first, Database first, code first. In Code-First Approach, we create the classes first and then generate the database from the classes directly

Application development step by step

Step 1: Create a simple application name “TMS” by asp.net mvc.

I think, you must know how to create an application by asp.net mvc .

Step 2: Install “nuget” packages.
For installing “nuget”, you must have enable internet connection.
Open Package Manager Console (Tools-> Library Package Manager –> Package Manager Console)

02-Packagemangerconsole

Run following commands in the console – bottom of the window.

PM>Install-Package EntityFramework

PM>Install-Package MvcScaffolding

Step 3: Create two models “Trainer” and “Training” in Model folder.

The following two files “Red marked” are Trainer and Training model.

1-Models

Trainer Model

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace TMS.Models
{
public class Trainer
{

[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }

public string Name { get; set; }

public string Designation { get; set; }
public string Oranizaton { get; set; }

public DateTime CreateDate { get; set; }
public DateTime ModificationDate { get; set; }

public bool IsActive { get; set; }
}
}

Training Model

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace TMS.Models
{
public class Training
{
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]

public long Id { get; set; }
public string Title { get; set; }
public string Venue { get; set; }
public long TrainerId { get; set; }

[ForeignKey("TrainerId")]
public virtual Trainer Trainer { get; set; }

public string Description { get; set; }

public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }

public DateTime CreateDate { get; set; }
public DateTime ModificationDate { get; set; }

public bool IsActive { get; set; }
}
}

In the above model, I used  [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]

Which means attribute “Id” of the model is primary key and it is a identity column.

[ForeignKey(“TrainerId”)] means TrainerId is a Foreign key of Trainer. This two are called data annotation. You will know more about data annotation. I will write another article on data annotation soon.

Step 4: Change Connection String

Create a database name “TMSDB” and change connection string like following

Step 5: Create Controller and View using “Scaffold”
Open Package Manager Console (Tools-> Library Package Manager –> Package Manager Console)
Type the following command to Package Manager Console.

PM> Scaffold Controller Trainer
PM> Scaffold Controller Training

After running the above command, the following (red marked) controller and view will be created.

03-Controllers

Step 6: Modify Contex and Layout.

Comment out the UserContext Class in AccountModels.cs file.

//public class UsersContext : DbContext
//{
// public UsersContext()
// : base("DefaultConnection")
// {
// }

// public DbSet UserProfiles { get; set; }
//}

Modify TMSContext.cs file like following

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace TMS.Models
{
public class TMSContext : DbContext
{
// You can add custom code to this file. Changes will not be overwritten.
//
// If you want Entity Framework to drop and regenerate your database
// automatically whenever you change your model schema, add the following
// code to the Application_Start method in your Global.asax file.
// Note: this will destroy and re-create your database with every model change.
//
// System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges());

//Added for customized connection string "TMSContext"
public TMSContext()
: base("TMSContext")
{
}

public DbSet UserProfiles { get; set; } //Added DbSet

public DbSet Trainers { get; set; } //Auto generated by scaffolding

public DbSet Trainings { get; set; } //Auto generated by scaffolding
}
}

Build the application you will find error. So, replace UsersContext by TMSContext and build again. Now it builds successfully.

Added the marked two line in the _Layout.cshtml page (Views->Shared->_Layout.cshtml)

04-Layout

Step 7: Add migration and update database
Run the following command in the package manager console.

PM> Enable-Migrations
PM> Add-Migration initialmigration
PM> Update-Database –Verbose

After running the above the command, table of the corresponding mode will be created like below.

05-database

Now your project is ready. Run your project and go to the Trainer and Training information link and you can View, insert, update and delete an entry. Let’s try. Yes it’s working. Thanks for your patient! :)

Routes and Controllers in ASP.NET MVC

Let’s consider a url http://localhost/home/about . How does it work in an MVC application? How does it deliver a request? Yes, routing engine is responsible for this task. So, what is routing engine? The routing engine is a core part of asp.net. It’s not tied to the MVC framework. You can use the routing engine to route requests for web form, WCF Service, actually any type of resources but in MVC we use this routing engine to direct requests to our controllers.

IC263184 - Copy

The goal of the routing engine, its job is to examine a URL and figure out where to send it for processing.

Let’s examine our TMS application (according to our previous article) or any other ASP.NET MVC application. If you open global.asax file of TMS, you can see a class here derived from HttpApplication and this allow to hook into some application level events like application start. This method(application_start) magically invoked by asp.net before processing the first http request. So when your application starts, application_start will execute one time before any of your controllers start executing. Here is the sample global.asax file.

public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

RouteConfig.RegisterRoutes(RouteTable.Routes); //Responsible for routing

BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();

}
}

In Application_Start() method the following statement is responsible for routing.
RouteConfig.RegisterRoutes(RouteTable.Routes);

If you click right button on “RegisterRoutes” and go to definition it will go to the RegisterRoutes method of the RouteConfig class which is App_Start folder. Here is the RouteConfig class. I can get into the definition of this method if I just put my cursor tight here on the method and press F12.

You have noticed that this class is called from the application start method in globa.asax.cs.

public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default", //Route Name
url: "{controller}/{action}/{id}", //URL with parameters (Pattern for the route)
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } //Default route

);
}
}

So, let me introduce details of the RegisterRoutes method. Here is the code we see, here the first statement is
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
It means ignore route which is in this pattern. Then let’s see the following statement. It means add a new route name “Default” and routing pattern must be “{controller}/{action}/{id}” and default routing

routes.MapRoute(
name: "Default", //Route Name
url: "{controller}/{action}/{id}", //URL with parameters (Pattern for the rout)
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } //Default route
);

Defaults route means, when you don’t type any controller or action in the URL, its goes to the index action of home controller.

Let’s go to the index action of home controller and modify the index action like following.

public ActionResult Index()
{
var controller = RouteData.Values["controller"];
var action = RouteData.Values["action"];
var id = RouteData.Values["id"];

var message = string.Format("{0}::{1} {2}",controller, action,id);

ViewBag.Message = message;

return View();
}

Now if you run the application you will see in the home page – Home::Index
If you slightly modify the url like – http://localhost:25379/Home/Index/2323.
You will see home page – Home::Index 2323
Now you understand what the function of route and controller is. Happy programming !!! :)

Recommended articles:

  1. Introduction to ASP.NET MVC
  2. How to create first Application by ASP.NET MVC
  3. Uses of ViewBag and Model in ASP.NET MVC

Uses of ViewBag and Model in ASP.NET MVC

In my series tutorial on ASP.NET MVC, I will try to develop an application which is called Training Management System (TMS). In this project, I will keep an employee’s skill matrix on the basis of training. Rather than this, I will keep employee information, training information and many more. I will continuously modify the project by implementing different features and functionality of ASP.NET MVC.
In this article, I will show how to implement a simple model and ViewBag. ASP.NET MVC offers us ViewBag for passing data from controller to view. ViewBag is dynamic object.
Let’s create a project using asp.net MVC. You can visit the following link for help: How to create first Application by ASP.NET MVC .

Step 1: Create a Model name – AboutModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TMS.Models
{
public class AboutModel
{
public string Name { get; set; }
public string Location { get; set; }
}
}

Step 2: Edit HomeController and update the About action as follows

public ActionResult About()
{
ViewBag.Message = "Company Information";

var aboutModel = new AboutModel();
aboutModel.Name = "Leadsoft Bangladesh Limited";
aboutModel.Location = "41/6, Purana Platan, Sawdesh Tower, Dhaka - 1000";

return View(aboutModel);
}

In this action, you will see, ViewBag.Message is used to hold a string, we will use it in view. I use a AboutModel object name aboutModel with its two property which will also use in the view.

Step 3: Edit About view (About.cshtml) as follows

@model TMS.Models.AboutModel
@{
ViewBag.Title = “About”;
}

@ViewBag.Title.




@ViewBag.Message


@Model.Name


Location : @Model.Location

Add @model TMS.Models.AboutModelat the top of the view. To view the ViewBag data use like @ViewBag.Message . Use AboutModel value like

@Model.Name


Location : @Model.Location
Now run the project and click About link. You will see the following output.
output

Recommended articles:

1. Introduction to ASP.NET MVC

2.How to create first Application by ASP.NET MVC

Introduction to ASP.NET MVC

What is MVC?

MVC is a framework methodology. It divides an application’s implementation into three component roles: models, views, and controllers.

MVC

  • The Model represents the application core (for instance a list of database records).
  • The View displays the data (the database records).
  • The Controller handles the input.

For example: If you request a page, first controller handle the request and order a action which will serve the request. Action can use model to get database record. Then action displays results to the view pages.

MVC provides full control over HTML, CSS and JavaScript.

You can think MVC model defines web applications with 3 logic layers:

The business layer (Model logic)

The display layer (View logic)

The input control (Controller logic)

The Model is the part of the application that handles the logic for the application data.
Often model objects retrieve data (and store data) from a database.

The View is the parts of the application that handles the display of the data.
Most often the views are created from the model data.

The Controller is the part of the application that handles user interaction.
Typically controllers read data from a view, control user input, and send input data to the model.

The MVC separation helps you manage complex applications, because you can focus on one aspect a time. For example, you can focus on the view without depending on the business logic. It also makes it easier to test an application.

The MVC separation also simplifies group development. Different developers can work on the view, the controller logic, and the business logic in parallel.

A Look at MVC Request Response process

From the above discussion, you may guess the Request Response process of MVC. Let us try to see this formally.

  1. User sends the request by the URL.
  2. UrlRoutingModule intercepts the request and starts parsing it.
  3. The appropriate Controller and handler will be identified from the URL by looking at the RouteTable collection. Also any data coming along with the request is kept in RouteData.
  4. The appropriate action in the identified controller will be executed.
  5. This action will create the Model class based on data.
  6. The action will then pass on this created model class to some view and tell the view to proceed.
  7. Now the view will execute and create the markup based on the logic and Model’s data and then push the HTML back to the browser.

This life cycle above is defined for explanation and has omitted some technical details.

What is View Engine?

View Engines are responsible for rendering the HTML from your views to the browser. The view engine template will have different syntax for implementation. Currently there are few numbers of view engines available for MVC and the top four view engines are Razor, traditional ASPX, Spark and NHaml.