Thursday, 27 October 2016

Microsoft SQL Server Trigger

Microsoft SQL Server have opportunity "Trigger" ."Trigger" is not like stored procedure or SQL Query , which need to execute ."Trigger" is an functionality object which fires himself when data in a table modified (Insert/Update/Delete). The firing will be determined by defination of trigger , when trigger will fired on Insert/Update/delete .Actually trigger is special kind of stored procedure automatically execute on event occur .We can create/alter trigger by simple DML statement.Trigger are generally execute to implement some business rules. , for example when I am creating a student records , it is obvious to create a login for that student.Here ,if we write a trigger which will create a login data when a new student inserted .Trigger will automatically fires when we add a new student and no need ti write extra logic or not extra event is required to create student login.Her is an exaple of trigger


CREATE TRIGGER myTrigger ON tbl_member
FOR INSERT,UPDATE, DELETE
AS
SELECT MEMBER_ID,MEMBER_NAME FROM Inserted
SELECT MEMBER_ID,MEMBER_NAME FROM deleted
--Wirte your next code here

In teh above exaple , we have a table tbl_membe .We have creatde a trigger on tbl_member .We have define the trigger "FOR INSERT,UPDATE, DELETE" .That means , any operation INSERT,UPDATE, DELETE , the trigger will fired .Now , what happen when Insert, Update , Delete happen ? There is a concept of magic table .During Insert/Update/Delte two type of magic table are created .
  1. Insertde
  2. Deleted
  Inserted tahble for Inserted value 
  Deleted table for deleted value
  For updated , both inserted & deleted table works , first deleted then inserted.

Some points to remember
  • Sql Server allow more than one trigger on a table
  • When we have multiple trigger on a table , we can use ,"sp_settriggerorder" to set trigger firing order .For example trigger A will fire first , trigger B will fire next
                              An Example of Trigger

 
CREATE Trigger Mytrigger1 ON [dbo].[tbl_student]
FOR INSERT
AS
DECLARE @l_student_name         VARCHAR(500),
            @l_student_dob          DATETIME,
            @l_student_class      INT,
            @l_student_address      VARCHAR(MAX)

SELECT @l_student_name=student_name,
         @l_student_dob=student_dob,
         @l_student_class=student_class,
         @l_student_address=student_address
                                      FROM INSERTED;
--Insert Audio Table
INSERT INTO tbl_student_audion
(
      student_name,
      student_dob,
      student_class,
      student_address
)
VALUES
(
     @l_student_name,
       @l_student_dob,
       @l_student_class,
       @l_student_address
)  
GO

In the above exaple , a table named tbl_student hilds , students records , when we insert data into tbl_student , the same data will be copied into tbl_student_audit without any extra event for fireing.

How ever , trigger are basically two types 

  1. After Trigger
  2. Instead of trigger
After Trigger
This type of trigger fires automatically after an insert/update/delete .After insert/After update/After Delete .This type of trigger fires only after main operation (Insert data).In the above example we can modify thus

CREATE Trigger Mytrigger1 ON [dbo].[tbl_student]

AFTER INSERT
AS
DECLARE @l_student_name         VARCHAR(500),
            @l_student_dob          DATETIME,
            @l_student_class      INT,
            @l_student_address      VARCHAR(MAX)

SELECT @l_student_name=student_name,
         @l_student_dob=student_dob,
         @l_student_class=student_class,
         @l_student_address=student_address
                                      FROM INSERTED;
