Wednesday, April 11, 2018

JQGrid in an ASP.Net Application

JQGrid is a light weighted and open source grid developed in JavaScript Jquery to fill data from the database.
Download the JQ Grid js file go to the following site: http://www.trirand.com/blog/?page_id=6.
1.Create a web method in Home.aspx.cs file and it should return json data to the UI. But, for the demo purpose i am creating an array and loading the data.
2.Add this code in to Home.aspx file first call all the related JQ Grid related js files.
<script src="../js/jquery-1.5.2.min.js" type="text/javascript"></script>
<script src="../js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="../js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="../Scripts/json2-min.js" type="text/javascript"></script>
After that for the JQ Grid paste The following code:
<script type="text/javascript">
    $(document).ready(function () {
        jQuery("#list1").jqGrid({
            datatype: "local",          
            colNames: ['Inv No', 'Date', 'Client', 'Amount', 'Tax', 'Total', 'Notes'],
            colModel: [
                     { name: 'id', index: 'id', width: 60, sorttype: "int" },
                     { name: 'invdate', index: 'invdate', width: 90, sorttype: "date" },
                     { name: 'name', index: 'name', width: 100 },
                     { name: 'amount', index: 'amount', width: 80, align: "right", sorttype: "float" },
                     { name: 'tax', index: 'tax', width: 80, align: "right", sorttype: "float" },
                     { name: 'total', index: 'total', width: 80, align: "right", sorttype: "float" },
                     { name: 'note', index: 'note', width: 150, sortable: false }
               ],
            multiselect: true,
            rowNum: 10,
            rowList: [5, 10, 20, 50, 100],
            pager: jQuery('#pager1'),
            sortorder: "desc",
            viewrecords: true,        
            caption: "Manipulating Array Data in to JQGrid"
        });     

        var mydata = [
             { id: "1", invdate: "2007-10-01", name: "test1", note: "note", amount: "200.00", tax:"10.00", total:
"210.00" },

             { id: "2", invdate: "2007-10-02", name: "test2", note: "note2", amount: "300.00", tax:"20.00", total: "320.00" },

             { id: "3", invdate: "2007-09-01", name: "test3", note: "note3", amount: "400.00", tax:"30.00", total: "430.00" },

             { id: "4", invdate: "2007-10-04", name: "test4", note: "note", amount: "200.00", tax:"10.00", total: "210.00" },

             { id: "5", invdate: "2007-10-05", name: "test5", note: "note2", amount: "300.00", tax:"20.00", total: "320.00" },

              { id: "6", invdate: "2007-09-06", name: "test6", note: "note3", amount: "400.00", tax:"30.00", total: "430.00" },

             { id: "7", invdate: "2007-10-04", name: "test7", note: "note", amount: "200.00", tax:"10.00", total: "210.00" },

             { id: "8", invdate: "2007-10-03", name: "test8", note: "note2", amount: "300.00", tax:"20.00", total: "320.00" },

             { id: "9", invdate: "2007-09-01", name: "test9", note: "note3", amount: "400.00", tax:"30.00", total: "430.00" }

             ];

        for (var i = 0; i <= mydata.length; i++)

            jQuery("#list1").jqGrid('addRowData', i + 1, mydata[i]);


            });
 //    });
        
</script>
3.Add this inside the body 

<table id="list1" ></table>
<div id="pager1" ></div>
4. Result: So in this example we have seen how to bind the value from an array to a JQ Grid.



Wednesday, June 29, 2016

MVC QA

1) Explain in which assembly is the MVC framework is defined?
The MVC framework is defined in System.Web.Mvc. 

2) Explain what is Model-View-Controller?
MVC is a software architecture pattern for developing web application. It is handled by three objects Model-View-Controller.

3) Mention what does Model-View-Controller represent in an MVC application?
In an MVC model,
ü  Model– It represents the application data domain. In other words applications business logic is contained within the model and is responsible for maintaining data
ü  View– It represents the user interface, with which the end users communicates. In short all the user interface logic is contained within the VIEW
ü  Controller– It is the controller that answers to user actions. Based on the user actions, the respective controller responds within the model and choose a view to render that display the user interface.  The user input logic is contained with-in the controller

4) Mention what is the difference between adding routes, to a webform application and an MVC application?
To add routes to a webform application, we can use MapPageRoute() method of the RouteCollection class, where adding routes to an MVC application, you can use MapRoute() method.
5) List out few different return types of a controller action method?
ü  View Result
ü  Javascript Result
ü  Redirect Result
ü  Json Result
ü  Content Result

6) Mention what are the two ways to add constraints to a route?
The two methods to add constraints to a route is
ü  Use regular expressions
ü  Use an object that implements IRouteConstraint Interface


7) Mention what is the advantages of MVC?
ü  MVC segregates your project into a different segment, and it becomes easy for developers to work on
ü  It is easy to edit or change some part of your project that makes project less development and maintenance cost
ü  MVC makes your project more systematic

8) Mention what “beforFilter()”,“beforeRender” and “afterFilter” functions do in Controller?
ü  beforeFilter(): This function is run before every action in the controller. It’s the right place to check for an active session or inspect user permissions.
ü  beforeRender(): This function is called after controller action logic, but before the view is rendered. This function is not often used, but may be required If you are calling render() manually before the end of a given action
ü  afterFilter(): This function is called after every controller action, and after rendering is done. It is the last controller method to run

