Instead of Update Trigger in SQL Server


Instead of Update Trigger

To Create INSTEAD OF UPDATE Triggers first of all we need to create a table (but we create two table) for which we apply trigger and need another table that hold all activity in main table.
-- We create tblDeparment

create table tblDeparment(
Id int identity(1,1) primary key not null,
DeparmentName varchar(30) not null,
Location Char(8) not null,
DeparmentHead varchar(20) not null
)

--Insert data into tblDeparment

Insert into tblDeparment values('IT','London','Carrie')
Insert into tblDeparment values('HR','Mexico','Toy')
Insert into tblDeparment values('Purchasing','Delhi','Ravi')
Insert into tblDeparment values('Finance','New York','Janie')

--Now crate table tblEmployee

create table tblEmployee(
Id int identity(1,1) primary key not null,
Name varchar(30) not null,
Gender Char(8) not null,
DeparmentId int null constraint FK_tblEmployee_DeparmentId foreign key(DeparmentId) references tblDeparment(Id)
)

--Insert data into tblEmployee 

insert into tblEmployee values('Jane', 'Female', 1) 
insert into tblEmployee values('Levis', 'Male', 3)
insert into tblEmployee values('Lee', 'Female', Null)
insert into tblEmployee values('Rose', 'Female', 1)
Here we create two table “tblDeparment” and “tblEmployee “ which are inter-connected through Foreign key constraint.

We will apply trigger for these tables.

Now create table that hold activity of main table by user.
create table tblAudit
(
Id int primary key identity(1,1) not null,
AuditData nvarchar(500)
) 
We have table are given below with data.
instead-of-update-triggers
Created All tables for Instead of Update Triggers

Now create the INSTEAD OF UPDATE Trigger for “tblEmployee”.
create trigger trtblEmployeeInsteadOfUpdate
on tblEmployee
INSTEAD OF update
AS
  BEGIN
     Declare @EmpId int,               
             @EmpMessage varchar(200),
             @Name varchar(30), @Gender varchar(8),
             @DepartmentId int;
     select  @EmpId =D.Id 
             from deleted D;
     select  @Name = I.Name, 
             @Gender = I.Gender,
             @DepartmentId= DeparmentId from Inserted I;
             
      
     If(Not exists(Select Id from tblEmployee where Id = @EmpId))   --If Id not Exists in Cloumn than through message. you can check other condition like departmentId =1 or Gender=Male, than you can print message you can not delete
       Begin
           SET @EmpMessage  = 'Employee With Id ' + CAST(@EmpId as varchar(5)) + 'Not Exists in the DataBase'
           Raiserror(@EmpMessage, 16, 1)
           Print 'Employee Not Exists'
           RollBack
       End
       Else
          Begin
            if(UPDATE(Name))
              begin
                 update tblEmployee set Name = @Name where Id= @EmpId
              end
             If(UPDATE(Gender))
               begin
                 update tblEmployee set Gender =@Gender where Id= @EmpId
               end
             If(UPDATE(DeparmentId))
               begin
                 update tblEmployee set DeparmentId =@DepartmentId where Id= @EmpId
               end
             insert into tblAudit values('Employee succefully Update with Id ' + CAST(@EmpId as varchar(5)) + 'and insert into trigger in date' + CAST(Getdate() AS nvarchar(30)))
          End
  END
Now try to Update data from tblEmployee, If we try to update id which is not exists than return message Employee with Id not exits
update tblEmployee set Name= 'janee' where id=5
Instead-of-update-Trigger-show-message
Show Message Employee Not Exit
Now we try to Update id which is already exists return message successfully row effect
update tblEmployee set Name= 'janee' where id=1
Now check data from tables.
Instead-of-update-trigger
Select all tables After, Instead of  Update Trigger fire


Example 2

For more understand about INSTEAD OF UPDATE Trigger we take another trigger example.

First we create another table that hold all activity of main table done by user.