--Insert Audio Table
INSERT INTO tbl_student_audion
(
      student_name,
      student_dob,
      student_class,
      student_address
)
VALUES
(
     @l_student_name,
       @l_student_dob,
       @l_student_class,
       @l_student_address
)  
GO
                      In this process , first record are inserted in the tbl_student table and then data copied tbl_student_audit table. If we change it to "After Delete" , the first data will be deleted and the data will be inserted to tbl_student_audit table.After trigger are the only trigger to allow the same record that client application currently has locked(The operation that caused the trigger to fire earlier or first phase.


                     Instead of Insert 
Instead of Insert trigger fires  before the original operation Insert/Update/Delete .Actually it replace the original operation , if an instead of delete trigger exits on a table , when client delete record , the trigger code will be fired and control return to client.Now question is , when we will use Instead of Trigger ? When you modify the changes made by the client before actually posting update , Instead of Trigger used.

 
CREATE Trigger Mytrigger1 ON [dbo].[tbl_student]
ALTER DELETE
AS
DECLARE @l_student_name         VARCHAR(500),
            @l_student_dob          DATETIME,
            @l_student_class      INT,
            @l_student_address      VARCHAR(MAX)

SELECT @l_student_name=student_name,
         @l_student_dob=student_dob,
         @l_student_class=student_class,
         @l_student_address=student_address
                                      FROM DELETED;
--Insert Audio Table
INSERT INTO tbl_student_audion
(
      student_name,
      student_dob,
      student_class,
      student_address
)
VALUES
(
     @l_student_name,
       @l_student_dob,
       @l_student_class,
       @l_student_address
)  
GO

Now , if i have a multiple trigger on a table , how to disable or on/off trigger ?
The syntax of trigger enable /disable is

ALTER TABLE table_name DISABLE TRIGGER tr_name
ALTER TABLE table_name ENABLE TRIGGER tr_name 

For example  , i want to disable "Mytrigger1" trigger from "tbl_student"
The sql will be

ALTER TABLE tbl_student ENABLE TRIGGER Mytrigger1

A Practical Example
 
--I am creating two table test1 and test2
 CREATE TABLE tests1
 (
 id INT IDENTITY,
 sname VARCHAR(50),
 age INT
 )
 CREATE TABLE tests2
 (
 id INT IDENTITY,
 sname VARCHAR(50),
 age INT
 )
 --I am inserting value to tests1
 INSERT INTO tests1(sname,age)
 VALUES('Name1',12)
 GO
 INSERT INTO tests1(sname,age)
 VALUES('Name2',13)

 --Now table test1 has 2 records and test2 is empty


CREATE Trigger Mytrigger1 ON [dbo].[tests1]
AFTER INSERT
AS
DECLARE @l_sname  VARCHAR(50),
        @l_age    INT
       
--Initialised variable
SELECT @l_sname='',
       @l_age=NULL
      
--get value from test1 into variable
SELECT @l_sname=sname,
       @l_age=age
       FROM INSERTED;

--insert data to test2
 INSERT INTO tests2(sname,age)
 SELECT @l_sname,@l_age

GO
---Now i am again addtin data to tests1
 INSERT INTO tests1(sname,age)
 VALUES('Name2',13)

 ---trigger will fires and put data to tests2

SELECT * FROM tests2

 
        

                      




Tuesday, 25 October 2016

017 Weekend Tour Murshidabad

Murshidabad Tour :
Murshidabad is a district of West Bengal , India . A land of Nawab tells history of Bengal and its culture .The most attractive place to visit Hazarduari Place Museum which is under Archeological Survey of India , Other place are Katra Masjid , Kathgola Garden , Jahan Khosa Garden , Khosh Bagh .Imambara , Tafarganj cemetery , Motijil ect . Mushidabad is situated at the Bank of Bhagirathi river also famous for  silk sari , it tell the story of glory of Independent Bengal During the British rule in India.













Place  to Stay : There are a lot of Hotels (Budget & Standard) in and around Mushidabad .But during the winter & festive season , a lot of tourist comes here to visit Hazar Duari place , it is recommended to Book hotel before.

How to reach : A lot of Bus services are available to reach Murshidabad from Kolkata .Kolkata-Berhampur bus are easily available from esplanade .By train Bhagirathi Express , Lalgola Passenger are there to reach Murshidabad.









Hazarduari palace Museum is situated near Lalbag , it is open for tourist , the precious historical article well preserved here , painting ,furniture , decorated pot of Mughal regime.There are also  two pairs of Mirror in the museum , that are placed 90 degree in such , one can other face but not his own.You can see Gallery of Armour ,Knives ,pistol ,old gun ,Arrow rifles tells the story of Nawab regime.
Khtra Masjit is one of the attraction of Mushidabad .It was build in 1723 and Mushid Quli khan , the famous was buried under staircase of entrance.A great heart touching story is there , guide will explain the story .







Kathgola Garden is another attraction of Murshidabad . Kathgola means black rose , Guide tells that black rose cultivated here earlier.The place is now privately own , here you will also see ancient painting , mirror ,furniture and have attractive and thrilling past story.Guide will told you the past , guide is mandatory here.
Motjil , Means pearl pond , Guide says that in the past pearl cultivated here , Motijil park is a good spot for tourist , beautiful green park , well decorated , well planned is popular among tourist.In the evening light and sound (fountain & music) performance is shown here.







Monday, 24 October 2016

View State Management ASP.Net

View State Management ASP.Net
 
ASP.Net is stateless , that means when we submit page to server , server generate new HTML for that page and deliver us.The value we entered  , get loss .For Example we have entered some information of student and send it to Server , when server return the page , the data i have entered losses.

To solve the problem , different framework introduced different technique .In ASP.Net , there are two type of technique , server Based & Client Based . 


View State is a good technique to handle State Management .View State is actually a hidden field which hold data in base 64 encrypted format.If you go to view HTML of the page , you will notice

It is always recomended to use  as little as possible , view state make extra overhead on perfoemance ,but little .We can enable/disable bu enter enableViewState=true/false.


Now we will discuss how , view state overhead effect .We have data and running two mode  
enableViewState=true/false .Let us see the performance.





Now , notice size of page increase , that means , it will take more time with View State , that means View State has a effect on Page performance.An extra overload make a page little bit slow in loading.

Now , can we control page level view state & control level view state ? can we do disable page view state and enable control view state , the answer is 'yes' , Asp.Net offer this solution also .In the page top just write enableViewState=false , this makes , page view state off , now we can turn on control of ASP.Net ViewStatemode enable disable will enable / disable will enable /disable control by control basis.

Some point to remember

  •   View State Loaded after page_init.
  •   View State created after page_prerender.
  •   View State is encrypted base 64 algorithm.                                                                                                     There are also encryption  option on View State , we can do it elthier page level
  •  
   OR 

Three Option are
Always  : Always encrypt view state.
Auto :encryption if the control on thre page request it.
Never :Recommended not use
  
                                         






Friday, 21 October 2016

ASP.Net State Management

ASP.Net State Management
                   We know any web page are state less, means when we post a page to server , server will not return the same state as it was send . The reason is , when we post a form /page to the server , server process the page and generate new html and send to browser .For example a web page is taking student information , student name , date of birth ,country ,state .We enter student name , date of birth , now we have Select student country “Say” India , page need to go server and get state list of India .When it posted to server for state information , the whole html is created again and when comes to browser , student name , date of birth not data is not there .Input fields are empty.

                To over come this problem , Asp.Net introduced State Management . State Management is a technique to keep data while post back occur , that means , when student page with student data will be posted to the server , and server will return  student page with student data.

              There are several way to maintain State in ASP.Net , such as View State ,Hidden Fields ,
Cookies ,  Query String , Control State . Some are Clint Site and Some are Server Site.


  View State : View state is the technique that the ASP.NET page  uses to preserve page and control  values when post back . The working of View State can be controlled by C# code , by default view state enabled . View state is a hidden filed with serialized into base64-encoded strings.We van enable /disable code from page level


%@ Page Language="C#"  CodeFile="Default2.aspx.cs" Inherits="Default2"  EnableViewState="false"

We can encrypt view state


%@ Page Language="C#"  CodeFile="Default2.aspx.cs" Inherits="Default2" EnableViewState="true ViewStateEncryptionMode="Always" 

There is also Option for enable/disable at control level

asp:TextBox EnableViewState=true

We can also do enable/disable  the whole page and enable/disable on or more control.
We can also use View State variable as follow


protected void Page_Load(object sender, EventArgs e)

    {

        if (ViewState["NameOfStudent"] != null)

            txtStudentName.Text = ViewState["NameOfUser"].ToString();

        else

            txtStudentName.Text = "Not set yet...";

    } 

    protected void SubmitForm_Click(object sender, EventArgs e)

    {
        ViewState["NameOfUser"] = txtStudentName.Text;
        txtStudentName.Text = NameField.Text;
    }
 

We can see view state value , to see the value , please write click on mouse and go to "View source" , here is the example
Hidden field : Hidden field is control , which is not displayed in the front end .This field are use to hold control value , here is an example


<body>
    <form id="form1" runat="server">
    <div>
      <asp:HiddenField ID="hiddn_1" runat="server" />
      <asp:TextBox ID="txtStudent" runat="server" ></asp:TextBox>
        <asp:Button ID="Button1" runat="server" oncommand="Button1_Command"
            Text="Button" />
        <br />
    </div>
    </form>
</body>

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        txtStudent.Text = hiddn_1.Value;
    }
    protected void Button1_Command(object sender, CommandEventArgs e)
    {
        hiddn_1.Value = txtStudent.Text;
    }
}