9) Explain the role of components Presentation, Abstraction and Control in MVC?
ü  Presentation: It is the visual representation of a specific abstraction within the application
ü  Abstraction: It is the business domain functionality within the application
ü  Control: It is a component that keeps consistency between the abstraction within the system and their presentation to the user in addition to communicating with other controls within the system.

10) Mention the advantages and disadvantages of MVC model?

Advantages
Disadvantages
·          It represents clear separation between business logic and presentation logic
·          Each MVC object has different responsibilities
·          The development progresses in parallel
·          Easy to manage and maintain
·          All classes and object are independent of each other
·          The model pattern is little complex
·          Inefficiency of data access in view
·          With modern user interface, it is difficult to use MVC
·          You need multiple programmers for parallel development
·          Multiple technologies knowledge is required


11) Explain the role of “ActionFilters” in MVC?
In MVC “ ActionFilters” help you to execute logic while MVC action is executed or its executing.

12) Explain what are the steps for the execution of an MVC project?
The steps for the execution of an MVC project includes
o   Receive first request for the application
o   Performs routing
o   Creates MVC request handler
o   Create Controller
o   Execute Controller
o   Invoke action
o   Execute Result

13) Explain what is routing? What are the three segments for routing is important?
Routing helps you to decide a URL structure and map the URL with the Controller.
The three segments that are important for routing is
o   ControllerName
o   ActionMethodName
o   Parameter

14) Explain how routing is done in MVC pattern?
There is a group of routes called the RouteCollection, which consists of registered routes in the application.  The RegisterRoutes method records the routes in this collection.  A route defines a URL pattern and a handler to use if the request matches the pattern. The first parameter to the MapRoute method is the name of the route. The second parameter will be the pattern to which the URL matches.  The third parameter might be the default values for the placeholders if they are not determined.

15) Explain using hyperlink how you can navigate from one view to other view?
By using “ActionLink” method as shown in the below code. The below code will make a simple URL which help to navigate to the “Home” controller and invoke the “GotoHome” action.
Collapse / Copy Code
<%= Html.ActionLink(“Home”, “Gotohome”) %>

16) Mention how can maintain session in MVC?

Session can be maintained in MVC by three ways tempdata, viewdata, and viewbag.

17) Mention what is the difference between Temp data, View, and View Bag?
ü    Temp data: It helps to maintain data when you shift from one controller to other controller.
ü    View data: It helps to maintain data when you move from controller to view
ü    View Bag: It’s a dynamic wrapper around view data

18) What is partial view in MVC?
Partial view in MVC renders a portion of view content. It is helpful in reducing code duplication. In simple terms, partial view allows to render a view within the parent view.

19) Explain how you can implement Ajax in MVC?
In Ajax, MVC can be implemented in two ways
ü    Ajax libraries
ü    Jquery

20) Mention what is the difference between “ActionResult” and “ViewResult” ?
“ActionResult” is an abstract class while “ViewResult” is derived from “AbstractResult” class.  “ActionResult” has a number of derived classes like “JsonResult”, “FileStreamResult” and “ViewResult” .
“ActionResult” is best if you are deriving different types of view dynamically.

21) Explain how you can send the result back in JSON format in MVC?
In order to send the result back in JSON format in MVC, you can use “JSONRESULT” class.

22) Explain what is the difference between View and Partial View?



23) List out the types of result in MVC?

                            View
                               Partial View
·          It contains the layout page
·          Before any view is rendered, viewstart page is rendered
·          View might have markup tags like body, html, head, title, meta etc.
·          View is not lightweight as compare to Partial View
·           It does not contain the layout page
·          Partial view does not verify for a viewstart.cshtml. We cannot put common code for a partial view within the viewStart.cshtml.page
·          Partial view is designed specially to render within the view and just because of that it does not consist any mark up
·          We can pass a regular view to the RenderPartial method



In MVC, there are twelve types of results in MVC where “ActionResult” class is the main class while the 11 are their sub-types
ü  ViewResult
ü  PartialViewResult
ü  EmptyResult
ü  RedirectResult
ü  RedirectToRouteResult
ü  JsonResult
ü  JavaScriptResult
ü  ContentResult
ü  FileContentResult
ü  FileStreamResult
ü  FilePathResult

24) Mention what is the importance of NonActionAttribute?
All public methods of a controller class are treated as the action method if you want to prevent this default method then you have to assign the public method with NonActionAttribute.

25) Mention what is the use of the default route {resource}.axd/{*pathinfo} ?
This default route prevents request for a web resource file such as Webresource.axd or ScriptResource.axd from being passed to the controller.

26) Mention the order of the filters that get executed, if the multiple filters are implemented?
The filter order would be like
ü  Authorization filters
ü  Action filters
ü  Response filters
ü  Exception filters

27) Mention what filters are executed in the end?
In the end “Exception Filters” are executed.

28) Mention what are the file extensions for razor views?
For razor views the file extensions are
ü  .cshtml: If C# is the programming language
ü  .vbhtml: If VB is the programming language

29) Mention what are the two ways for adding constraints to a route?
Two methods for adding constraints to route is
ü    Using regular expressions
ü    Using an object that implements IRouteConstraint interface

30) Mention two instances where routing is not implemented or required?
Two instance where routing is not required are
ü  When a physical file is found that matches the URL pattern
ü  When routing is disabled for a URL pattern