create table tblAuditDetailsBy
(
  Id int not null Primary key identity(1,1),
  EmpId int Not Null,
  EmpOldName varchar(30) Not Null,
  EmpNewName varchar(30) Not Null,
  EmpOldGender char(8) Not Null,
  EmpNewGender char(8) Not Null,
  EmpOldDeparmentId int Not Null,
  EmpNewDeparmentId int Not Null,
  AuditAction varchar(1000) Not Null,
  ActionTakenBy varchar(50) Not Null,
  AuditTime datetime not null default Getdate(),
  ServerName varchar(100) Not Null,
  ServerInstanceName varchar(100) Not Null
)
Now create the INSTEAD OF UPDATE Trigger for “tblEmployee”
create trigger trtblEmployeeInsteadOfDeleteByDetail
ON tblEmployee
INSTEAD OF UPDATE
As
 BEGIN
     Declare @EmpId int, 
             @OldEmpName varchar(30), @NewEmpName varchar(30),            
             @OldEmpGender varchar(8), @NewEmpGender varchar (8),
             @OldEmpDepatmentId int, @NewEmpDepatmentId int,
             @EmpMessage varchar(300),@AuditAction varchar(2000),
             @ActionTakenBy varchar(100),@AuditTime varchar(50),
             @ServerName varchar(100), @ServerInstanceName Varchar(100);
     select  @EmpId=D.Id,             --Id Not Change
             @OldEmpName = D.Name, 
             @OldEmpGender = D.Gender,
             @OldEmpDepatmentId = D.DeparmentId from deleted D;
     select  @NewEmpName = I.Name, --delete not only keep id column value, keep all column value for which id we want delete. 
             @NewEmpGender= I.Gender, @NewEmpDepatmentId= I.DeparmentId
             from inserted I
      
     If not exists(Select Id from tblEmployee where Id = @EmpId)   --If Id not Exists in Cloumn than through message, you can check other condition like departmentId =1 or Gender=Male, than you can print message you can not delete
       Begin
           SET @EmpMessage  = 'Employee With Id ' + CAST(@EmpId as varchar(5)) + 'Not Exists in the DataBase.'
           Raiserror(@EmpMessage, 16, 1)
           Print 'INSTEAD OF Update Triggers in SQL Server not fire because Employee Not Exists' 
           RollBack
       End
       Else
          Begin
             SET @AuditAction='Update Record '
             If(@OldEmpName <> @NewEmpName)
               begin
                  set @AuditAction = @AuditAction + 'Name from ' + @OldEmpName + 'to ' + @NewEmpName + ', '
                  update tblEmployee set Name= @NewEmpName where id=@EmpId
               end
             If(@OldEmpGender <> @NewEmpGender)
               begin
                 set @AuditAction =@AuditAction + 'Gender from ' + @OldEmpGender + 'to ' + @NewEmpGender + ', '
                 update tblEmployee set Gender= @NewEmpGender where id=@EmpId
               end
             If(@OldEmpDepatmentId <> @NewEmpDepatmentId)
               begin
                 set @AuditAction =@AuditAction + 'DeaparmentId from ' + CAST(@OldEmpDepatmentId as varchar(10)) + 'to ' + CAST(@NewEmpDepatmentId As varchar(10))+ ', '
                 update tblEmployee set DeparmentId= @NewEmpDepatmentId where id=@EmpId
               end
    set @ActionTakenBy = SYSTEM_USER;
 set @ServerName = CAST( SERVERPROPERTY('ServerName') AS VARCHAR(50));          -- select @@SERVERNAME return server name
 set @ServerInstanceName = CAST( SERVERPROPERTY('MachineName') AS VARCHAR(50));    --SELECT @@servicename return current machine name
             
            insert into tblAuditDetailsBy (EmpId, EmpOldName, EmpNewName, EmpOldGender, EmpNewGender,
                                 EmpOldDeparmentId, EmpNewDeparmentId, AuditAction,
                                ActionTakenBy, AuditTime,ServerName,ServerInstanceName)
                         values(@EmpId,@OldEmpName, @NewEmpName, @OldEmpGender, @NewEmpGender,
                                @OldEmpDepatmentId, @NewEmpDepatmentId, @AuditAction,
                                @ActionTakenBy,GETDATE(), @ServerName, @ServerInstanceName)
             PRINT 'Successfully Delete Data with ID= ' + CAST(@EmpId as varchar(5)) + CAST(Getdate() AS nvarchar(30));
             PRINT 'Fired the INSTEAD OF Update Triggers in SQL Server'
          End
 END
Now try to Update data from tblEmployee, If we try to Update id which is not exists than return message Employee with Id not exits
update tblEmployee set Name= 'jhone', Gender='Male' where id=5
But If we try to Update id which is already exists return message successfully row effect
update tblEmployee set Name= 'jhone', Gender='Male' where id=1
Instead-of-update-trigger
Update Tables

Now check data from tables.
select all-tables-for-Instead-of-update-tables




