Resolving Dependencies in ASP.NET MVC 5 using Unity Container

In this post, I will show you how to use Unity Container in ASP.NET MVC 5 application. This post may be handy for you because the way Unity was used in MVC 4 has been changed in MVC 5. Assuming you already have ASP.NET MVC 5 application, you can start using Unity Container using Nuget. Right click on project and from context menu click on Manage Nuget Packages and search for Unity.mvc5. Click to install Unity.mvc5 package in ASP.NET MVC application.

clip_image002

In App_Start folder you will find UnityConfig.cs. UnityConfig is a static class with one static method RegisterComponents. In this method you need to register dependency. For example ASP.NET MVC 5 application I am working on, got MovieRepository class depended on IMovieRepository. You need to instruct unity that IMovieRepository should resolve to MovieRepository. You can do this by registering type in Unity Container. [See image below]

clip_image004

If you have more than one dependencies all should get registered to container in RegisterComponents function. After registering all dependencies call RegisterComponents function in Application_Start() of Global.asax.cs . This can be done as shown below,

clip_image006

Note:

In earlier version of ASP.NET MVC and UNITY, you might have seen BootStrapper.start(). In MVC 5 it has been changed to UnityConfig.RegisterComponents()

In Controller class now I can inject dependency simply as below,

clip_image008

This is what all you need to do to resolve dependency using Unity Container in ASP.NET MVC application. In further posts I will discuss how to use other IOC containers like Structuremap, Windsor etc.

Happy Coding.

Unable to index file: Permission Denied error in git add command

While working on an application, I had to commit changes to local Git Repository. It was usual task and I started with following command,

git add –A

To surprise git add command gave me error as shown in image below. Error message was clear that to a particular file there was Permission denied.

clip_image002

Note: I was working on a MVC application which had local database attached. Name of database was MoviesRTM.mdf.

I tried to commit using Visual Studio 2013 as well. Here also I got same error as shown in image below,

clip_image004

This can be solved by two ways either shutting down IIS Express or restarting Visual Studio. I was using IIS Express to host MVC application. You can shut down IIS Express by right click on IIS Express and click on Exit from context menu.

clip_image006

If this option is not working then try restarting Visual Studio.

Note: Restarting Visual Studio or Shutting down IIS Express may worked in this scenario because permission denies error was on a database file (extension mdf). And database was locally created.

After shutting down I was able to run git add command successfully.

Happy coding.

Getting started with Code First Approach and Entity Framework Migrations Commands

For better understanding on Entity Framework, I recommend you to read EF Series by Anders Abel on his blog here . I learnt lot from his post about Entity Framework. You may want to follow Julie Lerman for better learning on ADO.NET Entity Framework.

In this post we will walk through basics of Entity Framework migration commands and learn about Code First Approach. Entity Framework allows you to create database from plain classes. You can model your domain into classes and subsequently database can be created or updated from the model using Entity Framework.

We model domain into classes and database gets created form model classes is known as Code First Approach. Here you can create database from plain old classes. Model classes does not have to extend any base class etc. The other two approaches are,

  1. Model First Approach
  2. Database First approach

Code First Approach in Entity Framework reduce task of modelling database on designer and working with XML etc.

Let us start rolling, suppose we need to model School database. For this we have created two POCO classes as below.


Public class School
    {
        public int Id { get; private set; }
        public string Name { get; set; }

        public Icollection<Student> Students { get; set; }

    }

    public class Student
    {
        public int Id { get; private set; }
        public string Name { get; set; }
        public string  Grade { get; set; }
    }


School and Student classes are representing School and Students real time entities respectively. Next we need to create Context class. This class must inherit DbContext class.


Public class Context : DbContext
    {
      public Context() :base()
        {

        }
        public DbSet<Student> Students { get; set; }
        public DbSet<School> Schools { get; set; }
    }


Regardless what kind of application you are working with and following Code First approach, you need to add reference of EntityFramework. You can use NuGet manager to install EntityFramework library in project you are working.

image

