Friday 8 January 2016

Evolution of MVC with features

This article describes the different MVC evolution and its features. You can know the difference between  MVC3, MVC4, MVC5 and MVC6.

Features in MVC 3
·         Razor View Engine
·         Support .NET 4 data annotation.
·         Improved model validation.
·         Better JavaScript support,
·         Jquery validation
·         JSON binding
·         Support multiple view(Razor) engines.
·         start supporting to the HTML 5 and CSS 3.
·         Improved the Dependency Injection by using the IDependencyResolver interface.
·         added output caching for Partial views.

Features in MVC 4
·         Web API  framework. it works over the HTTP.
·         Enhancement to default project templates.
·         Mobile project template using Jquery mobile
·         Introduced to empty project template.
·         Task support for Asynchronous controller
·         Introduced to bundling and Magnification concepts.
·         Introduced to OAuth and OpenID login with the help of DotNetOpenAuth library.
·         Supports Windows Azure SDK 1.6.

Features in MVC 5
·         Identity for authentication and identity management.
·         Authentication and authorization (Membership provider ) for social networking site  like Google, facebook etc.
·         MVC 5 added  to authentication filters for authenticate to users using  third party authentication provider or your custom logic by using filter override methods and now we can override to filters on  method and  controller both.
·         Replaced to bootstrap by using the default template. and Controller Level.

Now, In MVC 5
·         Empty Template
·         Internet Application Template
·         Intranet Application Template
·         ASP.NET Web API Template
·         Mobile Project Template
·         Single Page Application Template
·         Asp.Net Identity
·         Bootstrap in the MVC 5 templates
·         Authentication Filters
·         Filter overrides

ASP.NET vNext or MVC6
·         MVC 6 Added new cloud computing optimization system of MVC , web API, SignalR and entity framework.
·         The Microsoft  make a bundle of MVC, Web API, WebPages, SignalR , That bundle we called MVC 6.
·         In MVC 6, Microsoft removed the dependency of system.web.dll from MVC 6  because it's so expensive. Typically  it consume 30K memory per request/response.
·         Right now, in MVC 6 consume 2K  memory per request response. It's too small memory consume.
·         Most of the problem solved using the Roslyn Compiler.
·         The work of Roslyn compiler as given below image.
·         The ASP .Net  vNext used the Roslyn Compiler,  By using Roslyn compiler do not need to compile the application Its  compile automatically the application code.
·         The .NET vNext is a cross platform and open source.
·         The .Net vNext has the new project extension project.json. Basically project.  Json contain the all dependency dll of the application.

·         In MVC 5.1 and 5.2 support to Enum and EnumHelper in  razor views.

Tuesday 5 January 2016

Entity Framework Code First approach with MVC

This article includes step by step tutorial to learn  Code First Approach  using  MVC in  Visual Studio. This scenario targets a database that doesn’t exist and Code First will create, or an empty database that Code First will add new tables .
[ Note : Make sure that Entity Framework already installed with Visual Studio. Otherwise install using  NuGet Packages.]
Step 1. Creating an MVC Application
·         Open Visual Studio
·         File  à New  à Project…
·         Select ASP.NET MVC3/4 Web Application.
·         Enter the name of application as  "CodeFirstDemo".
·         Click on  OK.

Step 2. Creating the Model
Right Click on the Models folder and  Create a model with the name of  "User" as below the picture and Create a properties  as below code



public class User
    {
        public int UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EMail { get; set; }
        public string Address { get; set; }
        public string PhoneNo { get; set; }
        public string Company { get; set; }
        public string Designation { get; set; }
    }

Step 3. Create a DBContext
Create a class with the Name of  MVCDBContext as in following picture. And Write the code as follows in MVCDBContext class.




using System.Data.Entity;
using System.Linq;
using CodeFirstDemo.Models;

