Tuesday 16 December 2014

Async operations with jQuery Ajax and Asp.Net MVC


By design in a MVC web application every action that you perform does a post back and/or navigation to the interface that implements it. If you want to add for example a new entry in the database you’ll have to navigate to “Create a new entry” url where you have a submit button that does a post back to save the data and returns you the result. In my “Post to Wall” app I am trying to avoid such a behavior, any operation that involves calling a controller action must not redirect or post back, this can be accomplished in several ways.
Microsoft provides a helper class named Ajax, with this helper you can create an async submit form by using Ajax.BeginForm, but for my app I chose to use the $.ajax implementation from the JQuery library, I prefer to use Microsoft’s ajax only combined with the WebGrid component.  I’ve chosen the jQuery’s ajax because it makes the code easy to debug and in my opinion it’s more compact and straightforward. You can easily debug JQuery with Firefox and Firebug, just set a break point in Firebug to watch the ajax call and another break point in VS.NET in the controller’s method, it would be nice to just use VS.NET but Firebug is a must when it comes to javascript debugging.
There are several steps in order to accomplish an asynchronous data exchange:
  1. Add a jQuery event handler for the html element that triggers the action
  2. Call the controller desired action using JQuery ajax
  3. Handle the json formatted data received from the server based on the response type (success or fault)
  4. Update the user interface (html) with jQuery
Lets see this implemented in my Post to Wall app:
In Index.cshtml declare a input button like this:
Index.cshtml
<input name="submit" type="submit"  value="Post" class="post-button fg-button ui-state-default"/>
In the controller expose a JsonResult action that will perform a insert operation in the database:
TextNotesController.cs
[HttpPost]
[ValidateInput(false)]
public JsonResult PostNote(string content)
{
    string message = string.Empty;
    var n = TxtNote.CreateTxtNote(0);
    n.Title = content;
    n.Created = DateTime.Now;
    try
    {
        db.AddToTxtNotes(n);
        db.SaveChanges();
    }
    catch (Exception ex)
    {
        message = ex.Message;
    }
    return Json(new
    {
        Html = this.RenderPartialView("_NotesList"new List<TxtNote>() { n }),
        Message = message
    }, JsonRequestBehavior.AllowGet);
}
Note that this method has the ValidInput attribute set to false, I want to be able to receive information that contains characters specific to html like < > ‘ “, those  characters will be escaped so it will not break the Index.cshtml code, in order to escape the text I am using  System.Security.SecurityElement.Escape method.
The JsonResult consists of two elements, the Html that represents the new entry in the database and the a message in case any error occurs. To make the html for my new entry I am using a partial view, this view will iterate throw a list of notes and make list elements for each one, the PostNote method inserts only one note so it will generate a single li. This partial view is used to generate one or several notes html, so I can use it as well for search results method.
_NotesList.cshtml
@model IEnumerable<MvcSp.Models.TxtNote>
@using MvcSp.Helpers
@foreach (var item in Model)
{
<li class="bar-@item.Id">
    <div align="left">
        <a href="#" title="Delete" class="del-note" id="@item.Id"><span class="ui-icon ui-icon-trash"style="float:right; margin-right:10px;"></span></a>
        <a href="#" title="Edit" class="edit-note" id="edit-@item.Id"><span class="ui-icon ui-icon-pencil"style="float:right; margin-right:1px;"></span></a>
        <a href="#" title="Mail" class="mail-note" id="mail-@item.Id"><span class="ui-icon ui-icon-comment" style="float:right; margin-right:1px;"></span></a>
        <p class="note-text">@MvcHtmlString.Create(@item.Title.Prep()) <br /><em>@item.Created</em></p>
    </div>
</li>
}
The last piece of code needed is the JQuery function:
Index.cshtml
    //post note
    $(function () {
        $(".post-button").click(function (e) {
            e.preventDefault();
            var boxval = $("#content").val();
            var dataString = 'content=' + boxval;
            if (boxval == '') {
                showError("Can't post an empty note");
            }
            else {
                showLoader('Saving note');
                $.ajax({
                    type: "POST",
                    url: "TextNotes/PostNote",
                    data: dataString,
                    cache: false,
                    dataType: "json",
                    success: function (data) {
                        if (data.Message) {
                            $("#flash").hide();
                            showError(data.Message);
                        } else {
                            $("ol#update").prepend(data.Html);
                            $("ol#update li:first").slideDown("slow");
                            document.getElementById('content').value = '';
                            $("#flash").hide();
                        }
                    }
                });
            }
            return false;
        });
    });  //end post note