When you execute code, surprisingly you will find database has been created. You may wonder that where Context database (we created class Context which is inheriting DbContext class) has been created? Let us go back to context class, we have not provided any connection string in constructor. In this case database would get created in local SQL Express comes with Visual Studio. Alternatively connection string name can be provided in constructor to create database on a particular database server. Connection string can reside in configuration file. You can launch Server Explorer to view created database. Let us go ahead and examine schema of created table,

Student table is created as below,

image

And School table being created as below,

image

EF is intelligent enough to construct primary key on the column with name Id. If you don’t have Id column then EF will search for column with *Id and construct that column as primary key. For example if there is a property EmployeeId in model class then EF will construct column EmployeeId as primary key.

Other thing you may notice that for string properties EF is creating columns with type nvarchar(MAX). You may not want this and have control on size of the columns in database. This is allowed in EF using data annotations. Let’s go ahead and modify POCO classes with data annotation.


Public class School
    {
        public int Id { get; private set; }
        [Required]
        [StringLength(50)]
        public string Name { get; set; }

        public Icollection<Student> Students { get; set; }

    }

    public class Student
    {
        public int Id { get; private set; }
        [Required]
        [StringLength(50)]
        public string Name { get; set; }
        [Required]
        [StringLength(10)]
        public string  Grade { get; set; }
    }


We have put data validation annotations like Required (in db null not allowed) and StringLength. Other data validation annotations are MaxLength and MinLength.

Let’s go ahead and run again to recreate or update database schema. On running application I got following exception. Poor me,

image

EF is throwing very clear error message. We can break error in message in two parts,

  1. Model backing Context has changed
  2. It has changed since database has created

It is suggesting us to consider Code First Migration. So let’s learn Code First Migration. Before we go ahead and explore various migration techniques, let’s have a look on Database initialization strategies. There are four database initialization strategies,

  1. CreateDatabaseIfNotExist
  2. DropCreateDatabaseIfModelChanges
  3. DropCreateDatabaseAlways
  4. Cutsom DB Initalizer

All options are self-explanatory. One option is to use DropCreateDatabaseIfModelChanges database initializer to get rid of above exception. Let’s go ahead and modify Context class by adding database initializer in constructor,


public class Context : DbContext
    {
      public Context() :base()
        {

            Database.SetInitializer<Context>(new DropCreateDatabaseIfModelChanges<Context>());

        }
        public DbSet<Student> Students { get; set; }
        public DbSet<School> Schools { get; set; }
    } 


Okay so we did not get any exception and database schema has been updated as well. You may notice Name column has been updated with length 50 and Nulls are not allowed.

image

All good? Not really because we have lost all the data. Since in database initializer we have used option to drop database and create again if model changed. I am sure you don’t like this option and must be looking for some better options.

Other option is to Enable Migrations. You can enable migration by EF command. You can run EF command from Package Manager Console. Enable Migrations run command

PM> Enable-Migrations

image

I have run command to enable automatic migration. Let’s go back to solution explorer, you will find a Migration folder is being added with a class Configuration.cs . This class got a seed method. Configuration class will look like below,


internal sealed class Configuration : DbMigrationsConfiguration<SchoolDbApplication.Context>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            ContextKey = “SchoolDbApplication.Context”;
        }

        protected override void Seed(SchoolDbApplication.Context context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = “Andrew Peters” },
            //      new Person { FullName = “Brice Lambson” },
            //      new Person { FullName = “Rowan Miller” }
            //    );
            //
        }
    }


As you see that,

  1. AutomaticMigrationEnabled is set to true
  2. There is Seed method which will get executed after migrating to the latest version. So if you want to have some default data after migration, you will write code in Seed method.

Let us consider another scenario that we want to add one more column in Student table and for that we need to add a property in Student class. Modified Student class will look like below,


public class Student
    {
        public int Id { get; private set; }
        [Required]
        [StringLength(50)]
        public string Name { get; set; }
        [Required]
        [StringLength(10)]
        public string  Grade { get; set; }
        [Required]
        public int Age { get; set; }
    }


I have added Age property with basic data annotation [Required]. Previously when we tried modifying class and later database we lost all the data. This time we don’t want to repeat the mistake. So after modifying model class, add a migration with a name. Let’s run a command and give a name Student_Age to newly added migration. You are allowed to give any name of your choice.