Here , hidden field hold the value of "txtStudent" , while page load , the process  is reverse

Cookies : Cookies are small text to stored some value .This is like key pair combination.
Cookies are associated with a Web site, not with a specific page, so the browser and server will exchange cookie information no matter what page the user requests from your site.

 protected void Page_Load(object sender, EventArgs e)
    {       
     Response.Cookies["LoggedUsere"].Value = "MyUser";
     Response.Cookies["LoggedUser"].Expires = DateTime.Now.AddDays(1);
    }
    protected void Button1_Command(object sender, CommandEventArgs e)
    {
        HttpCookie obj = new HttpCookie("LoggedUser");
        string loggedUser = Request.Cookies["LoggedUser"].Values.ToString();

    }

Here ,  user values stored in cookies and later retrieved in a sting.

Context.Handler
Context handler just return the immediate previous web page when Server.transfer occure , this does not works for Response.redirect.


public partial class MyContext1 : System.Web.UI.Page
{
    internal string value
    {
        get
        {
            return TextBox1.Text;
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Server.Transfer("MyContext1.aspx");
    }
}

public partial class MyContext2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        MyContext1 largePare;
        largePare = (MyContext1)Context.Handler;
        this.textBox1.Text = largePare.value;
    }
}

Query String 
       This is popularly used in ASP.Net Application . A  string of query can be generated before posting and later while loading field value can be retrive from query .this works for both Server.Transfer and Request.Response.


   protected void Button1_Click(object sender, EventArgs e)
    {
        Server.Transfer("MyContext1.aspx?mText=20");
    }
 

protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["mText"] != null)
        {
            this.Textbox1.Text = Request.QueryString["mText"].ToString();
        }
    }

Session State
Asp.net offer a unique key to each user when a new session begin , this is called session id/ Session key.This key is stored is cookie.In each request client send the key to Server .Session State maintained by Globax.aspx


<%@ Application Language="C#" %>

<script runat="server">

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        Session["MyNumber"] = 100;
    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.

    }
      
</script>

Application State
As ASP.Net is stateless protocal ,it is application state which can hold some value , we can use during page load event to show the value to client .Application variable inisialised when application starts only.


<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        Application["MyAppVarable"] = "100";

    } 
</script>

Catching
Catching is a technique to deliver the same Web Page which is frequently   used without rebuild the page HTML.For I am using page A , after 3 second I called same page A to browser , server will return page A to browse from cache memory.But the question is how many time cache hold the page , which page will hold by cache , there are several caching technique output caching , data catching ,object catching.

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...