Tuesday, September 15, 2015

Real Time Example of Singleton Design Pattern

What is Singleton Design Pattern:

Singleton pattern ensures that a class has only one instance and provides a global access to it.


Code Implemented using C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SingletonSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Singleton obj1 = Singleton.Instance();
            Singleton obj2 = Singleton.Instance();
            Singleton obj3 = Singleton.Instance();
            Singleton obj4 = Singleton.Instance();

            if (obj1 == obj2 && obj2 == obj3 && obj3 == obj4)
            {
                Console.WriteLine("Objects are the same instance");
            }

            // Wait for user
            Console.ReadKey();
        }
    }

    class Singleton
    {
        private static Singleton _instance;

        protected Singleton()
        {

        }

        public static Singleton Instance()
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }
            return _instance;
        }
    }
}

Thursday, September 10, 2015

Singleton Design Pattern in C#


Singleton Design Pattern?

A Singleton Ensures a class has only one instance and provides a global point of access to it.
A single constructor, that is private and parameterless.
The class type is sealed.
A static variable that holds a reference to the single created instance, if any.
A public static means of getting the reference to the single created instance, creating one if necessary.

The important advantages of a Singleton Pattern are listed below:
  • Singleton can be lazy loaded.
  • Singleton helps to hide dependencies.
  • Singleton pattern can be implemented interfaces.
  • Singleton can be also inherit from other classes.
  • Singleton has Static Initialization.
  • Singleton provides a single point of access to a particular instance, so it is easy to maintain.
  • Singleton can be extended into a factory pattern.



Singleton Design Pattern Disadvantages 

  • Hard to switch for a mock object(Unit testing)
  • This pattern reduces the potential for parallelism within a program

Monday, May 7, 2012

How to Update on LINQ to SQL and LINQ to Entities Roadmap


  Update on LINQ to SQL and LINQ to Entities


   Since the release of LINQ to SQL and the Entity Framework, many questions have been raised about the future plans for the technologies and how they will relate to each other long term.
During this week of PDC we are now at a point, with the announcement of Visual Studio 10 and the .NET Framework 4.0, that we can provide more clarity on our direction.

We have seen great momentum with LINQ in the last year.  In .NET Framework 3.5 we released several LINQ providers, including LINQ to SQL which set the bar for a great programming model with LINQ over relational databases.  In .NET 3.5 SP1, we followed up that investment with the Entity Framework enabling developers to build more advanced scenarios and to use LINQ against any database including SQL Server, Oracle, DB2, MySQL, etc.

We’re making significant investments in the Entity Framework such that as of .NET 4.0 the Entity Framework will be our recommended data access solution for LINQ to relational scenarios.  We are listening to customers regarding LINQ to SQL and will continue to evolve the product based on feedback we receive from the community as well.

ASP.NET Web Programming Using the Razor Syntax


1. You add code to a page using the @ character

The @ character starts inline expressions, single statement blocks, and multi-statement blocks:

<!-- Single statement blocks  -->
@{ var total = 7; }
@{ var myMessage = "Hello World"; }

<!-- Inline expressions -->
<p>The value of your account is: @total </p>
<p>The value of myMessage is: @myMessage</p>

<!-- Multi-statement block -->
@{
    var greeting = "Welcome to our site!";
    var weekDay = DateTime.Now.DayOfWeek;
    var greetingMessage = greeting + " Today is: " + weekDay;
}
<p>The greeting is: @greetingMessage</p>
This is what these statements look like when the page runs in a browser:
You can find more details

ASP.NET MVC 3: Introducing Razor view engine


ASP.NET MVC 3: Introducing Razor view engine

ASP.NET MVC 3 brings us new view engine called Razor. Razor view engine was made available with WebMatrix first beta. Razor brings us new and very short syntax for writing views. In this posting I will introduce you shortly ASP.NET MVC Razor view engine.

New ASP.NET MVC project type

There is new ASP.NET MVC project type for Razor projects so you can start new application with Razor support already there.



The other options are project with ASPX based views and empty ASP.NET MVC project. As I am going to write sample application that uses Razor then it is not hard to guess which option I chose.

Razor files

New ASP.NET MVC Razor application is created like default ASP.NET MVC web application. The difference is that views are using Razor view engine. Project structure at file system level is same as before as you can see if you take a look at image on right.

There are some things you should know at this point:

Extension of Razor based views is .cshtml for view that use C# and .vbhtml for views that use VB.NET.
Files that cannot be shown by direct requests (master pages, partial views etc) have underscore (_) in the beginning of their names.
So if you try to make the request to _Layout.cshtml (this is master page) you will get error from server.

You can also see that there are controllers and models folders – things you don’t see in WebMatrix projects.

Razor syntax

Razor syntax is different from what we have seen this far. Razor provides us with way shorter and cleaner syntax and this is the reason why we should consider using it in our ASP.NET MVC projects. After playing with WebMatrix and Razor based pages I was pretty happy with Razor because my views looked cleaner than before.

Here is the example of Razor based view. This is the same Account/LogOn view that comes also with usual ASP.NET MVC default application. Although there is no syntax highlight yet you get the point.


Click on image to see it at original size.

Basically the rules are simple: everything that starts with @ is server-side code. If it is some known language structure that has body then it must be followed by { and }. Between them you can write whatever you want. Okay, there are more rules but all this is documented in WebMatrix tutorial Introduction to ASP.NET Web Programming Using the Razor Syntax.