PM> Add-Migration Student_Age

image

Further if required you can change Model and include in the same migration by running the same command. Let us go ahead and explore solution explorer again. In solution explorer inside Migrations folder you will find somenumber_Student_Age.cs file. This class contains information about this particular migration. Remember that we gave name of the migration as Student_Age.

Namespace SchoolDbApplication.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class Student_Age : DbMigration
    {
        public override void Up()
        {
            AddColumn(“dbo.Students”, “Age”, c => c.Int(nullable: false));
        }
        
        public override void Down()
        {
            DropColumn(“dbo.Students”, “Age”);
        }
    }
}


There are two methods inside this class Up and Down method. In Up method a column being added to Students table whereas in Down method column is dropped. Don’t forget to run Update-database command to update model changes in database.

PM> update-database –verbose

image

This time you will find database has been updated and age column is added to Students table with no loss of data.

For complete reference of EF Migrations commands you may want to refer here

Summary

In this post we learnt Code First approach in ADO.NET Entity Framework and some of the EF commands. I left you reference to learn further on same subject also. I hope after learning this post you should able to understand what is going around various EF commands and don’t accidently delete data while updating the schema. In further posts I will talk about Custom DB Initalizer and other important bits of Entity Framework.

Happy Coding.

Getting Started with Git and GitHub

 

 

Read complete article on Falafel Blog

Who is not talking about Git or GitHub? In one of our recent user group meetings, someone asked how many Pull Requests have you done so far in any of open source projects on GitHub. I realized many developers in the room were puzzled with the phrase Pull Request. In this post I will explain some basic Git terminology and explore basic Git commands which will help you get started with Git. In a later post I plan to show you how you can work with Git-based Source Control and Visual Studio 2013.

Let us start with understanding basic terminologies:

Repository

A Repository  is a space where projects reside. Repository can be on a local computer or at an online host like GitHub or Team Foundation Server (TFS). If you are working in project then a Repository is basic unit of working . It will contain all the files, images etc. needed for the project. It should always contains a readme file, which describes the project

Read complete article on Falafel Blog

The call is ambiguous between the following methods in C#

I was writing some Unit Tests on default ASP.NET MVC Movie Application. Application can be created by following tutorials here http://www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started or alternatively you can download sample application as well. Okay so while writing unit test, I had to pass null value for id in Edit action. Compiler was not happy me passing null and I got compile time error as given in below image,

image

Error is clearly saying that there is ambiguous between two methods. On examining Edit action found it was overloaded,

  • Id parameter
  • Instance of Movie parameter

Now when I passed null, complier was not able to decide which overloaded Edit action needed to be called. Because null can be pass for integer id value and for object Movie as well. And that’s the reason complier was throwing compile time error.

How to solve it? Of course you can change definition of Edit action. But we may not want to do it. Other option is to forcefully pass null either as movie or integer id. Null can be passed as integer id as below,

image

Remember this solution not restricted only for MVC and can work in any code written using C#. So, the call is ambiguous between the following methods in C# can be resolved as easily as given discussed above.

Learn AngularJS Hour 5: All about $scope object

In hour 1 , we learnt to get started with AngularJS.

In hour 2 , we learnt about AngularJS Template.

In hour 3 , we learnt about two way bindings and filter.

On hour 4 , we learnt about $http service and making HTTP operations.

In 5th hours of series, we will learn about $scope in Angular. $scope is an object which connects View and Controller together.

 

image

To understand $scope better let us start with first angular app we wrote,

image

Above program ran and due to $rootScope of angular. When you don’t provide any $scope explicitly, angular works with $rootScope. To understand $rootScope better let us understand below diagram,

image

We have added attribute name in $rootScope under the main function. Main function can be considered as main method of angular app. Since attribute is added to $rootScope, it can be accessed anywhere on the view and we do not need controller to access this. Due to $rootScope hello world ng-model of textbox got rendered on the view with template {{name}}.

For complex application you will have to create explicit $scope. Consider we have a view as below,


<div ng-controller="authorController" >
        {{author.name}} is {{author.age}} old
    </div>

