How to use DebugView to Log Entity Framework

In this post I will show you to use DebugView to log the Entity Framework. For detail discussion on the same topic you may want to learn more here:

Logging in Entity Framework on Steve Smith Blog

Profiling Database Activity in the Entity Framework by Julie Lerman

Download DebugView , unzip it and Run it as administrator. In Capture menu select the options as shown in below image,


Once the debugview is configured, you should configure the DataContext class as shown below. Enable database log to print on the debug window.


As the last step run the application using Entity framework without using Visual Studio or without attaching Visual Studio Debugger. In Visual Studio run the application using Ctrl+ F5. You should able to view the Entityframework log in Debugview as follows:


The Debugview can be your good friend when you stuck with performance issues and want to log the queries.

Happy Coding.

Work with ASP.NET MVC 5 Areas from different projects

Read full article on Falafel blog

While working on an ASP.NET MVC 5 application, I came across a requirement to use an Area from one project in another project. For example: I have a project A and a project B. I need to use an Area which is part of project B inside of project A. In this post I will discuss how this can be achieved.

To start with, let us say I have an MVC project AreaDemo with the structure as follows:


Read full article on Falafel blog

Using AutoMapper : Getting Started

Read full article on Falafel blog

I have often seen developers use the LINQ SELECT statement to create a new instance of one class from an existing instance of another class. There are many scenarios when you may have to do this, for example:

  • Creating the domain class instance from the entity class instance
  • Creating the DTO class instance from the entity class instance
  • Creating the POCO class instance from the entity class instance etc.

To do this, developers often use the select statement or manually convert a class object to another class object. Let’s look at an example:

Read full article on Falafel blog

Walkthrough: Login with Twitter Account in ASP.NET MVC 5 APP using ASP.NET Identity 2.0

ASP.NET Identity 2.0 simplifies task of social authentication in an ASP.NET MVC App at the great extent. There are lot to learn about ASP.NET Identity 2.0 and in further posts I will cover that. However In mean time if you are curious you can find the resources for ASP.NET Identity 2.0 here

To start with I created an ASP.NET MVC Application in Visual Studio 2013 y choosing MVC project template as follows:


Great, once the project is created next you need to configure Twitter for the application. To start with navigate to and select Create New App as shown below:


To create the Twitter application fill the form as follows. Off course you should provide Name, Description and Website information as of your application. Callback URL filed is worth discussing here, for development environment use instead of localhost as the server for Callback URL. For any other server give fully qualified server name. To create the new Twitter application form can be filled as follows:


That’s it. Now click on API Keys and copy the API Key and API Secret, you will need them in the application.


At the last step you need to open the project and browse to the App_Start folder. In this folder you will find a file Startup.Auth.cs. Open this file and uncomment the code app.UseTwitterAuthentication. You should also provide the consumerKey and consumerSecret key from Twitter here. (we created these keys in previous steps)



This is it Press F5 to run the application. And click on Login, you should see the Twitter option in Use another Service to log in.


Click on the Twitter option and you will be asked to authorize the app.


Once authorization is done, you can register with the Twitter username.


Now you are logged in to the application using Twitter account. So as you see ASP.NET Identity 2.0 makes it super easy to work with social authentication in the ASP.NET MVC or the ASP.NET application.

In further posts, I will share more on ASP.NET Identity 2.0 learning. Happy Coding.

User Instance login flag is not allowed when connecting to a SQL Server instance: Solved

While working with an ASP.NET MVC application I encountered following exceptions:


Exception clearly says that user instance login flag is not allowed when connecting to a SQL Server instance. For sure this error is related to SQL Server instance I am working on in this particular application. I examined the connection string in the web.config file.


There are two important points about this connection string:

  1. It points to local SQL Server database.
  2. User Instance is set to true

All local database runs under user instance and hence they don’t allow to configure user instance value in the web.config file. Removing User Instance entry should solve this problem. I modified connection string as follows:


And changing this resolved the issue. Hope it helps.

Three simple steps to use Kendo UI Web in ASP.NET MVC 5

I have seen the developers struggling to work with the KendoUI Web in an ASP.NET MVC application. In this post I will show you three steps required to get working with the KendoUI Web in the ASP.NET MVC application. At the end of the post we will take a look on working with the autocomplete widget.

Let us follow the steps as given below:

