Translate

Monday, December 31, 2012

Autofac Intermediate level Tutorial (autofac mvc 4)

If you are absolutely new to autofac and inversion of control, I would strongly recommend reading up on these two articles before you proceed

C# Dependency Injection tutorial
Introduction to AutoFac


In this article I will create a simple MVC4 application first without Autofac and then I will introduce Autofac (version 2.6.3.862) into the application. All this application does is display this page below. This application has been simplified to focus more on Autofac. Ideally this is how an MVC application should be laid out.













If you have already played around with autofac, you can directly skip to bootstrap.cs (Its towards the bottom of the article)


Application Without Autofac 

Create an empty MVC4 application called UI.


To the solution, add a C# class library project called Objects:















In this project include a class file called Person.cs



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

namespace Objects
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string SocialSecurityNumber { get; set; }
    }
}



Add a C# class library called DataAccessLayer.:













 Add a reference to the Objects project added above.
 Add this class file called DAL.cs. We will pretend that this class returns data from a database.


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

namespace DataAccessLayer
{
    public class DAL
    {

        public Person GetAPerson()
        {
            var p = new Person { Name = "Jack", Age = 27, SocialSecurityNumber = "999-99-9999" };

            return p;

        }
    }
}




MVC Project UI:
























In the MVC4 project called UI, add references to both the Objects and the DataAccessLayer Projects created above.This UI project has the following three files HomeController.cs,PersonViewModel.cs, People.cshtml

HomeController.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataAccessLayer;
using UI.Models;
namespace UI.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult People()
        {
            var dal = new DAL();
            var person = dal.GetAPerson();
            var personViewModel = new PersonViewModel(person);

            return View(personViewModel);
        }


    }
}



PersonViewModel.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Objects;

namespace UI.Models
{
    public class PersonViewModel
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public PersonViewModel(Person p)
        {
            Name = p.Name;
            Age = p.Age;
        }

    }
}



People.cshtml


@model UI.Models.PersonViewModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>People</title>
</head>
<body>
    <div>
       @Model.Name, @Model.Age
    </div>
</body>
</html>



Go ahead and run the app. It should correctly display a page that says Jack,27

------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------




Application With Autofac 

What we are going to do here is, in the application start code in global.asax.cs, we will call the code (BootStrap class) that sets up all the dependencies. Here in the BootStrap class, we tell the DI container (autofac) two things
  1. Which implementation of an interface to use (Object composition)
  2. When should that instance be disposed (Object Lifetime)
The second aspect (that is lifetime of the object) is something that would take a little more reading to understand and is outside the scope of this article. This is an excellent resource to understand how to set up the object lifetimes in autofac.


Modify the Objects Project:

Add a file called IDAL.cs to the Objects project.


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

namespace Objects
{
   public interface IDAL
    {

        Person GetAPerson();
    }
}


Modify the DataAccessLayer project:

Modify DAL.cs so that it inherits from the interface IDAL

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

namespace DataAccessLayer
{
    public class DAL:IDAL
    {

        public Person GetAPerson()
        {
            var p = new Person { Name = "Jack", Age = 27,SocialSecurityNumber="999-99-9999" };

            return p;

        }
    }
}



Modify the UI project

Use nuget to add Autofac,Autofac.Configuration and Autofac.Integration.Mvc dlls to the UI project. Use these nuget commands to do that

Install-Package Autofac -Version 2.6.3.862
Install-Package Autofac.Mvc4 -Version 2.6.2.859

Bootstrap.cs:

Add a file called bootstrap.cs to the UI project.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Autofac;
using System.Web.Mvc;
using Autofac.Integration.Mvc;
using DataAccessLayer;
using Objects;
using System.Reflection;

namespace UI
{
    public class BootStrap
    {

        public IContainer myContainer { get; private set; }

        public void Configure()
        {
            ContainerBuilder builder = new ContainerBuilder();
            OnConfigure(builder);

            if (this.myContainer == null)
            {
                this.myContainer = builder.Build();
            }
            else
            {
                builder.Update(this.myContainer);
            }

            //This tells the MVC application to use myContainer as its dependency resolver
           DependencyResolver.SetResolver(new AutofacDependencyResolver(this.myContainer));
        }


        protected virtual void OnConfigure(ContainerBuilder builder)
        {
            //This is where you register all dependencies

            //The line below tells autofac, when a controller is initialized, pass into its constructor, the implementations of the required interfaces
            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            //The line below tells autofac, everytime an implementation IDAL is needed, pass in an instance of the class DAL
            builder.RegisterType<DAL>().As<IDAL>().InstancePerLifetimeScope();         


        }
    }

}