namespace CodeFirstDemo
{
    public class MVCDBContext :DbContext
    {
        public DbSet<User> Users { get; set; }

    }
}
[ Note : Make sure that you are using " System.Data.Entity " Namespace. ]

Step 4 : Create a Controller.
Right click on the Controller folder and create a controller with the name of  "MyController"  as in picture below. And Write the following Code in as follows in My controller within Index Action.


        public ActionResult Index()
        {
            var dbContext = new MVCDBContext();
            var userList = from user in dbContext.Users select user;
            var users = new List<CodeFirstDemo.Models.User>();
            if (userList.Any())
            {
                foreach (var user in userList)
                {
                    users.Add(new CodeFirstDemo.Models.User() {
 UserId = user.UserId, Address = user.Address,
 Company = user.Company, FirstName = user.FirstName,
 LastName = user.LastName, Designation = user.Designation,
 EMail = user.EMail, PhoneNo = user.PhoneNo });
                }
            }
            ViewBag.FirstName = "My First Name";
            ViewData["FirstName"] = "My First Name";
            if(TempData.Any())
            {
                var tempData = TempData["TempData Name"];
            }
            return View(users);
        }

Now ,
·         Right click on Index and select add View… as  following image.
·         Click on Add button appear in the dialog box.


·         Gogto View folder and choose index.cshtml in My folder.


·         Type the following code in Index.cshtml file.

@model List<CodeFirstDemo.Models.User>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<div>
<table>
    <tr>
        <th>
            FirstName
        </th>
        <th>
            LastName
        </th>
        <th>
            EMail
        </th>
        <th>
            Address
        </th>
        <th>
            PhoneNo
        </th>
        <th>
            Company
        </th>
        <th>
            Designation
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.FirstName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.LastName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.EMail)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Address)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.PhoneNo)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Company)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Designation)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.UserId }) |
                @Html.ActionLink("Details", "Details", new { id=item.UserId }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.UserId })
            </td>
        </tr>
      
    }

</table>
</div>

Now, Again go to MyController and create new action with the name of Details as follows.
    public ActionResult Details(int? id)
        {
         var dbContext = new MVCDBContext();
         var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);
            var user = new CodeFirstDemo.Models.User();
            if (userDetails != null)
            {
                user.UserId = userDetails.UserId;
                user.FirstName = userDetails.FirstName;
                user.LastName = userDetails.LastName;
                user.Address = userDetails.Address;
                user.PhoneNo = userDetails.PhoneNo;
                user.EMail = userDetails.EMail;
                user.Company = userDetails.Company;
                user.Designation = userDetails.Designation;
            }
            return View(user);
        }
Again, Right click on the Details ActionResult and add view as same as index. and Write the code as follows in your Details view which you just created.

@model CodeFirstDemo.Models.User

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<fieldset>
    <legend>User</legend>

    <div class="display-label">FirstName</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.FirstName)
    </div>

    <div class="display-label">LastName</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.LastName)
    </div>

    <div class="display-label">EMail</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.EMail)
    </div>

    <div class="display-label">Address</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Address)
    </div>

    <div class="display-label">PhoneNo</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.PhoneNo)
    </div>

    <div class="display-label">Company</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Company)
    </div>

    <div class="display-label">Designation</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Designation)
    </div>
</fieldset>
<p>
    @Html.ActionLink("Edit", "Edit", new { id=Model.UserId }) |
    @Html.ActionLink("Back to List", "Index")
</p>

