Friday, January 22, 2016

Dependency Injection - Intro

This gonna be post series which I gonna continue .. Because this is bit complex and without theoretical part hard to understand.

Fist thing first.. Lets move with theoretical background of it with this post

 Assume this scenario.. - Entire Post sequence will use  this as example
There is student registration system we need to develop solution for student registration  

Here is our usual MVC code.


public class Student
   {
       public int StudentId { getset; }
       public string StudentName { getset; }
       public string RegId { getset; }
       public int Age { getset; }
 
 
       public IEnumerable<Student> GetStudents()
       {
           return new List<Student>();
       }
   }
 
Model Class 
 
public class StudentController : Controller
    {
        private readonly Student _student;
        public StudentController()
        {
            _student = new Student();
        }
        // GET: /<controller>/
 
        public IActionResult Index()
        {
            var data = _student.GetStudents();
            return View(data);
        }
    }
Controller Class 


In this way Model and controller is tightly coupled ( change of one class will effect other ) .  This way is not good in large scale projects a importantly. ( not recommend in any case )

You can find advantages and disadvantages of tight coupled code in OOP concepts.






  Dependency Injection


Dependency injection is the best way to create loose coupled code and resolve dependencies among the  classes .

In dependency injection some other class is responsible for injecting the dependencies in to client class(ex: Student Controller) we called it injector class at application run time.


here is object Diagram of it




Here is code how its look like with DI

public class Student:IStudent
   {
       public IEnumerable<Student> GetStudents()
       {
           return new List<Student>();
       }
   }
 
   public interface IStudent
   {
       IEnumerable<Student> GetStudents();
   }



public class StudentController : Controller
    {
        private readonly IStudent _student;
        public StudentController(IStudent student)
        {
            _student = student;
        }
        // GET: /<controller>/
 
        public IActionResult Index()
        {
            var data = _student.GetStudents();
            return View(data);
        }
    }
 
Enjoy Coding .. next post is on the way

Thursday, January 21, 2016

Web API From Code (Entity frameworkk code first model)

If you going to target mobile based applications to the small business you need to have API/web service on the hand.

Today we are going to develop Web API within few minutes.

Im using entity framework code first model approach here. (You can use same approach with Asp.NET web sites too) 

Advantages of Code first Model
  • All handle in the code. Full control with the code
  • No need to worry about the database

Here is the scenario today im working.

There is DVD rental store. Which each user can get one or more movie dvd's . 
















1. Create Asp.NET web API project
2. Then Add the following classes to it in model

TransactionId is auto increment 

/// <summary>
/// User Db Model 
/// </summary>
public class User
{
    public Guid UserId { getset; }
    public string UserName { getset; }
    public string NIC { getset; }
    public DateTime BirthDay { getset; }
 
    //One user may have multiple transactions
    public virtual ICollection<Transaction> Transactions { getset; }
}

/// <summary>
/// Video Db Model
/// </summary>
public class Video
{
    public Guid VideoId { getset; }
    public string VideoName { getset; }
    public string Publisher { getset; }
 
    //One video may have multiple transactions 
    public virtual ICollection<Transaction> Transactions { getset; }
}

/// <summary>
/// Transaction db model
/// </summary>
public class Transaction
{
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public int TransactionId { getset; }
    public Guid UserId { getset; }
    public Guid VideoId { getset; }
    public DateTime ReserveDate { getset; }
    public DateTime ReturnDate { getset; }
 
    //Add forign key 
    public virtual Video Video { getset; }
    public virtual User User { getset; }
} 

3. Install Entity Framework
4. Create Db Context file (RentalContext)
/// <summary>
/// Database context 
/// </summary>
public class RentalContext:DbContext
{
    public RentalContext():base("RentalContext")
    {
 
    }
 
    /******************Database tables ******************/
    public DbSet<User> UserSet { getset; }
    public DbSet<Video> VideoSet { getset; }
    public DbSet<Transaction> TranactionSet { getset; }
 
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
         base.OnModelCreating(modelBuilder);
    }
}

5. Then create Db initialize to change database when any changes happen with model
***With few sample data

public class RentalInitilizer : DropCreateDatabaseIfModelChanges<RentalContext>
{
    /// <summary>
    /// Add sampe data to the database 
    /// </summary>
    /// <param name="context"></param>
    protected override void Seed(RentalContext context)
    {
        List<User> Users = new List<User>()
        {
            new User(){BirthDay=Convert.ToDateTime("1990-05-03"),NIC="90563247855V",UserId=new Guid("93d82550-eefb-4b08-aab9-aa0cf8f3309f"),UserName="Dummy User1"},
            new User(){BirthDay=Convert.ToDateTime("1990-05-03"),NIC="90563247855V",UserId=new Guid("93d92550-eefb-4b08-aab9-aa0cf8f3309f"),UserName="Dummy User2"},
            new User(){BirthDay=Convert.ToDateTime("1990-05-03"),NIC="90563247855V",UserId=new Guid("93d82550-eefb-4b08-aab9-aa0cf8f3309f"),UserName="Dummy User3"}
 
        };
 
        Users.ForEach(x => context.UserSet.Add(x));
 
        List<Video> Videos = new List<Video>()
        {
            new Video(){Publisher="Publisger 1",VideoId=new Guid("4fb4912c-6f7d-4d34-8fd0-9ec641ae328d"), VideoName="Video 1"},
            new Video(){Publisher="Publisger 2",VideoId=new Guid("bcfc276a-8c41-40ad-bb7b-05731dbfcce5"), VideoName="Video 2"},
            new Video(){Publisher="Publisger 3",VideoId=new Guid("6a95ce93-6b9d-4d29-9bb0-fb69e2bb53bb"), VideoName="Video 6"}
 
        };
        Videos.ForEach(x => context.VideoSet.Add(x));
 
        List<Transaction> Transactions = new List<Transaction>()
        {
            new Transaction(){ReserveDate=DateTime.Now,ReturnDate=DateTime.Now.AddDays(5),UserId= new Guid("93d82550-eefb-4b08-aab9-aa0cf8f3309f"),VideoId=new Guid("6a95ce93-6b9d-4d29-9bb0-fb69e2bb53bb")},
            new Transaction(){ReserveDate=DateTime.Now,ReturnDate=DateTime.Now.AddDays(5),UserId= new Guid("93d82550-eefb-4b08-aab9-aa0cf8f3309f"),VideoId=new Guid("bcfc276a-8c41-40ad-bb7b-05731dbfcce5")}
 
        };
        Transactions.ForEach(x => context.TranactionSet.Add(x));
 
        context.SaveChanges();
        
       base.Seed(context);
    }
}
 

6. Edit the config
Add context to the entity framework
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
    <contexts>
      <context type="SEF_CodeFirst_API.Models.DbModels.RentalContext, SEF_CodeFirst_API">
        <databaseInitializer type="EF_CodeFirst_API.Models.DbModels.RentalInitializer, SEF_CodeFirst_API" />
      </context>
    </contexts>
  </entityFramework>

Add the  Connection string
 <connectionStrings>
    <add name="RentalContext" 
 connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Rental;Integrated Security=SSPI;" 
 providerName="System.Data.SqlClient" />
  </connectionStrings>


Then  you have to create Controller's from Entity framework with read write options.. you are in


Enjoy