MVC

MVC 4 APPLICATION USING ENTITY FRAMEWORK 5.0 WITH DATABASE FIRST APPROACH

INTRODUCTION
Now a day’s most of the developers will go for Code First approach in the entity framework where the database is very small and easy to manage. In this case developers will create the model first and create the database out of it.
What in the case of large projects? Here developers will prefer to opt for Database first approach where the database is created first and data model is created out of the database.

OVERVIEW
We will be using Visual studio 2012, MVC 4 and entity frame framework 5 for this example.
We will be using Sql Server 2008 R2 for database creation.

Creating a MVC 4 Project

To start with open the visual studio 2012 and select new project from the file menu. The new project dialog box opens as shown below.
1_New_Project
Select ASP.NET MVC 4 Application and provide desired name for your project and click on the OK button. The project Template dialog box opens as shown below.

2_Project_Template
Select Internet Application from the Project Template and click on the OK button.Visual studio opens the MVC 4 project with the name which you have provided.Remove the Default created pages by .net framework 4.5.

Create a database for the project.

We will be creating the database by name “MVC_EF_DatabaseFirst” in Sql server 2008 R2.
Create a table by name Users which will maintain the details for the user.
Below is the script for the same.
USE [MVC_EF_DatabaseFirst]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[UserDetails]
(
[UserID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](100) NOT NULL,
[Address] [varchar](1000) NULL,
[Town] [varchar](50) NULL,
[County] [varchar](50) NULL,
[Country] [varchar](50) NULL,
[Rating] [int] NULL,
[DoB] [datetime] NULL,
CONSTRAINT [PK_UserDetails] PRIMARY KEY CLUSTERED
(
[UserID] ASC
)
WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

Once you have done with creating the database and table, we will start working on project. Now we need to create the Entity Data Model class file from the Users table. To create Data model class file, we will do reverse engineering for code first.

Right click on the Project -> point to Entity Framework -> click on Reverse engineer Code first as shown below.

Reverse_code_first

This will open the connection Properties. Specify the connection details and click on the OK button as shown below.

Db_connection

This will generate the Entity data model with the mapping class add the connection string in your Web. Config file as shown below.

Mapping_Class

Open the HomeController.cs file and write the code to fetch the data from the model.

Index Page

We will start by creating an index page. Below is the screenshot for the Index page.

Index_no_records_page

Please add the below code to the Index.cshtml page.

Html_Index

In the above html code I have specified the title of the page followed by table which loops through the records for displaying the data.I have also provided the search functionality which will search for the specific record and display it in table.In the controller add the below code so that the index page will display data.

private MVC_EF_DatabaseFirstContext dbContext = new MVC_EF_DatabaseFirstContext();
public ActionResult Index(string strValue)
{
try
{
var GetUserDetails = from s in dbContext.UserDetails select s;
if (!String.IsNullOrEmpty(strValue))
{
GetUserDetails = GetUserDetails.Where(user => user.Name == strValue || user.Address == strValue || user.Town == strValue || user.Country == strValue || user.County == strValue);
}
return View("Index", GetUserDetails);
}
catch (Exception)
{
return View();
}
}

In the above code we have called UserDetails entity through the context and fetch the data into the view.

Add User

Now i will create the Add user page to add new user to the database.  Right click on the Views -> Home -> Add -> View.

It will open a dialog box to add new view. Name the view as AddUser.cshtml. Below is the screenshot for the same.

Add_New_User

Now add the below code in the controller for add user page working.

public ActionResult AddUser()
{
return View();
}

[HttpPost]
public ActionResult AddUser(UserDetail objUserdetails)
{
try
{
if (ModelState.IsValid)
{
dbContext.UserDetails.Add(objUserdetails);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
}
catch (Exception)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(objUserdetails);
}

In the above code we have created the object of the UserDetails entity and used that object to fill the data into the context.

ModelState.IsValid will validate the data entered by the user. Now I need to provide other validations such length of the string etc on the field.

For that open the UserDetails.cs file under Models folder.

Add the data annotations to each field as shown in the below code.

public partial class UserDetail
{
public int? UserID { get; set; }

[Display(Name="User Name")]
[Required]
[StringLength(50, ErrorMessage = "User name cannot be longer than 50 characters.")]
public string Name { get; set; }

[Display(Name = "User Address")]
[Required]
[StringLength(1000, ErrorMessage = "User Address cannot be longer than 1000 characters.")]
public string Address { get; set; }

[Display(Name = "User Town")]
[Required]
[StringLength(50, ErrorMessage = "User Town cannot be longer than 50 characters.")]
public string Town { get; set; }

[Display(Name = "User County")]
[Required]
[StringLength(50, ErrorMessage = "User County cannot be longer than 50 characters.")]
public string County { get; set; }

[Display(Name = "User Country")]
[Required]
[StringLength(50, ErrorMessage = "User Country cannot be longer than 50 characters.")]
public string Country { get; set; }

public Nullable<int> Rating { get; set; }

[Display(Name = "User Date of Birth")]
[Required]
[DisplayFormat(DataFormatString = "{0:dd MMMM, yyyy}")]
public Nullable<System.DateTime> DoB { get; set; }
}

The above code checks for required, string length and date format.

Edit User

When the user clicks on the Edit Hyperlink in the table it will navigate to the Edit user page.

To create the Edit User page, right click on the Views -> Home -> Add -> View.

It will open a dialog box to add new view. Name the view as EditUser.cshtml. Below is the screenshot for the same.

Edit_user

Create a view by name EditUser.cshtml and add the below code for the same.

Html_EditNow add the below code in the controller for displaying the records in the Edit mode and save it after changes.

public ActionResult EditUser(int id = 0)
{
UserDetail userDetail = dbContext.UserDetails.Find(id);

if (userDetail == null)
{
return HttpNotFound();
}
return View(userDetail);
}


[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditUser(UserDetail objUserdetails)
{
try
{
if (ModelState.IsValid)
{
dbContext.Entry(objUserdetails).State = System.Data.EntityState.Modified;
dbContext.SaveChanges();
return RedirectToAction("Index");
}
}

catch (Exception)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View();
}

In the above code the Edit user page will display records in the edit mode for that particular user. Once the data is modified the user can save the changes in to the database.

User Details

User details page will display the all the details for that particular user when clicked on the Details link from the grid.

To create the User Details page, right click on the Views -> Home -> Add -> View.

It will open a dialog box to add new view. Name the view as EditUser.cshtml. Below is the screenshot for the same.

User_Details

Create a view by name UserDetails.cshtml and add the below code for the same.

Html_Details

Add the below code in the controller for user detail functionality.

public ActionResult UserDetails(int id = 0)
{
UserDetail userDetail = dbContext.UserDetails.Find(id);

if (userDetail == null)
{
return HttpNotFound();
}
return View(userDetail);
}

The above code will take user id as a input parameter and displays the data accordingly.

Delete User

Create a delete User page by name DeleteUser.cshtml and add the below code in the page.

Html_Delete

Add the below code in the Controller.

public ActionResult DeleteUser(int id = 0)
{
UserDetail userDetail = dbContext.UserDetails.Find(id);
if (userDetail == null)
{
return HttpNotFound();
}
return View(userDetail);
}

[HttpPost, ActionName("DeleteUser")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
try
{
UserDetail userDetail = dbContext.UserDetails.Find(id);
dbContext.UserDetails.Remove(userDetail);
dbContext.SaveChanges();
}
catch (DataException)
{
return RedirectToAction("DeleteUser", new { id = id, saveChangesError = true });
}
return RedirectToAction("Index");
}

The above code will take user id as a parameter and displays all the user details on the page.

When the user clicks on the delete button DeleteConfirmed action result will get fired deleting the user and redirection it back to the index page.

The source code can be downloaded from Here.

ERROR HANDLING USING ELMAH IN MVC

INTRODUCTION

Error Handling is the one of the most important thing which we used to track errors.

There are different ways of handling errors which developers preferred to log errors. Some developers write their own code to log errors in database, XML files or either text files.

There are also third party tools available to log errors. In this article I will show you how to log errors in the database using Google Elmah error handling in MVC application.

OVERVIEW

To integrate Elmah tool in your application you need to download the file from the Google code site.

To download the file click on the following link: – http://code.google.com/p/elmah/.

Or you can install through the Nuget package manager. You can install the Nuget package manager through the visual studio Library Package Manager. For more information visit http://www.nuget.org/

I will be installing the Elmah using the Nuget package manager.

I will be demonstrating the use of Elmah in Visual Studio 2012 using MVC 4 application.

Open the visual studio 2012 and select New Project from the start menu.

This will open the New Project dialog box as shown below.

New_Project

Select MVC 4 web Application from the template and provide the name of the project.

This will open the MVC 4 project template as shown below.

Project_Template

Select the Internet application and click on the OK button to launch the MVC 4 project.

Now, we will install the Elmah through the Nuget package manager.

Select tools from the menu and point to Library Package Manager. Select Manage Nuget Packages for Solution as shown below.

Nuget_manager_Console

This will open the Package Manager Console. Now install the Elmah using the below command.

Install-Package Elmah

This will install the Elmah package in to the application as shown below.

Install_elmah_Nuget

It will automatically add all the details in to the Web.Config file.

A couple of modification is required to make in the Web.config files to make Error logging work.

You need to add handlers and make modification in the Elmah section as shown below.

Just specify the data source, user name and password in your connection string and rest of the settings for Elmah you need to specify as shown below.

Config

Now you need to create the database for logging the errors.

To download the Elmah script visit the link https://code.google.com/p/elmah/source/browse/src/Elmah.SqlServer/SQLServer.sql

Once done with the above configuration we will write a code to generate the error.

Now we need to make use of Elmah for logging the error in the database you have created.

For testing the Elmah error log create a method that will generate the error as shown below.

private void Division()
{
try
{
int i = 0;
int j = 2;
int x = j / i;
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}

Call this method in the Index Action Result.

ErrorSignal.FromCurrentContext().Raise(ex) is used to log error and store it in database.

To check the error, just open the browser and type the URL of your web application followed by elmah.axd. Below is the screenshot.

Elmah

Now access the URL for example. http://localhost:6061/elmah.axd

You can see the screen in the grid format displaying the details of your error.
To view more details related to your error click on the details link next to your error. The details explanation of the error will be displayed as shown below.

Elmah_Details

For more information Elmah Error logging refer to the below link.

http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/logging-error-details-with-elmah-cs

To download the demo project, click Here.