Response.Redirect in ASP.NET and use of EndResponse


Response.Redirect in ASP.NET


In the previous part we study about what is page navigation and there types and also study HyperLink type page navigation technique in detail. In this part we will study about Response.Redirect which also one of the navigation techniques in ASP.NET which is use to move from one web form to another that means use to redirect a user to another URL.

According to MSDN website it redirect to new URL whether execution of the current page terminated.

Redirect is a method of the HttpResponse class in ASP.NET applications, when hover mouse on it Response class and return type is void.

The HttpResponse class has two overloaded method of versions of the Redirect.

The first method takes one input parameter as a URL of the other page.
e.g.  Response.Redirect("~/default.aspx");

response.redirect c# true false


Another one is take two parameters, one as a URL and second is a Boolean value (true or false).
Response.Redirect("~/default.aspx",false);    // means current page execution is not terminated and code written after the Response.Redirect("default.aspx", false) is executed and then after the page is redirected to the default.aspx.
or
Response.Redirect("~/default.aspx",true); 
When we try to use Response.Redirect("default.aspx", false) in a page then the execution of current page is not terminated instead of this code written after the Response.Redirect is executed and then after that page is redirected to the given page.

When we try to use Response.Redirect("default.aspx",true) which is by default true then the execution of current page is terminated and code written after the Response.Redirect is not executed instead of executing code written after the Response.Redirect ,the page is redirected to the given page.

Note:-

1. When you use the first overloaded version in the code, the second overloaded version is called automatically and endResponse passed True .

2. When we pass false as second parameter value that indicates we do not want an exception to be thrown to terminate the page. 3. When we use overloaded method, URL (string type) is mandatory parameter and endResponse (Boolean type, by default true) is optional parameter.

4. URL is the string parameter which takes the url or page name and endResponse is the boolean parameter which has true and false values.

We create z-test.aspx page in ASP.NET and drag and drop buttons control in this page from toolbox.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="z-test.aspx.cs" Inherits="AspDotNets.z_test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
<asp:Button ID="button1" runat="server" Text="Button 1" OnClick="button1_Click" /><br />
<asp:Button ID="button2" runat="server" Text="Button 2" OnClick="button2_Click"/><br /> 
 <asp:Button ID="button3" runat="server" Text="Button 3" OnClick="button3_Click" /><br />
<asp:Button ID="button4" runat="server" Text="Button 4" OnClick="button4_Click" /><br />
</form>
</body>
</html>
Now write the code in code behind (z_test.aspx.cs).
using System;
namespace AspDotNets
{
    public partial class z_test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
        protected void button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/test2.aspx");
        }
        protected void button2_Click(object sender, EventArgs e)
        {
            Session["Before_redirect"] = "This String is Before Response.Redirect When EndResponse values is false"; 
            Response.Redirect("~/z-test2.aspx",false);
            Session["After_redirect"] = "This String is after Response.Redirect When EndResponse values is false"; 

        }
        protected void button3_Click(object sender, EventArgs e)
        {
            Session["Before_redirect"] = "This String is Before Response.Redirect When EndResponse values is true"; 
            Response.Redirect("~/z-test2.aspx",true);
            Session["After_redirect"] = "This String is after Response.Redirect When EndResponse values is true"; 
        }
        protected void button4_Click(object sender, EventArgs e)
        {
            Response.Redirect("http://web-designing-developing-tutorials.blogspot.in/");
        }

    }
}
Now create a webform (z-test2.aspx) and write the code in code behind (z_test2.aspx.cs).
using System;
namespace AspDotNets
{
    public partial class z_test2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("String receive from session variable Before_redirect =" + Session["Before_redirect"] + ""); 
            Response.Write("String receive from session variable After_redirect =" + Session["After_redirect"]);        
        }
     }
}
When click on Button 1

When click button1 than simply transfer to page z-test2.aspx. In button 1 we does not transfer any value to z-test.aspx.cs because we does not use session variable in button1.

But if click first button 2, or 3 than click one than session store string in session variable because Session variable store by default 20 min. In detail we study later part.

When click on Button 2

String store in session variables “Before_redirect” and “After_redirect” just before and after Response.Redirect, these session variables strings will be accessed on another page (we name it z-test2.aspx).

If we try to access these session on the other page both before and after session will be accessed because execution of current page is not terminated when EndResponse values is false. i.e code after Response.Redirect will be accessed.