Step 1: Add Reference

Add the reference of KendoUI Web the project using Package Manager Console. After successful addition, you should find reference added in the Content folder and the Scripts folder.


Step 2: Bundle the required files

Open BundleConfig.cs file. In this file add two entries, one for the KendoUI Web scripts and other for Kendo UI Web CSS.

Add the script entry as follows:

bundles.Add(new ScriptBundle("~/bundles/kendoui").Include(

Next add the CSS files for KendoUI widgets. CSS for all the widgets can be bundled as follows:

    bundles.Add(new StyleBundle("~/Content/kendo/css").Include(

Step 3: Refer the Bundles

Once bundle for the Kendo UI Web has been created, you need to add them on the layout file. That can be added as follows:


By default you will find the jQuery bundle at the end of the layout file. To work with Keno UI widgets, you should move the jQuery bundle at the top of the file and as well include the bundles of KendoUI CSS and Scripts.

These are the three steps you should follow to work with KendoUI in an ASP.NET MVC 5 application.

Use KendoUI Web Widgets

Now let us see the autocomplete widget in the action. I have created controller returning JSON data as follows:

        public ActionResult Index()
           return View();

        public ActionResult GetMP()
            var result = from r in _db.GetMPDetails()                      
                         select r;            
            return Json(result, JsonRequestBehavior.AllowGet);

We will bind returned JSON from the GetMP() action to the autocomplete widget. On the razor view you can create autocomplete as follows:

<input id="mp" />

<script type="text/javascript">
    $(document).ready(function () {
        //create AutoComplete UI component
            dataTextField: "Name",
            filter: "startswith",
            minLength: 3,
            dataSource: {
                transport: {
                    read: "/Mpsearch/GetMP",


Make sure the View is using the layout file in which you added reference of the bundles.


As we seen in this post that working with Kendo UI Web widgets are as simple as following above three steps:

  1. Add reference of Kendo UI Web
  2. Create the bundles
  3. Add bundles reference in layout page

I hope this post is useful. Happy coding.

Keep your code DRY

Other day my Boss was reviewing the code written by me. He had a feedback, keep the code DRY. It was great feedback, and I thought why not to share with you that what does DRY mean?

DRY stands for Do not Repeat Yourself.


To understand it better let is consider below code snippet:


I am fetching a particular movie on basis of the id. As you notice this code is inside Details method. Next in another method Edit in the controller and I am doing the same fetching a particular movie on basis of the id as shown below:


As you clearly notice that I am repeating the code in the same class hence CODE IS NOT DRY in above scenario. The code should not be repeated and should be kept in repository class. We could have a function FindById() in MovieRepository class and both the methods will call FindById(). A common function to find the movie by id can be created as follows:


And then both methods of Controllers can use them as follows:


In the layered architecture approach DRY code is very essential for robust software development. I hope now you have better understanding of having code DRY and you will follow this approach.

Happy Coding.

Understanding IEnumerable and IQueryable in C#

Read full article at Falafel blog

I see developers are not that confident about usage of the mentioned interfaces. In this post, I am going to discuss basic differences among IEnumerable<T> and IQueryable<T> and in which scenario to use what.


The IEnumerable<T> is used to iterate a read only collection. It has only one method GetEnumeartor() which allows you to iterate the read only collection using a foreach loop. It only iterates in the forward direction. IEnumerable <T> is defined in as follows:


Read full article at Falafel blog

Refactoring the ASP.NET MVC Application to the Onion Architecture

Source Code on GitHub


Any application should be fairly tested before it shipped to the customer. Biggest challenge in the testing is tightly coupled behavior of the UI with the Application Logic and further to the Database logic .Good testable systems are the one in which presentation layer does not directly depends on the application logic and the database logic. Application logic should be independent of UI such that both can be tested independent of each other. For example you should not call DBContext methods on click event of a button from the UI. If you do so, then the UI is tightly coupled with the database layer and any change in the database logic will impact the UI. Other disadvantage is that to unit test the database logic you need the UI. Testing of various components of the application is as important as building the components of the application. You should able to do the Unit Testing without the need of the database. Now let us assume, you are creating an ASP.NET MVC application and you have written all the database codes (fetching records or inserting etc.) in the controller itself. Your application may be up and running but in this pattern, you cannot unit test the controller without database. Other problem could be, you may have duplicate the database codes in different controllers and certainly you would not like that. There are challenges with duplicate codes. One change in database logic may require you to do multiple changes in the code. Other problem is your controller is aware of the underlying database source and if in future you change the data source, the controller will be affected and again this is not the best practice to create an ASP.NET MVC application. These problems are not only restricted to MVC but can exist in any kind of applications which is having database logic tightly coupled with the application itself.

You may want to read on Falafel blog :

Use Types from a Project without Referencing It
Three steps to use jQuery UI in ASP.NET MVC 5
Work with ASP.NET MVC 5 Areas from different projects
Types of ASP.NET MVC Views

Let us summarize problems we discussed above:

  • Duplicate database access codes
  • Hard to maintain the codes
  • Difficulties in Unit Testing
  • Hard to replace type of data sources
  • Tough to put centralized database access related policy

Usual approach we follow is the Layered Architecture. In layered architecture the presentation layer is transitively depends on the database layer and that does not solve the problem we discussed earlier in an absolute way.

Onion Architecture is the preferred way of architecting application for better testability, maintainability and dependability on the infrastructures like databases and services. This term was first coined by Jeffery Palermo in his blog back in 2008.

Learn more about the Onion Architecture in the series of blog posts by Jeffery Palermo

  • In the Onion Architecture layers talk to each other using the Interfaces. Any concrete implantation would be provided to application at the run time.
  • Any external dependency like database access and the web service call are part of the external layers
  • UI is part of the external layers
  • Objects representing domain are part of the internal layers or they are the centers
  • External layers can depend on the layers internal to it or central to it
  • Internal layer should not depend on the external layers.
  • Domain object which is at the core or center can have access to the both the UI and the database layers.
  • All the coupling are towards the center
  • Codes which may change often should be part of the external layers

I would recommend you to watch Steve Smith course on same topic at Pluralsight for better understanding on the concepts of the Onion Architecture. I will not go much into discussion of Onion architecture and jump into showing you refactoring ASP.NET MVC application to use the Onion Architecture.

Create N-Tier application using C# by Steve Smith


Let us implement Repository Pattern in MvcMovieRTM ASP.NET MVC Application. You can download this app from official Microsoft site here . After downloading, open the app in Visual Studio and in Package Manager Console run the command update-database. Go ahead and press F5 to run the application. Navigate to Movie Controller and you should able to see list of movies, can edit, delete and create new movie. We are going to refactor this application to adhere the Repository Pattern. Before we move ahead, let us examine the code in MoviesController.


As you see in the above code snippet that inside the controller we are directly accessing the database. All logics to fetch data from database is written right inside the controller and that makes the controller and the database access tightly coupled to each other. You cannot unit test Index action in isolation of database.

Refactoring to Repository Pattern

Follow the following steps to refactor the existing application:

Create two class library projects and give them name as MvcMovie.Infrastructure and MvcMovie.Core. In the project MvcMovie.Infrastructure all database related operation will be placed. In this example Entity Framework is used. So all Entity Framework dependency will be part of MvcMovie.Infrastructure project.

Setting up Infrastructure Project

Let’s start with moving the MovieDBContext class to the MvcMovie.Infrastructure project. Infrastructure project will contain all the database related classes and the operations. Since application is using Entity framework, we need to add the Entity framework reference in Infrastructure project. From Nuget manager add Entity framework package in the project. MovieDBContext class will look like as follows:



using System.Data.Entity;

namespace MvcMovie.Infrastructure
    public class MovieDBContext : DbContext

        public DbSet<Movie> Movies { get; set; }


Next create MovieRepository class in the Infrastructure project. This class will contain all the database operations. Essentially we will move operations which are directly working with MovieDbContext class from the MoviesController to MovieRepository class. After moving the Entity framework codes the MovieRepository class will look like follows:


using MvcMovie.Core;
using System;
using System.Collections.Generic;
using System.Data.Entity;

namespace MvcMovie.Infrastructure
    public class MovieRepository : IMovieRepository, IDisposable
        MovieDBContext db = new MovieDBContext();
        public IEnumerable<Movie> GetMovies()

                return db.Movies;


        public void Add(Movie m)



        public void Edit(Movie m)

                db.Entry(m).State = EntityState.Modified;


        public void Remove(int id)
                Movie movie = db.Movies.Find(id);


        public void Dispose()


Once MovieRepository class is created refactor it to extract Interface from this class. You need to move extracted interface to the MvcMovie.Infrastructure project.


Visual Studio will extract the IMovieRepository interface and put it inside the MvcMovie.Infrastructure project. Move the IMovieRepository interface to the MvcMovie.Core project. IMovieRepository will look like follows in MvcMovie.Core project:


using System;
using System.Collections.Generic;
namespace MvcMovie.Core
   public interface IMovieRepository
        void Add(Movie m);
        void Edit(Movie m);
        IEnumerable<Movie> GetMovies();
        void Remove(int id);

Do not forget to implement the IMovieRepository interface in the MovieRepository class. At this point of time if you go ahead and build the MvcMovie.Infrastructure project, you will get compile time errors. In solution explorer MvcMovie.Infrastructure project should look like follows:


Setting up Core Project

Move Movie class from the MvcMovie project to the MvcMovie.Core project. To work with data annotations add reference of System.ComponentModel.DataAnnotaions in the MvcMovie.Core project. Movie class should look like follows in core project:


using System;
using System.ComponentModel.DataAnnotations;

namespace MvcMovie.Core
  public class Movie

        public int ID { get; set; }

        [StringLength(60, MinimumLength = 3)]
        public string Title { get; set; }

        [Display(Name = "Release Date")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime ReleaseDate { get; set; }

        public string Genre { get; set; }

        [Range(1, 100)]
        public decimal Price { get; set; }

        public string Rating { get; set; }

You should have the IMovieRepository interface and the Movie class inside the MvcMovie.core project. In solution explorer the MvcMovie.Core project will look as follows:


Compile MvcMovie.Core project and add its reference to the MvcMovie and the MvcMovie.Infrastruture project. After adding reference of the MvcMovie.Core in the MvcMovie.Infrastructure project, you should able to successfully compile the MvcMovie.Infrastructure project.

Refactor MoviesController

Previously in the MoviesController class we were directly creating instance of the MovieDBContext and performing database operations. To follow Onion Architecture, controller will only know about the IMovieRepository and perform database operations using the IMovieRepository. Very first let’s create instance of the IMovieRepository

private IMovieRepository db = new MovieRepository() ;

Next any database operation will be performed on instance of MovieRepository. Some of the operations are as follows:

Fetch Genre

            var GenreQry = from d in db.GetMovies()
                           orderby d.Genre
                           select d.Genre;

Fetch All Movies

var movies = from m in db.GetMovies()
                         select m;

Add Movie


Edit Movie


Remove Movie


Replace various database operations in MoviesController with the code as shown above. As of now you should successfully able to run the application.

Inverting the Dependency

We are directly creating instance of the MovieRepository in the MoviesController which makes Controller tough for Unit Test. In this scenario to test the Controller, you need the database. We can solve this problem by inverting the control using any DI Container. You are free to use any DI container of your choice, however I am using Microsoft provided Unity Container. To use it add the Unity reference using Nuget Package Manger. In Unity.Config (located in the App_Start) folder register the type as given below:

  container.RegisterType<IMovieRepository, MovieRepository>();

Once type is registered you need to call the RegisterComponents() method of UnityConfig in the Application_Start() method of the Global.asax.cs as shown below:


As the last step refactor Controller as shown below:


If you remember in beginning we were directly creating the instance of the MovieDBcontext inside controller hence the controller was fully dependent on database and was making it tough to test it in isolation.

MvcMovie application has been refactored to Onion Architecture. Next task you may want to do, is to download the code discussed in this post from GitHub and start writing test.

Source Code on GitHub


We have refactored the application adhering to the onion architecture. Domain objects like Movie is at the center of the architecture and are the part of internal layers. The Infrastructure project in which we are working with database and database logics are part of the external layers. They depend on the centeral layers like core. UI or in this case the MVC application is also an external layer and depndes on the Core project. All layers are interacting to each other using the interfaces rather than the concrete definitions. You can very easily write Unit Test against the controllers using Fake or Mock without hitting the datbase. In future you can easily change data access technology from Enity Framework to something else without affecting the UI and the Core.


Source Code on GitHub

Learn more about the Onion Architecture in the series of blog posts by Jeffery Palermo