January 29, 2016

Miscellaneous

Avoid Too Many Parameters 

Declare a class instead of too many parameters.

Creating a class that puts all these parameters together. This is generally a better design and valuable abstraction.


Avoid Complex Expressions

Minimize the Number of Returns

Use Parameterize queries instead of inline query

public DataTable GetUser(string userid)

{

str = "select ,PINCODE,ACTIVE from mkt_user_mast where type=:userid";

OracleCommand orc = new OracleCommand(str);

orc.Parameters.AddWithValue("userid", userid.ToUpper());

dst = objconnection.fnselectPara(orc);

return dst;

}


Separation of concerns - by putting code in separate layers, you separate the various parts of your application, such as data access, business logic and the UI. This makes it easier to design and build the application and makes it possible for developers in multiple disciplines (database, server side programming, and frontend development, design) to work on the application in parallel.

Abstraction - With a layered architecture it's easier to look at a complete application and understand the roles and responsibilities of individual layers and the relationship between them. Each layer has its own responsibilities which allow you to analyze them in isolation. 

Testability - with a layered architecture, it's much easier to test each layer separately with unit tests as there are fewer dependencies between the various layers. This means, for example, that you can test your business logic or your UI without requiring a real database to test against. 

Replaceability - It'll be easier to swap out layers. For example, you can replace your data access technology without affecting the other layers higher up in the stack. 

Reuse - You can reuse one or more layers in different applications. You'll see the benefits of this in part 6 through 9 where the same data access and business layers are reused in four different frontend applications without requiring any changes to the lower layers. 
http://aspnetboilerplate.com/Pages/Documents/NLayer-Architecture
http://dotnetdaily.net/tutorials/n-tier-architecture-asp-net/
http://aspnetboilerplate.com/

class Person - Entity and POCO.
an instance of this class is Domain Object

class Person 
{
    public string PersonId;       
    public string Name;
    public string Email;