Here we have attach a controller object to div element of DOM in view. Now to make sure that author.name and author.age attribute is available on the view, we need to create explicit $scope. That can be created as below,


app.controller('authorController', function ($scope) {
    $scope.author = {
        name: "Dhananjay Kumar",
        age: 32
    };
});

Attribute author of authorController will be available to all child element of the div to which authorController is attached. For example consider below View, we are able to read value of author attribute in child div as well,

  <div ng-controller="authorController" >
        <div>
            I am in child div  <br/>
            {{author.name}} is {{author.age}} old
        </div>
    </div>

We can summarize few points about $scope as follows,

  • $scope ties view and controller together
  • $scope provides an execution context in which DOM element is bound
  • In context of MVC , $scope can be seen as model
  • View and model both have access of $scope
  • $scope holds data and functions from controller that should be displayed and get executed in view
  • $rootScope is top most scope in on DOM element with ng-app directive

In angular all the $scope are created with prototypal inheritance. All $scope has access to their parent scope. For above example $scope of authorController has access to $rootScope. On the view $scope of child controller can access attributes of parent controller. To understand it better, let us create two controllers. authorController is parent controller and childAuthorController is child controller. You can see in the child controller childAuthorController that author attribute of authorController


var app = angular.module('AuthorApp', []);

app.controller('authorController', function ($scope) {
    $scope.author = {
        name: "Dhananjay Kumar",
        age: 32
    };
});

app.controller('childAuthorController', function ($scope) {

    $scope.hello = function()
    {
        alert($scope.author.name);
    }
})


On the view we have two div, first div is attached to parent controller whereas second view is attached to child controller.


<div ng-controller="authorController" >
        <div ng-controller="childAuthorController">
            
            {{author.name}} is {{author.age}} old
            <button ng-click="hello()" class="button" >say Hello</button>
        </div>       
    </div>

You can see that we have access of parent controller attributes inside DOM element which is attached with child controller.

$scope work on prototypal inheritance in angular. Diagrammatically we can show that as follows,

image

This is the way $scope object works in angular. Even though it performs complex tasks like binding controller and view together at the end of the day it is simple JavaScript object. Having a good knowledge on $scope is big help in implementing complex angular applications. Happy coding.

Learn AngularJS Hour 4: service in AngularJS and making HTTP call using $http

In hour 1 of this series we learnt to get started with AngularJS.

In hour 2 of this series we learnt about AngularJS Template.

In hour 3 of this series we learnt about two way bindings and filter.

In this hour we will learn about,

  • · Using Services in Angular
  • · Calling remote service to load data

If you are following this hour series on AngularJS, you might have noticed that we are using local data for authors. Using Services in AngularJS, you can call a remote service. Here we are going to call a HTTP based (REST Service) service. You can use $http of AngularJS to call a remote service or to make a HTTP request.

image

So in controller we need to modify to make a call to the service. In below example service is returning JSON.

image

Let us see what is happening in above code,

  • $http service is making HTTP GET operation
  • Service is returning JSON data
  • $http service returns promise object having success method. In this method service response will be handled asynchronously.
  • In success method of promise object of $http service, Angular is assigning returned data to current scope and creating model named author
  • Parsing of returned data is done by angular.

As you might have noticed that to use a service we need to pass service as dependency in the constructor of Controller.

clip_image001

Dependency Injector of Angular provided services to controller. It works in three steps,

  1. Injector identifies $http as dependency of controller
  2. Injector checks whether instance of $http exist or not? if not creates new instance of $http
  3. Injector pass singleton instance to controller of service. In this case Angular dependency injector will check whether $http service singleton instance is passed to AuthorController or not?

image

So for your reference code from above discussion is given below. Module and Controller is created given below,


var AuthorApp = angular.module('AuthorApp', []);

AuthorApp.controller('AuthorController',
                      function ($scope, $http)
{
   
    $http.get('http://localhost:21800/Service1.svc/GetAuthors')
        .success(function (data)
        {
                 $scope.authors = data;
        });
    
});


And View is as below,


<!DOCTYPE html>
<html ng-app="AuthorApp">
<head>
    <title>Angular Demo</title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Author.js"></script>