Friday, May 4, 2012

MVC3, Entity Framework, Code-First with existing Database and few more..


Introduction
In this whitepaper, I will walk you through developing a simple MVC 3 application architecture using Entity Framework’s code first technology. Later hopefully you can evolve this to be an architecture that you can use for small to mid-size web application development.
Try to read this from start to the end and that way you will be able to gradually build the architecture together with me.
Pre-Requisites
Visual Studio 2010
SQL Server 2005/ 2008
Entity Framework
MVC 3
Create the Database
In real world scenario, the Code-First Technique does not encourage you to create a database at all. When you code the models, the system creates the respective database for you. However it does have its own issues, and out of the issue list, the most difficult to live with is, it re-create the whole database every time the DB schema changes. This made you lose the existing data in the database. So I don't want to deal with that hassle, hence, as a work-around we will be taking a different approach. We use the code-first technique, but with an existing database. So as the first step of this unlike it was with regular code first technique, you have to create the database. What you see below is a simple database I have created for me to do this architecture demonstration.
In general when you create a database, the following few best practices are good to follow
Let the composite table have its own primary key.
Use field ‘IsActive’ to avoid physical deletion of records from the database. If not you will ended up losing vital information when records are deleted.
As a habit use the field ‘Name’ to describe the table record. This can be used as the record descriptor when displaying records to the user.
Create a MVC3 Projects
In this demo I will be using ASP.NET MVC3 Web Application, so let’s create a project and name it as “MVC3Demo”. Let’s also make it a ‘Razor’ Internet Application.

I decided to have a separate project for the business logic code. So let's create class library type project with the name ‘MVC3Demo.Bll’.
Examine the ‘Web.Config’ of the MVC Web Project
The ‘Web.Config’ of our Web project has a connection string already defined and if you examine that closely, you will notice that the connection string with the name ‘ApplicationServices’ is by default using the SQL-EXPRESS database, which is installed with the visual studio 2010 itself. This configuration setting will creates a database inside the ‘App_Data’ folder for you. This is where the system store application services, such as membership service (if you create a new user in the MVC sample project, then it uses the member ship service, to be precise ‘AspNetSqlMembershipProvider’, to create those users in auto-created SQL Express database) related records. However we don’t want to use that database, so let us modify it and also add another connection string for our database that store our system's data objects.
The modified web configuration file will look like this..
Now, with this change, we added another entry with the name ‘DemoDbContext’ and you need to use this very same name to name the database context class that we create to communicate with the database via entity-framework. This context class has to be created by inheriting the .net framework system class named ‘DbContext’. This way the system auto-look for a configuration tag with the name of the class that inherits ‘DbContext’ to find out the connection string details. Additionally in our case we decide to keep the application service setting untouched, so that we have the option of even using a separate database for our role and profile management.
Create ‘MemberShip’ Database
You need to use the command named ‘aspnet_regsql’ to newly create the membership database in our data-base server. In order to do that, let’s go to Star >> ‘All Programs’ >> ‘Microsoft Visual Studio 2010’ >> ‘Visual Studio Tools’ >> ‘Visual Studio Command Prompt (2010)’ and type 'aspnet_regsql'. This will drive you through a wizard and let you create the ‘AccessControlDemo’ database in for your database.  
Run the Project and verifies that new users can be registered with the system and you can login to the system with those newly created user.
Install ‘EntityFramework’ Package for your BLL Project
Since our business logic layer is a class library type project, you do not have required reference for it to be the entity-framework back end. You can use the Library Package Manager, if you have it (it installs automatically with MVC 3.0) to install required 'entity-framework dll' for this project. In order to do that, from within your project in Visual Studio 2010, go to Tools > Library Package Manager > Package Manager Console. In the console, after the "PM>" prompt, type “install-package entityframework” and this will install the package and add the ‘EntityFramework’ reference to your WEB project. Use the Installed location and reference that ‘EntityFramework.Dll’ to your BLL project.

Create ‘DemoDbContext’ Class
As stated few times before, this has to be created by inheriting the ‘DbContext’ Class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
namespace MVC3Demo.Bll
{
    public class DemoDbContext : DbContext
    {
    }
}
Once this is done, you have almost complete the design framework for your project. Remainder is all about building your system on top of this established framework.
Create Model Classes
These model classes are pretty much like the model classes that you have in the MVC web project itself. However in this case we must create them to tally with our database tables. There has to have separate model classes for each table and there has to have properties of same type as fields of the tables. This separation will allow me to share my 'Models' and model access logic across many other projects too.
When you develop by this technique, you need to be extra careful when naming models and their respective properties. One misspell record will break the whole system and to make it worst the system generated errors around this region is not a help at all.
So having that in mind, let me creates a class with the name ‘Student’. Use 'Copy' and 'Paste' as much as possible to avoid typos. I use to copy the table records like this and..
Paste them on to my code like this..  