    public static bool IsValidName() { //logic here}
    public static bool IsValidEmail() { //logic here }
}

class PersonService
{
    private PersonRepository pRepository;
 
    PersonService(PersonRepository pRepository)
    {
        this.pRepository = pRepository;
    }
 
    public bool IsExistingEmail(string email)
    {
        //calls repo method to see if email is in db
    }
 
    public Person GetPerson(email)
    {
        return pRepository.Get(email);
    }
 
 
    public void SavePerson(Person p)
    {
        if (Person.IsValidEmail(p.Email) && !IsExistingEmail(p.Email)
        {
            pRepository.Save(p);
        }
    }
}
 
 
class PersonRepository
{
    public void Save(Person p)
    {
        //save to db
    }
    public Person Get(string email)
    {
        //get from db
    }
    public bool IsExistingEmail(string email)
    {
        //see if email in db
    }
}

January 27, 2016

Entity Framework

The NuGet Gallery is the central package repository used by all package authors and consumers.



module is a set of functions, types, classes, ... put together in a common namespace.
library is a set of modules which makes sense to be together and that can be used in a program or another library.
package is a unit of distribution that can contain a library or an executable or both. It's a way to share your code with the community.
Entity Framework is ORM (Object relational mapper)

Entity Framework overview


Entity Framework Architecture

  • Extension of EF is .edmx
  • EF is directly talk with database. DAL is not required .
  • EF use ObjectContext =>DbContext interfacing with database
  • EF use EDM concept that describe the structure of data

https://msdn.microsoft.com/en-us/library/ee382825(v=vs.110).aspx


  • Entity type is class. it generate from table structure.
  • Entity type contain property and method where property is column of table and method is operation (Select/Insert/Update/Delete) done on that table
  • EF can do the operation on table with the help of LINQ or  store procedure
  • Complex object is created via Model browser if we have to call store procedure
  • Model browser - show the edmx file Model browser tab

EDM contain
  • CSDL- conceptual schema definition language
  • SSDL- storage schema definition language
  • Table Mapping - conceptual mapping and storage mapping
  • Schema contain multiple entity containers.
  • Entity container is namespace and contain entity type
  • EntityType (NavigationProperty,Scalar Property(facet),EntityKey).
  • Property contain facet (other information related to that column like Not NULL, Max length)
  • Validate - check CSDL or SSDL are synch or not
  • Complex Property
  • association - create relation between entity types

The relationship between an entity type and an entity set is analogous to the relationship between a row and a table in a relational database: Like a row, an entity type describes data structure, and, like a table, an entity set contains instances of a given structure.

Entity Framework Architecture

Setup Entity Framework Environment:


Entity Framework5


Entity Framework6




Install EF via Nuget:

Entity Framework install

Create Entity Data Model:




Entity Framework 5.0 Tutorial

Context & Entity Classes:

Entity Framework 5.0 Tutorial

Model Browser
Entity Framework 5.0 Tutorial

DBContext:

Entity Framework 5.0 Tutorial


Types of Entity in Entity Framework:

  • POCO Entity (Plain Old CLR Object):
  • Dynamic Proxy (POCO Proxy):



Entity Framework dbcontext


Entity Relationships:


Entity relationships in entity framework




entity relationships in entity framework





Entity Lifecycle:


entity states in Entity



Choose Entity Framework modling


can execute native SQL queries for a relational database

using (var ctx = new SchoolDBEntities())
{
    var studentName = ctx.Students.SqlQuery("Select studentid, studentname, standardId from Student where studentname='Bill'").FirstOrDefault<Student>();
}    

Maintain change track


Connected scenario

Entity Framework tutorial 4.3 dbcontext




using (var context = new SchoolDBEntities())
{
    var studentList = context.Students.ToList<Student>();

    //Perform create operation
    context.Students.Add(new Student() { StudentName = "New Student" });

    //Perform Update operation
    Student studentToUpdate = studentList.Where(s => s.StudentName == "student1").FirstOrDefault<Student>();
    studentToUpdate.StudentName = "Edited student1";

    //Perform delete operation
    context.Students.Remove(studentList.ElementAt<Student>(0));

    //Execute Inser, Update & Delete queries in the database
    context.SaveChanges();
} 

Disconnected scenario






using (var context = new SchoolDBEntities())
{
    var studentList = context.Students.ToList<Student>();

    //Add student in list
    studentList.Add(new Student() { StudentName = "New Student" });

    //Perform update operation
    Student studentToUpdate = studentList.Where(s => s.StudentName == "Student1").FirstOrDefault<Student>();
    studentToUpdate.StudentName = "Edited student1";

    //Delete student from list
    if (studentList.Count > 0)
        studentList.Remove(studentList.ElementAt<Student>(0));

    //SaveChanges will only do update operation not add and delete
    context.SaveChanges();
}

There are two ways to go with code first approach:
  1. Data annotation
  2. Fluent API

Code First Approach using Data Annotation

Create one .cs file and give name person.cs and paste the below code into it. As this his data annotation approaches, don’t forget to add System.ComponentModel.DataAnnotation namespace.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class Person
    {
        [Key]
        public int Id{get;set;}
        [Required]
        public string name { get; set; }
        [Required]
        public string surname { get; set; }
    }

    public class Address
    {
        [Key]
        public int personAdressId { get; set; }
        public string address { get; set; }

        [MaxLength(6)]
        public string pin { get; set; }

        [ForeignKey("Person")]
        public int PersonId { get; set; }

        //Navigation property
        public virtual Person Person { get; set; }
    }

    public class personContext : DbContext
    {
        public personContext() : base("DBConnectionString")
        {
            //If model change, It will re-create new database.
            Database.SetInitializer<personContext>(new DropCreateDatabaseIfModelChanges<personContext>());
        }
        public DbSet<Person> person { get; set; }
        public DbSet<Address> Address { get; set; }
    }
}
we will specify connection string in web.config file in application. Here is code for mine.
<connectionStrings>
    <add name="DBConnectionString" 
        connectionString="Data Source=SOURAV-PC;Initial Catalog=personDB;Integrated Security=true" 
        providerName="System.Data.SqlClient"/>
  </connectionStrings>



We will implement the same model to create database using fluent API. Have a look at the below modified code of person.cs file.


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class Person
    {
        public int Id{get;set;}
        public string name { get; set; }
        public string surname { get; set; }
    }

    public class Address
    {
        public int personAdressId { get; set; }
        public string address { get; set; }
        public string pin { get; set; }
        public int PersonId { get; set; }
        public virtual Person Person { get; set; }
    }

    public class personContext : DbContext
    {
        public personContext()
            : base("DBConnectionString")
        {
            //If model change, It will re-create new database.
            Database.SetInitializer<personContext>(new DropCreateDatabaseIfModelChanges<personContext>());
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Set primary key to Person table
            modelBuilder.Entity<Person>().HasKey(m => m.Id).Property(m => m.Id).IsRequired();
            //name fleld is required

            modelBuilder.Entity<Person>().Property(p => p.name).IsRequired();
            //surname is required
            modelBuilder.Entity<Person>().Property(p => p.surname).IsRequired();

            //set primary key to Address table
            modelBuilder.Entity<Address>().HasKey(m => m.personAdressId);

            //set max length property to 6 
            modelBuilder.Entity<Address>().Property(m => m.pin).HasMaxLength(6);

            //Set foreign key property
            modelBuilder.Entity<Address>().HasRequired(t => t.Person)
                .WithMany().HasForeignKey(t => t.PersonId);
        }
        public DbSet<Person> person { get; set; }
        public DbSet<Address> Address { get; set; }
    }
}