menu

Saturday, September 24, 2016

Code First CRUD in Entity Framework using ASP.NET

Steps to implement code first CRUD in entity framework. (Download Sample App)
1. Install entity framework liberary from NuGet.
2. Create model classes and context class
3. Create table to store student information and add connection string in Web.config file.
CREATE TABLE [dbo].[Students](
       [ID] [int] IDENTITY(1,1) NOT NULL,
       [Name] [nvarchar](max) NULL,
       [DOB] [datetime] NOT NULL,
       [Photo] [varbinary](max) NULL,
       [Height] [decimal](18, 2) NULL,
       [Weight] [real] NULL,
       CONSTRAINT [PK_Students] PRIMARY KEY CLUSTERED ([ID] ASC)
       WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
       IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
       ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
4. Create UI in Asp.net WebForm as shown above. (Download .aspx and aspx.cs)
5. Create a handler to bind binary data to grid view. (Download handler code)

Sunday, September 18, 2016

Covariance & Contravariance

Covariance 
Before .Net 4.0 it was not possible to assign a reference variable of List of parent type to List of its child type.
IEnumerable<Employee> empList = new List<PermanentEmployee>(); X (not possible)
Where PermanentEmployee is child type of Employee type.

But possible in 4.0 on-words by introducing out keyword.

Contravariance
A base type of function pointer (delegate) reference variable was not able to get assign to reference variable of its child type.
delegate void MyPtr<T>(T o);
MyPtr<Employee> oEmp = Print;
MyPtr<PermanentEmployee> oPEmp = oEmp; X (not possible)

But possible in 4.0 on-words by introducing in keyword.
delegate void MyPtr<in T>(T o);

Below is the complete code demonstrating both.
using System;
using System.Collections.Generic;
namespace CovarianceContravariance
{
    class Program
    {
        delegate void MyPtr<in T>(T o);
        static public void Contraveriance()
        {
            MyPtr<Employee> oEmp = Print;
            MyPtr<PermanentEmployee> oPEmp = oEmp; //Backword campatability
        }
        static void Print(Employee emp)
        {
            Console.WriteLine(emp.Name);
        }
        //-------------------------------------------------------------
        public void Coveriance()
        {
            Employee emp = new PermanentEmployee(); //Polymorphism - Valid Statement
            emp = new ContractEmployee(); //Polymorphism - Valid Statement
            //Valid Statement, Invalid below 4.0
            IEnumerable<Employee> empList = new List<PermanentEmployee>();
        }
        //-------------------------------------------------------------
        static void Main(string[] args)
        {
           
        }
    }
    public class Employee
    {
        public string Name = "Animal";
    }
    public class PermanentEmployee : Employee
    {

    }
    public class ContractEmployee : Employee
    {

    }
}

Data Annotation

Is a way to validate business objects in easy and simplified manner.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace DataAnnotations
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer cust = new Customer();
            try
            {
                cust.name = "";//It will throw exception
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            cust.name = "TestName";
            cust.number = "1234567890";//here length is 11 and requird max length is 10
            ValidationContext context = new ValidationContext(cust);
            List<ValidationResult> vResults = new List<ValidationResult>();
            bool isValid = Validator.TryValidateObject(cust, context, vResults, true);
            foreach (ValidationResult vResult in vResults)
           {
                Console.WriteLine(vResult.ErrorMessage);
            }
            Console.WriteLine("Customer Validation: {0}", isValid);
        }
    }
    public class Customer
    {
        private string _name;
        //Traditional way
        public string name
        {
            get { return _name; }
            set
            {
                if (value.Length == 0)
                {
                    throw new Exception("Name is required !");
                }
                _name = value;
            }
        }
        private string _number;
        //Through data annotation
        [Required(ErrorMessage = "Number is required !")]
        [StringLength(10, ErrorMessage = "Length should be <= 10")]
        public string number
        {
            get { return _number; }
            set { _number = value; }
        }
    }
}

Saturday, September 17, 2016

Change Data Capture (CDC)

In order to enable it we have to enable on 2 level.
1.       Database Level - EXEC SYS.SP_CDC_ENABLE_DB
Once CDC enables, it creates some tables and stored procedures to keep track of records.

2.       Table Level - Before running below query first make sure that SQLServerAgent is running.
EXEC SYS.SP_CDC_ENABLE_TABLE @SOURCE_SCHEMA=N'dbo',
@SOURCE_NAME=N'Sales', @ROLE_NAME=NULL

Once CDC enables on table, it creates one more table.

Insert, update and delete operations on dbo.Sales table will insert log record in cdc.dbo_Sales_CT.
1.       Blank tables

2.       Insert new records to dbo.Sales will make an entry in cdc.dbo_Sales_CT table to keep log of insert with flag 2 in __$operation column.

3.       Update a record will make 2 entry in cdc.dbo_Sales_CT to indicate old as well as new row with flag 3 and 4 respectively in __$operation column.

4.       Delete a record will make one entry in cdc.dbo_Sales_CT to indicate deleted row with flag 1 in __$operation column.

Sunday, September 11, 2016

Custom List with OnAdd Event

using System;
using System.Collections.Generic;
namespace Event
{
    class Program
    {
        static void Main(string[] args)
        {
            CustomList<int> list = new CustomList<int>();
            list.OnAdd += new EventHandler<CustomEventArgs<int>>(OnListAdd);
            list.Add(1);
        }
        static void OnListAdd(object sender, CustomEventArgs<int> e)
        {
            Console.WriteLine("Item: {0} added...", e.Item);
        }
    }
    class CustomList<T> : List<T>
    {
        public event EventHandler<CustomEventArgs<T>> OnAdd;
        public void Add(T item)
        {
            if (null != OnAdd)
            {
                CustomEventArgs<T> args = new CustomEventArgs<T>() { Item = item };
                OnAdd(this, args);
            }
            base.Add(item);
        }
    }
    class CustomEventArgs<T> : EventArgs
    {
        public T Item { get; set; }
    }

}