Repeat  the same process  for create an action in MyController for Create , Edit and Delete as follows and also add a views.
#region Edit...
        /// <summary>
        /// Get Action for Edit
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(int? id)
        {
         var dbContext = new MVCDBContext();
         var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);
         var user = new CodeFirstDemo.Models.User();
            if (userDetails != null)
            {
                user.UserId = userDetails.UserId;
                user.FirstName = userDetails.FirstName;
                user.LastName = userDetails.LastName;
                user.Address = userDetails.Address;
                user.PhoneNo = userDetails.PhoneNo;
                user.EMail = userDetails.EMail;
                user.Company = userDetails.Company;
                user.Designation = userDetails.Designation;
            }
            return View(user);
        }

        /// <summary>
        /// Post Action for Edit
        /// </summary>
        /// <param name="id"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(int? id, User userDetails)
        {
            TempData["TempData Name"] = "Akhil";

            try
            {
                var dbContext = new MVCDBContext();
                var user = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);
                if (user != null)
                {
                    user.FirstName = userDetails.FirstName;
                    user.LastName = userDetails.LastName;
                    user.Address = userDetails.Address;
                    user.PhoneNo = userDetails.PhoneNo;
                    user.EMail = userDetails.EMail;
                    user.Company = userDetails.Company;
                    user.Designation = userDetails.Designation;
                    dbContext.SaveChanges();
                }
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region Delete...
        /// <summary>
        /// Get Action for Delete
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(int? id)
        {
            var dbContext = new MVCDBContext();
         var user = new CodeFirstDemo.Models.User();
         var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);
            if (userDetails != null)
            {
                user.FirstName = userDetails.FirstName;
                user.LastName = userDetails.LastName;
                user.Address = userDetails.Address;
                user.PhoneNo = userDetails.PhoneNo;
                user.EMail = userDetails.EMail;
                user.Company = userDetails.Company;
                user.Designation = userDetails.Designation;
            }
            return View(user);
        }

        /// <summary>
        /// Post Action for Delete
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userDetails"> </param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(int? id, CodeFirstDemo.Models.User userDetails)
        {
            try
            {
                var dbContext = new MVCDBContext();
                var user = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);
                if (user != null)
                {
                    dbContext.Users.Add(user);
                    dbContext.SaveChanges();
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        #endregion



Create.cshtml
@model CodeFirstDemo.Models.User

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>User</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.EMail)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EMail)
            @Html.ValidationMessageFor(model => model.EMail)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Address)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Address)
            @Html.ValidationMessageFor(model => model.Address)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.PhoneNo)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.PhoneNo)
            @Html.ValidationMessageFor(model => model.PhoneNo)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Company)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Company)
            @Html.ValidationMessageFor(model => model.Company)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Designation)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Designation)
            @Html.ValidationMessageFor(model => model.Designation)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Delete.cshtml
@model CodeFirstDemo.Models.User

@{
    ViewBag.Title = "Delete";
}

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<fieldset>
    <legend>User</legend>

    <div class="display-label">FirstName</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.FirstName)
    </div>

    <div class="display-label">LastName</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.LastName)
    </div>

    <div class="display-label">EMail</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.EMail)
    </div>

    <div class="display-label">Address</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Address)
    </div>

    <div class="display-label">PhoneNo</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.PhoneNo)
    </div>

    <div class="display-label">Company</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Company)
    </div>

    <div class="display-label">Designation</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Designation)
    </div>
</fieldset>
@using (Html.BeginForm()) {
    <p>
        <input type="submit" value="Delete" /> |
        @Html.ActionLink("Back to List", "Index")
    </p>
}

Edit.cshtml
@model CodeFirstDemo.Models.User

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>User</legend>

        @Html.HiddenFor(model => model.UserId)

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.EMail)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EMail)
            @Html.ValidationMessageFor(model => model.EMail)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Address)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Address)
            @Html.ValidationMessageFor(model => model.Address)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.PhoneNo)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.PhoneNo)
            @Html.ValidationMessageFor(model => model.PhoneNo)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Company)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Company)
            @Html.ValidationMessageFor(model => model.Company)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Designation)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Designation)
            @Html.ValidationMessageFor(model => model.Designation)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>



Please make sure your Web.config file look as follows :


Now press  F5 to run the application,

Summary
In this walkthrough we looked at Code First development using a new database. We defined a model using classes then used that model to create a database and performed CRUD operation.