This function adds a event handler to my post button using $(“post-button”).click, I am using the css class to refer the button, another way is by using the id of the element, like is done to obtain the text from  the textarea: $(“#content”).val(). the js will checks if the textarea is empty and will pop-up a jQuery UI dialog with the warning message, same for any errors occurs on the server side.
After the note is extracted from the textarea is appended to the json formatted data, I am using the same name “content=” as used in the controller method. Before starting the ajax call I am displaying a message to the user so he will know that an async operation is started, showing a gif animation is a good practice. For the rest of the js code involved in this operation you should download the project and see for yourself.
download source code files

Version history ; Entity Framework.

Friday 5 December 2014

Generic Repository pattern - app.net MVC




Introduction

Creating a Generic Repository pattern in an MVC3 application with Entity Framework is the last topic that we are about to cover in our journey of learning MVC.
The article will focus on Unit of Work Pattern and Repository Pattern, and shows how to perform CRUD operations in an MVC application when there could be a possibility of creating more than one repository class. To overcome this possibility and overhead, we make a Generic Repository class for all other repositories and implement a Unit of Work pattern to provide abstraction.

Our roadmap towards Learning MVC

Just to remind our full roadmap towards learning MVC, 

Pre-requisites

There are few pre-requisites before we start with the article,
  1. We have running sample application that we created in fifth part of the article series.
  2. We have Entity Framework 4.1 package or DLL on our local file system.
  3. We understand how MVC application is created (follow second part of the series).

Why Generic Repository

We have already discussed what Repository Pattern is and why do we need Repository Pattern in our last article. We created a User Repository for performing CRUD operations, but think of the scenario where we need 10 such repositories.
Are we going to create these classes? Not good, it results in a lot of redundant code. So to overcome this situation we’ll create a Generic Repository class that will be called by a property to create a new repository thus we do not result in lot of classes and also escape redundant code too. Moreover we save a lot of time that could be wasted creating those classes.

Unit of Work Pattern

According to Martin Fowler Unit of Work Pattern “Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems."
From MSDN, The Unit of Work pattern isn't necessarily something that you will explicitly build yourself, but the pattern shows up in almost every persistence tool. The ITransaction interface in NHibernate, the DataContextclass in LINQ to SQL, and the ObjectContext class in the Entity Framework are all examples of a Unit of Work. For that matter, the venerable DataSet can be used as a Unit of Work.
Other times, you may want to write your own application-specific Unit of Work interface or class that wraps the inner Unit of Work from your persistence tool. You may do this for a number of reasons. You might want to add application-specific logging, tracing, or error handling to transaction management. Perhaps you want to encapsulate the specifics of your persistence tooling from the rest of the application. You might want this extra encapsulation to make it easier to swap out persistence technologies later. Or you might want to promote testability in your system. Many of the built-in Unit of Work implementations from common persistence tools are difficult to deal with in automated unit testing scenarios."
The Unit of Work class can have methods to mark entities as modified, newly created, or deleted. The Unit of Work will also have methods to commit or roll back all of the changes as well.
The important responsibilities of Unit of Work are,
  • To manage transactions.
  • To order the database inserts, deletes, and updates.
  • To prevent duplicate updates. Inside a single usage of a Unit of Work object, different parts of the code may mark the same Invoice object as changed, but the Unit of Work class will only issue a single UPDATE command to the database.
The value of using a Unit of Work pattern is to free the rest of our code from these concerns so that you can otherwise concentrate on business logic.

Why use Unit of Work?

Again Martin Fowler statements, "When you're pulling data in and out of a database, it's important to keep track of what you've changed; otherwise, that data won't be written back into the database. Similarly you have to insert new objects you create and remove any objects you delete.
You can change the database with each change to your object model, but this can lead to lots of very small database calls, which ends up being very slow. Furthermore it requires you to have a transaction open for the whole interaction, which is impractical if you have a business transaction that spans multiple requests. The situation is even worse if you need to keep track of the objects you've read so you can avoid inconsistent reads.
A Unit of Work keeps track and takes responsibility of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work."
You see I don’t have to concentrate much on theory, we already have great definitions existing, all we needed is to stack them in a correct format.

Using the Unit of Work

One of the best ways to use the Unit of Work pattern is to allow disparate classes and services to take part in a single logical transaction. The key point here is that you want the disparate classes and services to remain ignorant of each other while being able to enlist in a single transaction. Traditionally, you've been able to do this by using transaction coordinators like MTS/COM+ or the newer System.Transactions namespace. Personally, I prefer using the Unit of Work pattern to allow unrelated classes and services to take part in a logical transaction because I think it makes the code more explicit, easier to understand, and simpler to unit test(From MSDN).

Creating a Generic Repository

Cut the Redundancy…
Step 1: Open up our existing MVC3 application created in Part5 in Visual Studio.
Step2: Right click Learning MVC project folder and create a folder named GenericRepository and add a class namedGenericRepository.cs to that folder.
The code of the GenericRepository.cs class is as follows:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

namespace LearningMVC.GenericRepository
{
    public class GenericRepository<TEntity> where TEntity : class
    {
        internal MVCEntities context;
        internal DbSet<TEntity> dbSet;

        public GenericRepository(MVCEntities context)
        {
            this.context = context;
            this.dbSet = context.Set<TEntity>();
        }

        public virtual IEnumerable<TEntity> Get()
        {
            IQueryable<TEntity> query = dbSet;
            return query.ToList();
        }

        public virtual TEntity GetByID(object id)
        {
            return dbSet.Find(id);
        }

        public virtual void Insert(TEntity entity)
        {
            dbSet.Add(entity);
        }

        public virtual void Delete(object id)
        {
            TEntity entityToDelete = dbSet.Find(id);
            Delete(entityToDelete);
        }

        public virtual void Delete(TEntity entityToDelete)
        {
            if (context.Entry(entityToDelete).State == EntityState.Detached)
            {
                dbSet.Attach(entityToDelete);
            }
            dbSet.Remove(entityToDelete);
        }

        public virtual void Update(TEntity entityToUpdate)
        {
            dbSet.Attach(entityToUpdate);
            context.Entry(entityToUpdate).State = EntityState.Modified;
        }
    }
}
We can see, we have created the generic methods and the class as well is generic, when instantiating this class we can pass any model on which the class will work as a repository and serve the purpose.
TEntity is any model/domain/entity class. MVCEntities is our DBContext as discussed in earlier parts.
Step 3: Implementing UnitOfWork: Create a folder named UnitOfWork under LearningMVC project, and add a class UnitOfWork.cs to that folder.
The code of the class is as follows:
using System;
using LearningMVC.GenericRepository;

namespace LearningMVC.UnitOfWork
{
    public class UnitOfWork : IDisposable
    {
        private MVCEntities context = new MVCEntities();
        private GenericRepository<User> userRepository;

        public GenericRepository<User> UserRepository
        {
            get
            {
                if (this.userRepository == null)
                    this.userRepository = new GenericRepository<User>(context);
                return userRepository;
            }
        }

        public void Save()
        {
            context.SaveChanges();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
We see the class implements IDisposable interface for objects of this class to be disposed.
We create object of DBContext in this class, note that earlier it was used to be passed in Repository class from a controller.
Now it's time to create our User Repository. We see in the code itself that, simply a variable named userRepositoryis declared as private GenericRepository<User> userRepository; of type GenericRepository serving User entity to TEntity template.
Then a property is created for the same userRepository variable in a very simplified manner,
public GenericRepository<User> UserRepository
{
    get
    {
        if (this.userRepository == null)
            this.userRepository = new GenericRepository<User>(context);
        return userRepository;
    }
}
I.e., mere 6-7 lines of code. Guess what? Our UserRepository is created.
(Taken from Google)
You see it was as simple as that, you can create as many repositories you want by just creating simple properties, and no need to create separate classes. And now you can complete the rest of the story by yourself, confused???? Yes it'sDBOperations, let's do it.
Step 4: In MyController, declare a variable unitOfWork as:
private UnitOfWork.UnitOfWork unitOfWork = new UnitOfWork.UnitOfWork();
Now this unitOfWork instance of UnitOfWork class holds all th repository properties,if we press “." After it, it will show the repositories.So we can choose any of the repositories created and perform CRUD operations on them.
E.g. our Index action:
public ActionResult Index()
{
    var userList = from user in unitOfWork.UserRepository.Get() select user;
    var users = new List<LearningMVC.Models.UserList>();
    if (userList.Any())
    {
        foreach (var user in userList)
        {
            users.Add(new LearningMVC.Models.UserList() { 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);
}
Here,
  • unitOfWork.UserRepository ­­> Accessing UserRepository.
  • unitOfWork.UserRepository.Get() -> Accessing Generic Get() method to get all users.
Earlier we used to have MyController constructor like:
public MyController()
{
    this.userRepository = new UserRepository(new MVCEntities());
}
Now, no need to write that constructor, in fact you can remove the UserRepository class and Interface we created in part 5 of Learning MVC.
I hope you can write the Actions for rest of the CRUD operations as well.

Details

public ActionResult Details(int id)
{
    var userDetails = unitOfWork.UserRepository.GetByID(id);
    var user = new LearningMVC.Models.UserList();
    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);
}

Create:
[HttpPost]
public ActionResult Create(LearningMVC.Models.UserList userDetails)
{
    try
    {
        var user = new 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;
        }
        unitOfWork.UserRepository.Insert(user);
        unitOfWork.Save();
        return RedirectToAction("Index");
          }
    catch
    {
        return View();
    }
}

Edit:
public ActionResult Edit(int id)
{
    var userDetails = unitOfWork.UserRepository.GetByID(id);
    var user = new LearningMVC.Models.UserList();
    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);
}

[HttpPost]
public ActionResult Edit(int id, User userDetails)
{
    TempData["TempData Name"] = "Akhil";

    try
    {
        var user = unitOfWork.UserRepository.GetByID(id);
        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;
        unitOfWork.UserRepository.Update(user);
        unitOfWork.Save();
        return RedirectToAction("Index");
    }

Delete:
public ActionResult Delete(int id)
{
    var user = new LearningMVC.Models.UserList();
    var userDetails = unitOfWork.UserRepository.GetByID(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);
}

[HttpPost]
public ActionResult Delete(int id, LearningMVC.Models.UserList userDetails)
{
    try
    {
        var user = unitOfWork.UserRepository.GetByID(id);

        if (user != null)
        {
            unitOfWork.UserRepository.Delete(id);
            unitOfWork.Save();
        }

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

Note: Images are taken from Google images.

Conclusion

We now know how to make generic repositories too, and perform CRUD operations using it.
We have also learnt UnitOfWork pattern in detail. Now you are qualified and confident enough to apply these concepts in your enterprise applications. This was the last part of this MVC series, let me know if you feel to discuss any topic in particular or we can also start any other series as well. For more informative articles,visit my blog A Practical Approach 
Happy coding :-).

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...