</head>
<body ng-controller="AuthorController">

    Search: <input ng-model="searchtext">

    Sort:
    <select ng-model="sortorder">
        <option value="AuthorName">Name</option>
        <option value="age">Age</option>
    </select>

    <ul>
        <li ng-repeat="author in authors |
            filter:searchtext |
            orderBy:sortorder">
            {{author.AuthorName}}

       </li>
    </ul>
</body>
</html>


On the web page all the authors will be rendered as below,

image

We learnt how easy it is using Angular service to make a HTTP request. We also learnt about using Angular service like $http in application. Happy coding.

Convert List to List using ConvertAll in C#

I see many developers convert one list to another list using foreach. It is ok and get the job done but there is better way to convert one list to another list using ConvertAll();

Just to explain you scenario better, let us assume you got two classes as below. InternalStudent class is representing Student class internally in the project and this is not supposed to be exposed in Service etc.


public class InternalStudent
    {
        public string IName { get; set; }
        public int IAge { get; set; }
    }

Another class is Student


  public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

Now you have List of InternalStudents as below,


List<InternalStudent> lstInterStudent = new List<InternalStudent>
            {
                new InternalStudent {IName="dj",IAge=32},
                new InternalStudent{IName="pinal",IAge=36}
            };

Requirement is to convert List<InternalStudent> to List<Student>. Usually we convert one list to another list using foreach as given below,


List<Student> lstStudent = new List<Student>();
foreach(InternalStudent s in lstInterStudent)
            {
                lstStudent.Add(new Student
                    {
                        Name = s.IName,
                        Age = s.IAge
                    });
            }

There is no problem as such in this way of conversion from one generic list to another generic list. However there is better way to do this conversion.


List<Student> lstStudent = lstInterStudent.ConvertAll(x => new Student
                {
                    Age = x.IAge,
                    Name = x.IName
                });

We are using ConvertAll to convert one generic list to another generic list. I hope you find this post useful. Thanks for reading.

Learn AngularJS: Hour 3

In hour 1 of this series we learnt to get started with AngularJS.

In hour 2 of this series we learnt about AngularJS Template.

In this hour we will learn about,

  • Filter
  • orderBy
  • Two way binding

image

Now filter can be applied to repeater directive by providing option filter. In filter we need to set value as

clip_image001

Let us consider understanding that what exactly happening here. First thing is Data Binding which is the core feature of AngularJS. Angular bind name of the input box to a variable in data model. This is the two way binding. Two way binding keeps input box and data model in sync.

image

Later we are using filter function. This function will use input box ng-model value to create new array that will contain filtered value based on matched ng-model value from input box. Next let us see that how easily orderBy function can be implemented in AngularJS. Let us say we have a drop down as below,

image

We have created a drop down with two options. Both options are having value as the properties of the controller. Next just to sort the order set orderBy function value to ng-model value of the drop down list.

image

For your reference full source code for Controller is given below,

 


var AuthorApp = angular.module('AuthorApp', []);

AuthorApp.controller('AuthorController', function ($scope) {
    $scope.authors =
        [
                { 'name': 'Dhananjay Kumar','age':'32' },
                { 'name': 'Pinal Dave', 'age': '35' },
                { 'name': 'Glen Block', 'age': '40' },
                { 'name': 'Dan Wahlin', 'age': '40' },
                { 'name': 'Mahesh Chand', 'age': '41' },
                { 'name': 'Prabhjot Singh', 'age': '42' },
                { 'name': 'Julie Learman', 'age': '38' }
        ];

    
});


Source code of View is given below,


<!DOCTYPE html>
<html ng-app="AuthorApp">
<head>
    <title>Angular Demo</title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Author.js"></script>
</head>
<body ng-controller="AuthorController">

    Search: <input ng-model="searchtext">

    Sort:
    <select ng-model="sortorder">
        <option value="name">Name</option>
        <option value="age">Age</option>
    </select>

    <ul>
        <li ng-repeat="author in authors |
            filter:searchtext |
            orderBy:sortorder">
            {{author.name}} is {{author.age}} years old

       </li>
    </ul>
</body>
</html>


I hope you find this hour 3 of AngularJS series helpful. Thanks for reading. Happy coding.