and then modify it to be like this…

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace MVC3Demo.Bll.Models
{
    [Table("Student", Schema = "dbo")]
    public class Student
    {
        [ScaffoldColumn(false)]
        public int StudentId { get; set; }
        [Required]
        [StringLength(50, ErrorMessage="{0} cannot exceed {1} characters")]
        public string Name { get; set; }
        [Required]
        public int Age { get; set; }
        [Required]
        [StringLength(150)]
        public string Address { get; set; }
        [Required]
        [DisplayName("Registered Date")]
        public DateTime RegisteredDate { get; set; }
        [NotMapped]
        public bool SeniorStudent
        {
            get
            {
                DateTime today = DateTime.Now;
                TimeSpan tSpan = today.Subtract(RegisteredDate);
                return (tSpan.TotalDays > 365);
            }
        }
        [Required]
        [DisplayName("Is Active")]
        public bool IsActive { get; set; }
        public string Description { get; set; }
    }
}
Here is an important point, I have used attributes to include validation logics. Not only that you can have respective error messages define and associate them with the property. In Addition to that, you have the option of having new properties that are not in the database define inside the class with a special attribute (see the 'NotMapped' attribute) as well. The property named, ‘SeniorStudent’ is one such record. In that case you need to mark that with ‘NotMapped’ attribute. To find out more about property attributes, please look at link. msdn.
Just by following the same pattern you can create model classes for the other two tables as well, that is for the table with the name ‘Course’ and ‘StudentCourse’.
Educate the Code to Relate Related Classes.
Now, you may wonder how the relationship in-between tables are been defined here. That is pretty easy, you can educate the model to maintain its relations like this..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MVC3Demo.Bll.Models
{
    public class StudentCourse
    {
        public int StudentCourseId { get; set; }
        public int CourseId { get; set; }
        public Course Course { get; set; }
        public int StudentId { get; set; }
        public Student Student { get; set; }
    }
}
Since the 'StudentCourse; has a many-to-one relationship with both Student and Course class. You need to define 'Student' and 'Course' object inside the 'StudentCourse' class. Tip: Look for Id type properties and as a general practice, add a property with the same name right below it.
Go to 'Student' and 'Course' class and add a property of type ICollection to indicate the many side of the one-to-many relationship.
See how the ‘Course’ class looks ..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MVC3Demo.Bll.Models
{
    public class Course
    {
        public int CourseId { get; set; }
        public string Name { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public int Period { get; set; }
        public bool IsWeekEnd { get; set; }
        public bool IsActive { get; set; }
        public ICollection<StudentCourse> StudentCourses { get; set; }
    }
}
Note: We have used this technique to develop few systems in some of the places I worked for and some of these systems are now run in production environments. In development stage, when naming the properties, we always recommended copy & paste of the name as a small typo often leads us to errors that are very difficult to track. However this technique is proven to be good for architecting small to mid-size systems.
Create Controllers
Just compile the ‘Mvc3Demo.Bll’ and add its reference to our main web project. Now compile the web-project, as when not compiled the add controller wizard does not show the modification done in referenced projects. (I believe Microsoft is aggressively working on some of these minor issues that we see in this version of the release). Then, right click on the controller and fill the respective fields to create the ‘Controller’ and the associated ‘Views’ for our models with names 'Student', ‘Course’ and ‘StudentCourse’.
Compile it and see if everything works. There is one more final adjustment needed. If you run this project as is and try to create a new ‘Course’ then you will get "Invalid object name 'dbo.Courses'" error message. This is because the name of the tables in our database is singular but the context is having plural names for the respective lists that directly match with tables. To avoid this you need to modify the 'DemoDbContext' class as given below.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using MVC3Demo.Bll.Models;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MVC3Demo.Bll
{
    public class DemoDbContext : DbContext
    {
        public DbSet<Student> Students { get; set; }

        public DbSet<course /> Courses { get; set; }

        public DbSet<studentcourse /> StudentCourses { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<pluralizingtablenameconvention />();
        }
    }
}
Go to the ‘Global.asax’ file and modify the register route method to point the system to 'Student' Index page.
Then run the project and see if everything all right..
Let’s now look at the ‘StudentCourse’ create view and see how the required dropdown box are being automatically created..
Now with this, we have completed developing a basic system. However if you look at the three controller classes, you will see that there are duplicate code being written. To improve the overall quality of the code, I decided to add a abstract controller class. That way I can avoid duplicated code, and have a better architecture in place for the system. This way I can allow newly joining developers to easily adjust to the code and write high-quality codes with very little learning curves.
Create an Abstract Controller Class
In the process of creating this class, I thought of doing few more additional refactoring as noted below..
Added a separate folder called Common, and added few classes that you may want to commonly use across any project you do to this folder. This includes exception logging, handling of cookies, handling of web.config's application settings data and a class to have all commonly used strings.
In addition to this, I decided to add two extensions to the same Common folder. I hope that may come handy at latter part of this code. One extension is for ‘Query’ class and another is added for ‘View’ class.
Note: As you develop multiple projects, the classes you find in this folder can easily be grown to a separate project itself. Such projects can be grouped under your company name. As an example if your company name is XYZ then common project can be named as ‘Xyz.Common’ and let all the project your company develop reference this project. In this way you can set companywide standard for areas of which such standards are applicable.
Added a separate folder called ‘Libraries’. This will keep all third party DLLs that are being referenced by this project. This way you can avoid some of the common DLL reference related errors that you get after deploying project in to the production environment.
Added another class called ‘ConfirmationViewModel’ to Web projects 'Model' folder. This is just to demonstrate how to call a shared view for deletion of records. You will see this being used later..
With these refactoring, I manage to remove almost all the duplicated codes from my controller class and implement them in my generic abstract class. Finally, the fully re-furbished ‘CourseController’ class look here.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC3Demo.Bll.Models;
using MVC3Demo.Bll;

namespace Mvc3Demo.Controllers
{
    public class CourseController : BaseController<Course>
    {
        public CourseController()
            : this(new DemoDbContext())
        { }

        public CourseController(DemoDbContext db)
            : base(db.Courses, db)
        {
        }

        protected override void LoadEditViewBags(Course entity)
        {
        }

        protected override void LoadAddViewBags()
        {
        }

        protected override Type LogPrefix
        {
            get { return this.GetType(); }
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
The important base controller is given below. A part of this code is taken from one of our internal company project. Hence that has few additional commonly used methods are being implemented. I have no issues even if you all decide to use this code in your projects too..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC3Demo.Bll;
using System.Data.Entity;
using System.Data;
using MvcContrib.UI.Grid;
using log4net;
using System.Reflection;
using System.Data.Entity.Infrastructure;
using Mvc3Demo.Common;
using Mvc3Demo.Models;

namespace Mvc3Demo.Controllers
{
    public abstract class BaseController<E> : Controller
        where E : class
    {
        protected DbSet<e /> dbEntitySet;
        protected DemoDbContext db;
        protected readonly ILog logManager;
        public BaseController()
        { }
        public BaseController(DbSet<e /> dbSet, DemoDbContext dbContext)
        {
            dbEntitySet = dbSet;
            db = dbContext;
            logManager = LogManager.GetLogger(LogPrefix);
        }

        public BaseController(DemoDbContext dbContext)
        {
            dbEntitySet = null;
            db = dbContext;
            logManager = LogManager.GetLogger(LogPrefix);
        }

        public virtual ViewResult Index()
        {
            return View(dbEntitySet);
        }

        //
        // GET: /entity/Details/5
        /// <summary />
        /// Get record of the entity from the database
        /// and pass it on to the Details 'PartialView'
        /// </summary />
        /// <param name="id" />Primary Key of the record to be searched</param />
        /// <returns /></returns />
        public virtual PartialViewResult Details(int id)
        {
            return PartialView(GetDetailsData(id));
        }

        //
        // GET: /entity/Create
        /// <summary />
        /// Create the empty View of the entity
        /// </summary />
        /// <returns /></returns />
        public virtual ActionResult Create()
        {
            GetCreateData();
            return View();
        }

        //
        // POST: /entity/Create
        /// <summary />
        /// newly create the entity object in the database. calls to the 'GetCreatePostBackData'
        /// and then call to the 'LoadEditViewBags' and fianlly return a 'View'
        /// </summary />
        /// <param name="entity" /></param />
        /// <param name="DoNotRedirect" /></param />
        /// <returns /></returns />
        [HttpPost]
        public virtual ActionResult Create(E entity, bool? DoNotRedirect)
        {
            try
            {
                int i = GetCreatePostBackData(entity, DoNotRedirect);
                if (i < 0)
                {
                    LoadEditViewBags(entity);
                    return View(entity);
                }
                else
                    return Redirect(PortalCookie.Get(ConstString.URL_DATA, ConstString.URL_REDIRECT_TO));
            }
            catch (Exception e)
            {
                this.AddToMessage(e.Message, MessageTypes.Error);
                logManager.Error("Error in Controller", e);
                throw e;
            }
        }

        // GET: /entity/Delete/5
        /// <summary />
        /// Delete a record via Ajax delete popup
        /// </summary />
        /// <param name="id" /></param />
        /// <returns /></returns />
        public virtual ActionResult Delete(int id)
        {
            try
            {
                PortalCookie.Set(ConstString.URL_DATA, ConstString.URL_REDIRECT_TO, Request.UrlReferrer.ToString());
                ConfirmationViewModel confirm = new ConfirmationViewModel();
                confirm.Id = id;
                confirm.Action = "Delete";
                confirm.Controller = typeof(E).Name;
                confirm.OperationName = "Delete";
                if (Request.IsAjaxRequest())
                    return PartialView("Confirmation", confirm);
                else
                    return View("Confirmation", confirm);
            }
            catch (Exception e)
            {
                this.AddToMessage(e.Message, MessageTypes.Error);
                logManager.Error("Error in Controller", e);
                throw e;
            }
        }

        //
        // POST: /entity/Delete/5
        /// <summary />
        /// Once a delete is confirmed via the popup it will do the DB operation
        /// and relavent messages added to the view bag
        /// </summary />
        /// <param name="id" /></param />
        /// <returns /></returns />
        [HttpPost, ActionName("Delete")]
        public virtual ActionResult DeleteConfirmed(int id)
        {
            try
            {
                E entity = dbEntitySet.Find(id);
                dbEntitySet.Remove(entity);
                int i = db.SaveChanges();
                this.AddToMessagePlus(i + " record(s) Deleted Successfully!"
                    , MessageTypes.Success);
                return Redirect(PortalCookie.Get(ConstString.URL_DATA, ConstString.URL_REDIRECT_TO));
            }
            catch (Exception e)
            {
                this.AddToMessage(e.Message, MessageTypes.Error);
                logManager.Error("Error in Controller", e);
                throw e;
            }
        }

        //
        // GET: /entity/Edit/5
        /// <summary />
        /// Update a particular entity.
        /// </summary />
        /// <param name="id" /></param />
        /// <returns /></returns />
        public virtual ActionResult Edit(int id)
        {
            try
            {
                E entity = GetEditData(id);
                return View(entity);
            }
            catch (Exception e)
            {
                this.AddToMessage(e.Message, MessageTypes.Error);
                logManager.Error("Error in Controller", e);
                throw e;
            }
        }

        //
        // POST: /entity/Edit/5

        [HttpPost]
        public virtual ActionResult Edit(E entity, bool? DoNotRedirect)
        {
            try
            {
                int i = GetEditPostBackData(entity, DoNotRedirect);

                if (i < 0)
                {
                    LoadEditViewBags(entity);
                    return View(entity);
                }
                else
                    return Redirect(PortalCookie.Get(ConstString.URL_DATA, ConstString.URL_REDIRECT_TO));
            }
            catch (Exception e)
            {
                this.AddToMessage(e.Message, MessageTypes.Error);
                logManager.Error("Error in Controller", e);
                throw e;
            }
        }

        protected int EditEntity(E entity)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    UpdateTrackingData(entity, false);
                    db.Entry(entity).State = EntityState.Modified;
                    int i = db.SaveChanges();
                    return i;
                }
                return -2;
            }
            catch (Exception e)
            {
                logManager.Error("Error in Controller", e);
                return -1;
            }
        }

        protected int CreateEntity(E entity)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    UpdateTrackingData(entity, true);
                    dbEntitySet.Add(entity);
                    int i = db.SaveChanges();
                    return i;
                }
                return -2;
            }
            catch (Exception e)
            {
                this.logManager.Error("Db Related Error Occured", e);
                return -1;
            }
        }

        protected IEnumerable<e /> GetIndexData()
        {
            try
            {
                return UpdateIncludes(dbEntitySet).AsEnumerable();
            }
            catch (Exception e)
            {
                this.AddToMessage(e.Message, MessageTypes.Error);
                logManager.Error("Error in Controller", e);
                throw e;
            }
        }

        protected E GetDetailsData(int id)
        {
            try
            {
                return dbEntitySet.Find(id);
            }
            catch (Exception e)
            {
                this.AddToMessage(e.Message, MessageTypes.Error);
                logManager.Error("Error in Controller", e);
                throw e;
            }
        }

        protected void GetCreateData()
        {
            PortalCookie.Set(ConstString.URL_DATA, ConstString.URL_REDIRECT_TO, (Request.UrlReferrer == null)
                ? Request.RawUrl.ToString() : Request.UrlReferrer.ToString());
            LoadAddViewBags();
        }

        protected E GetEditData(int id)
        {
            PortalCookie.Set(ConstString.URL_DATA, ConstString.URL_REDIRECT_TO, Request.UrlReferrer.ToString());
            E entity = dbEntitySet.Find(id);
            LoadEditViewBags(entity);
            return entity;
        }

        /// <summary />
        /// CreateEntity is called and
        /// then relavent message is add to the view bag
        /// </summary />
        /// <param name="entity" /></param />
        /// <param name="DoNotRedirect" /></param />
        /// <returns /></returns />
        protected int GetCreatePostBackData(E entity, bool? DoNotRedirect)
        {
            int i = CreateEntity(entity);
            return AddCreateSatusMessage(DoNotRedirect, i);
        }

        protected int AddCreateSatusMessage(bool? DoNotRedirect, int i)
        {
            if (i == ConstString.ERROR_INT)
                this.AddToMessage("Error: No record(s) Created!", MessageTypes.Error);
            else if (i == ConstString.ERROR_INVALID_OBJECT_INT)
                this.AddToMessage("Warning: Some record(s) yet to be filled!", MessageTypes.Warning);
            else if ((DoNotRedirect.HasValue) && (DoNotRedirect.Value))
                this.AddToMessage(i + " record(s) Created Successfully!", MessageTypes.Success);
            else
                this.AddToMessagePlus(i + " record(s) Created Successfully!", MessageTypes.Success);
            return i;
        }

        /// <summary />
        /// EditEntity is called and
        /// then relavent message is add to the view bag
        /// </summary />
        /// <param name="entity" /></param />
        /// <param name="DoNotRedirect" /></param />
        /// <returns /></returns />
        protected int GetEditPostBackData(E entity, bool? DoNotRedirect)
        {
            int i = EditEntity(entity);
            return AddEditStatusMessage(DoNotRedirect, i);
        }

        protected int AddEditStatusMessage(bool? DoNotRedirect, int i)
        {
            if (i == ConstString.ERROR_INT)
                this.AddToMessage("Error: No record(s) Updated!", MessageTypes.Error);
            else if (i == ConstString.ERROR_INVALID_OBJECT_INT)
                this.AddToMessage("Warning: Some record(s) yet to be filled!", MessageTypes.Warning);
            else if ((DoNotRedirect.HasValue) && (DoNotRedirect.Value))
                this.AddToMessage(i + " record(s) Updated Successfully!", MessageTypes.Success);
            else
                this.AddToMessagePlus(i + " record(s) Updated Successfully!", MessageTypes.Success);
            return i;
        }

        private PagedViewModel<e /> createPageViewModel(GridSortOptions gridSortOptions
            , int? page, string sortColumn)
        {
            ShowCurrentMessage();
            return new PagedViewModel<e />
            {
                ViewData = ViewData,
                Query = dbEntitySet,
                GridSortOptions = gridSortOptions,
                DefaultSortColumn = sortColumn,
                Page = page,
                PageSize = Common.ConstString.PAGE_SIZE,
            };
        }

        private PagedViewModel<e /> createPageViewModel(GridSortOptions gridSortOptions
            , int? page, string sortColumn, DbQuery<e /> dbQuery)
        {
            ShowCurrentMessage();
            return new PagedViewModel<e />
            {
                ViewData = ViewData,
                Query = dbQuery,
                GridSortOptions = gridSortOptions,
                DefaultSortColumn = sortColumn,
                Page = page,
                PageSize = Common.ConstString.PAGE_SIZE,
            };
        }

        private void UpdateTrackingData(E entity, bool isNew)
        {
            this.UpdateTrackingData<e />(entity, isNew);
        }

        /// <summary />
        ///
        /// </summary />
        /// <param name="name" />Name of the view</param />
        /// <param name="value" />Select list to be assigned to a drop down box</param />
        /// <returns />BaseController itself</returns />
        internal BaseController<e /> AddToViewBag(string name, SelectList value)
        {
            ViewData[name] = value;
            return this;
        }

        /// <summary />
        /// If you have any dropdown boxes please use this method to load their list
        /// to respective view bags.
        /// </summary />
        /// <example />
        /// this.AddToViewBag("EmployeeId", new SelectList(db.Employees, "EmployeeId", "EPFNo"))
        /// .AddToViewBag("DowntimeReasonId", new SelectList(db.DowntimeReasons, "DowntimeReasonId", "Name"))
        /// </example />
        protected abstract void LoadAddViewBags();

        protected abstract void LoadEditViewBags(E entity);

        protected virtual IQueryable<e /> UpdateIncludes(DbSet<e /> dbEntitySet)
        {
            return dbEntitySet.AsQueryable<e />();
        }

        protected void UpdateTrackingData<t />(T entity, bool isNew)
        {
            PropertyInfo pInfoMBy = entity.GetType().GetProperty(ConstString.PROPERTY_MODIFY_BY);
            if (pInfoMBy != null)
                pInfoMBy.SetValue(entity, Convert.ChangeType(User.Identity.Name, pInfoMBy.PropertyType), null);
            PropertyInfo pInfoMDate = entity.GetType().GetProperty(ConstString.PROPERTY_MODIFY_DATE);
            if (pInfoMDate != null)
                pInfoMDate.SetValue(entity, Convert.ChangeType(DateTime.Now, pInfoMDate.PropertyType), null);
            PropertyInfo pInfoABy = entity.GetType().GetProperty(ConstString.PROPERTY_ADDED_DATE);
            if (pInfoABy != null)
                pInfoABy.SetValue(entity, Convert.ChangeType(DateTime.Now, pInfoABy.PropertyType), null);
        }

        /// <summary />
        /// Return this.GetType(); This name is used to trace
        /// error locations of the log message write via log4net library.
        /// </summary />
        protected abstract Type LogPrefix
        {
            get;
        }

        public class CommonMessage
        {
            public CommonMessage()
            {
                this.Message = "";
                this.MessageType = MessageTypes.None;
            }

            public CommonMessage(string message, MessageTypes mType)
            {
                this.Message = message;
                this.MessageType = mType;
            }
            public string Message { get; set; }
            public MessageTypes MessageType { get; set; }
        }

        public CommonMessage GetFromMessagePlus()
        {
            string[] tempArray = TempData.GetMessageSummary();
            if (tempArray == null)
                return null;
            if (tempArray.Length > 0)
            {
                string[] mesgs = tempArray[0].Split('|');
                int t;
                if (int.TryParse(mesgs[1], out t))
                    return new CommonMessage(mesgs[0], (MessageTypes)t);
            }
            return null;
        }

        public void AddToMessagePlus(string message, MessageTypes mtype)
        {
            TempData.AddStatusMessage(message + "|" + (int)mtype);
        }

        public void ShowCurrentMessage()
        {
            CommonMessage temp = GetFromMessagePlus();
            if (temp != null)
                AddToMessage(temp.Message, temp.MessageType);
        }

        public void AddToMessage(string message, MessageTypes mtype)
        {
            switch (mtype)
            {
                case MessageTypes.Success:
                    {
                        ViewBag.successbox = message;
                    } break;
                case MessageTypes.Warning:
                    {
                        ViewBag.warningbox = message;
                    } break;
                case MessageTypes.Error:
                    {
                        ViewBag.errormsgbox = message;
                    } break;
            }
        }
    }

    public enum MessageTypes
    {
        Error,
        Warning,
        Success,
        None
    }
}

Make the Grid Sortable
There are many fancy grid views around that can be used with MVC2 razor views. Yes, as you all know that area need lot more improvements too (over to MSFT). In my view point, out of the lot, the jQuery grid is the best but I thought of going with a more basic simpler ‘MvcContrib.Gird’ for this..
You can find out more about how to integrate ‘MVCContrib’ grid here http://mvccontrib.codeplex.com/wikipage?title=Grid
In the process of integrating the grid, I had to remove the ‘Index’ method (Action) implementation from my abstract class. That creates ambiguity between that and the new method that I wanted in the ‘CourseController’ class. So If I am go with ‘MVCContrib’ grid I have two possible design options,

Remove the Index method implementation from the abstract base controller and have that implemented in the specific controller classes.
Have a new view defined do the action implementation for it in the specific controller while preserving the ‘Index’ method of the abstract controller class.