Modify Application_Start() in global.asax.cs: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;

namespace UI
{

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            var bootstrap = new BootStrap();
            bootstrap.Configure();

        }

    }
}


Modify Homecontroller.cs:




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataAccessLayer;
using UI.Models;
using Objects;
namespace UI.Controllers
{
    public class HomeController : Controller
    {

        private IDAL _dal;

        public HomeController(IDAL dal)
        {
            _dal = dal;
        }

        public ActionResult People()
        {

            var person = _dal.GetAPerson();
            var personViewModel = new PersonViewModel(person);

            return View(personViewModel);
        }


    }
}


Go ahead and run the app. It should run without any errors.








Saturday, December 29, 2012

Layout of an N-tier MVC application (MVC N-tier architecture)


The image below shows the layout of an N Tier MVC application.




Friday, December 28, 2012

Some useful Resharper commands

These are some of my favorite resharper commands/functionality


Command
What does it do?


Ctrl+T
Find Type
 CTRL+Shift+Alt+A (brings up a menu)
The click on "Incoming Calls"
Finds all the calls to the function
Alt+end
Find implementation
(A very useful feature if you are using dependency injection)
Copy stack trace onto your clipboard and then do
Ctrl+E+T
You will see the breaking llike of code as a clickable link

This feature makes it possible to quickly travel to the erroneous lines of code when debugging.
Alt+Shift+L
Locate in solution
Click on a field or class name and then do Ctrl+shift+R
Gives you many options such as
Change signature
Rename (This will rename all the references and all the other needful)
Safe Delete
Extract Interface
Extract Super CLass
Extract Class
Push Members Down
Convert Property To Method(s)
Make Static

CTRL+ALT+F
Shows all the fileds, properties and definitions in the current code page
























Monday, December 24, 2012

Windows 7 port numbers

All the assigned port numbers in a windows 7 machine is located at


C:\Windows\System32\drivers\etc\services

Friday, December 21, 2012

c# cast parent to child (c# downcast)

The Principle:

The easiest way to downcast in C# is to serialize the parent and then de-serialize it into a child instance.


 var serializedParent = JsonConvert.SerializeObject(parentInstance); 
 Child c  = JsonConvert.DeserializeObject<Child>(serializedParent );



The complete example :

For the console application example below I used  Newtonsoft.Json to serialize  an abject into a JSON object. If you are using asp.net, a reference to  Newtonsoft.Json is automatically included when you create a new project.



using System; 
using Newtonsoft.Json;
 
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var a = new Animal { AnimalProperty = "I am an animal" }; 
 
            //Dog d = (Dog)a; //throws  System.InvalidCastException
 
 
            var serializedAnimal = JsonConvert.SerializeObject(a); 
            Dog d  = JsonConvert.DeserializeObject<Dog>(serializedAnimal);
 
            d.DogProperty = "woof woof";
 
            Console.WriteLine(d.AnimalProperty);//Displays I am an animal
            Console.WriteLine(d.DogProperty);   //Displays woof woof
 
        }
    }
 
    public class Animal
    {
       
 
        public string AnimalProperty
        {
            get; 
            set; 
        }
    }
 
    public class Dog : Animal
    {
 
        public string DogProperty
        {
            get;
            set;
        }
    }
 
 
}

Wednesday, December 12, 2012

Some handy command prompt (Windows console ) commands for Windows

Command example
What it does


net use
Shows the paths to all the mapped drives
ping www.google.com
Checks the response time for a request sent to google.com and also lists the ip address that is assigned to google.com
ping -a 98.139.183.24
Gives the Domain name assigned to the ip address 98.139.183.24
tracert www.yahoo.com
Traceroute will print out a list of all the routers, computers, and any other Internet entities that your packets must travel through to get to their destination.
shutdown -t 0 -r -f
Restart a computer through command prompt. (Comes in handy when connected to a remote windows machine)
NET GROUP myGroupName /domain
This command will give you all the members in the active directory group myGroupName

qwinsta /server:servername
 Tells you who all are logged into a remote server.
netstat 
Netstat (network statistics) is a command-line tool that displays network connections (both incoming and outgoing)




















Sunday, December 2, 2012

Cipher Meaning Software

Cipher in English language means to transform text to conceal its meaning.  That is exactly what it means in software too. A simple example of cipher would be to move letter by one position in alphabetical order. So instead of a write b, instead of b write c and so on. So "CAT" would be ciphered into "DBU".