When click on Button 3

Similarly as in button2 string store in session variables “Before_redirect” and “After_redirect” just before and after Response.Redirect, these session variables strings will be accessed on another page.

If we try to access these session on the other page only before Response.Redirect session will be accessed and after session will not be accessed because execution of current page is terminated when EndResponse values is true.


When click on Button 4

When click button4 it move to web-designing-developing-tutorials.blogspot blogger.

Note:-

1. The button 3 rule also apply for button 1 because EndResponse by default true if not use EndResponse.

2. If you use our code to learn than first click on Button1, Button2, than Button3 on order because Session variable store by default 20 min. In detail we study later part.

Understand Response.Redirect flow between client-and-server

When we use response.redirect, there are two request-response cycle round trip will be happend, Suppose, when we click on button immediately postback response is happened for the page and send to web server have code for respose.redirect than web server send response header back to the client and then client initiate new request for the new page and web server receive the request and process and send html page back to the client browser, this type of page navigation technique does not involve two response cycle.

Initial request with redirect                                               
                             ----------------------->

                            Got Response header from server
                           <--------------------------
       Client                                                      Web Server
                              New Request Initiated
                            ------------------------>

                           Response sent back as HTML
                           <-------------------------

NOTE:-

1. Reponse.Redirect is maintained browser history which help to back previous using back button. Redirect can be used to navigate pages/website on the same web server or different web server.

2. Response.Redirect is similar to the HyperLink technique use to navigate any website/Pages on same webserver or different web server.
In the above example, in button4_click event is satisfy this rule. 3. Due to Round trip it is bit slow.

4. After sending headers to the client and try to redirect, you receive an HttpException exception error.

Interview Question:-


Q1. What is difference between Response.Redirect true and Response.Redirect false and Rsponse.Redirect?



previous Related Post



Page navigation techniques in asp.net-Hyperlink


Page Navigation


In this part we will study what is page navigation technique? Why use them? Basically there are different types of page navigation technique in ASP.NET but each technique has its own importance and benefits, and which page-navigation technique should be used depends on the current scenario of the application.

Page Navigation technique in the ASP.NET
1. HyperLink Control
2. Rsponse.Redirect
3. Server.Execute
4. Cross Page PostBack
5. Window.Open

Page-Navigation use to navigate a page by suggested path. Not only you navigate a page you can also apply website navigation.

In real time in web application we need to navigate a page from one page to another page, but if not properly navigate than through an error at runtime (like 404 error).

Hyperlink


The easiest way to navigate from one web page to another web page with an ASP.NET hyperlink control.

Hyper link control maintain the history, Hyper link control is a like html anchor tag, which is use to navigate same web-server or different server.

Hyperlink does not expose server side events, so when user click on a HyperLink, there is no server side event to intercept the click where button click event is intercept.

We create Page-Navigation.aspx page in ASP.NET and drag and drop HyperLink control in this page from toolbox.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Page-Navigation.aspx.cs" Inherits="AspDotNets.Page_Navigation" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
      <asp:HyperLink ID="hyperlink1" runat="server" NavigateUrl="~/Default.aspx" Text="Navigate to another page"></asp:HyperLink><br/>
<a href="~/Default.aspx" title=""> Navigate to another page</a>
    </form>
</body>
</html>
You can see in the above example we link Default.aspx page in the NavigateUrl property.

We also developed an anchor tag (a href link), which also move to the same page (Default.aspx) when click on anchor tag as we said above hyperlink control of ASP.NET is similar to anchor tag of html.

We create another webform to which we want to navigate through Hyperlink and we name it Default.aspx.

In the above example we show, this is the one of the simple and good website (paste link of website path in navigateUrl) or page navigation method through which we simply navigate a page from one page to another page.



difference between tier and layer architecture in ASP.NET


Before understand difference between n/3 tier architecture in asp.net or n/3 layer architecture we have to understand first of all what is Tier and What is layer?

Layer and Tier


The layers reside on the same machine where the tiers can reside on different machines i.e. an individual running server is one tier, which may mean different assemblies such as DLL, EXE, etc. on the same server or multiple servers, that means we can say that Layer is logical separation of code and Tier is physical separation of code i.e. Tiers are the physical deployment of layers. In other words we can say that Tier Architecture is a physical structuring system where as Layer Architecture is a logical structuring system.

Layer is a good way to achieve tier architecture. Layer and tier may or may not exactly match each other. Each layer may run in an individual tier. However, multiple layers may also be able to run in one tier.

Layer communicates with each other either by Value or by Reference while tier communicate by Value only – as serialized objects.

The 3/n-layer/Tier application has mainly three layers.
1. Presentation Layer
2. Business Logic Layer
3. Data Access Layer

Presentation Layer


The Presentation Layer is basically responsible for displaying the user interface page like ASP.NET, ASPX pages, user controls, html page to the end user, So it is very important layer for getting user data and pass to Business Logic Layer for further operation, and when data is received in Value Object then it’s responsible to represent value object in the appropriate form which user can understand easily.

Business Logic Layer


The Business Logic Layer (BLL) is basically contains all the calculations and business rule that are required in the development of the application. C# business logic layer act as a bridge between Presentation Layer and data Access layer. In this layer the all the functionality that get data from the Presentation Layer and send that data to database through Data Access Layer.

Data Access Layer


The Data Access Layer (DAL) is basically gets the data from the business layer and sends it to the database or vice versa. DAL is responsible for accessing data and forwarding it to BLL. In an ASP.NET n­Tier architecture, web pages do not make direct access to the database

prestation-layer-bussiness-layer-data-access-layer-architecture
3/n- Layer/Tier Architecture
 Advantage:-

1. Presentation layer can only access the public components in application layer, but not in data layer where as Application layer can only access the public components in data layer, but not in presentation layer. This process can minimize the dependencies of layers on each other and provide finer security control to the whole system.

2. Since each layer are independent so it is easy to change one database storage too another database storage like from MS SQL Server to oracle.

3. Suppose we need to change some change in business access layer than no need to change in data access layer i.e. if we change in business layer than data layer no effect.

e.g. recently The Indian Govt. change our Tax system, than Indian Govt. only need to update business logic system without changing or affecting in the other system.

Disadvantages:-

1. If we use n- tier application in our project, we know it has great advantage but still it has some disadvantage, the performance of the entire system may be slow if the hardware and network, computers and processes aren’t good enough for the system.

2. Cost of the entire System may be hike because more hardware, network system involved..

3. Maintenance and deployment of the system become difficult because more hardware and better network bandwidth are needed for deployment and maintenance.

Note:-
All above layers are able to run in three separate computers. Practically, these three layers can also be deployed in one computer ﴾3‐Tier architecture, but deployed as 1‐Tier﴿.

3-Layer:-

In 3 layer architecture , the Database Access Layer (DAL), Business Logic Layer (BLL) and User Interface Layer (UIL) resides as 3 different project and the output of these 3 projects must be together in the same server or on same machine in order for the system to run.
In 3 layer architecture DAL, BLL and UIL can work on same machine.

3-Tier:-

In three tier architecture the Database Access Layer (DAL), Business Logic Layer (BLL) and User Interface Layer (UIL) reside as 3 different projects. But each of the projects can be deployed at the different server or at the different machines and distributed functionality is explored.

In three tier architecture in asp net c# a client in on one machine, the application Server is hosted in another machine and the database server resides in another machine i.e. Three-tier is a client–server architecture in which the User Interface, Business Logic , Data Storage and Data Access are developed and maintained as independent modules on separate platforms.

N-Tier:-

We hear a lot of time about c# n tier architecture even some of us read or use N‐Tier architecture for many time but still misunderstand its concepts of it. In this part we tries to clarify many basic concepts in N‐Tier architecture and we will also provide some industry based examples in the next parts.

N-tier architecture is probably one of the most used architecture models in the usually use in industry software architecture model, N-tier supports client/server applications by solving many points like scalability, security, extensible, secure and maintainable, over time, functionality and many more which helps the developers with different roles to better do their job without interfering with each other.

Visual studio have no pre‐defined tools or process that tell how to implement or solve the N-Tier architecture so it is very necessary to understand full concept of N-Tier before implementation.

N‐tier data applications are data applications that are separated into multiple tiers. Also called distributed applications and multitier applications. N‐tier application includes a presentation tier, a middle tier, and a data tier.

During Development of the n tier application or n layer application we need to keep in mind some points which are given below.

1.   All Application tier or layer must be independent to each other.

2.   Each component and module must be responsible for specific feature or functionality.

3.   Each functionality must be define once in the application

4.   Your application must be developed as like whenever you need to add new layer/tier or change technology you can implement easily.

5.   Most important point to remember must set some coding standard, Each developer has own standard coding style.