Sunday, November 10, 2013

SQL Trigger

 

 

What is a Trigger

A trigger is a special kind of a store procedure that executes in response to certain action on the table like insertion, deletion or updation of data. It is a database object which is bound to a table and is executed automatically. You can’t explicitly invoke triggers. The only way to do this is by performing the required action no the table that they are assigned to.

Types Of Triggers

There are three action query types that you use in SQL which are INSERT, UPDATE and DELETE. So, there are three types of triggers and hybrids that come from mixing and matching the events and timings that fire them.

Basically, triggers are classified into two main types:-

(i) After Triggers (For Triggers)
(ii) Instead Of Triggers

(i) After Triggers

These triggers run after an insert, update or delete on a table. They are not supported for views.
AFTER TRIGGERS can be classified further into three types as:

(a) AFTER INSERT Trigger.
(b) AFTER UPDATE Trigger.
(c) AFTER DELETE Trigger.

Let’s create After triggers. First of all, let’s create a table and insert some sample data. Then, on this table, I will be attaching several triggers.

CREATE TABLE Employee_Test
(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)

INSERT INTO Employee_Test VALUES ('Anees',1000);
INSERT INTO Employee_Test VALUES ('Rick',1200);
INSERT INTO Employee_Test VALUES ('John',1100);
INSERT INTO Employee_Test VALUES ('Stephen',1300);
INSERT INTO Employee_Test VALUES ('Maria',1400);
 
 
I will be creating an AFTER INSERT TRIGGER which will insert the rows 
inserted into the table into another audit table. The main purpose of 
this audit table is to record the changes in the main table. This can be
 thought of as a generic audit trigger. 



Now, create the audit table as:-

CREATE TABLE Employee_Test_Audit
(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
) 


(a) AFTRE INSERT Trigger

This trigger is fired after an INSERT on the table. Let’s create the trigger as:-

CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test] 
FOR INSERT
AS
 declare @empid int;
 declare @empname varchar(100);
 declare @empsal decimal(10,2);
 declare @audit_action varchar(100);

 select @empid=i.Emp_ID from inserted i; 
 select @empname=i.Emp_Name from inserted i; 
 select @empsal=i.Emp_Sal from inserted i; 
 set @audit_action='Inserted Record -- After Insert Trigger.';

 insert into Employee_Test_Audit
           (Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
 values(@empid,@empname,@empsal,@audit_action,getdate());

 PRINT 'AFTER INSERT trigger fired.'
GO
 
The CREATE TRIGGER statement is used to create the trigger. THE ON 
clause specifies the table name on which the trigger is to be attached. 
The FOR INSERT specifies that this is an AFTER INSERT trigger. In place 
of FOR INSERT, AFTER INSERT can be used. Both of them mean the same. 


In the trigger body, table named inserted  has been used. This 
table is a logical table and contains the row that has been inserted. I 
have selected the fields from the logical inserted table from the row 
that has been inserted into different variables, and finally inserted 
those values into the Audit table. 


To see the newly created trigger in action, lets insert a row into the main table as : 
 
 insert into Employee_Test values('Chris',1500); 

Now, a record has been inserted into the Employee_Test table. The AFTER 
INSERT trigger attached to this table has inserted the record into the 
Employee_Test_Audit as:-
 
6   Chris  1500.00   Inserted Record -- After Insert Trigger. 2008-04-26 12:00:55.700 
 

(b) AFTER UPDATE Trigger

This trigger is fired after an update on the table. Let’s create the trigger as:-
CREATE TRIGGER trgAfterDelete ON [dbo].[Employee_Test] 
AFTER DELETE
AS
 declare @empid int;
 declare @empname varchar(100);
 declare @empsal decimal(10,2);
 declare @audit_action varchar(100);

 select @empid=d.Emp_ID from deleted d; 
 select @empname=d.Emp_Name from deleted d; 
 select @empsal=d.Emp_Sal from deleted d; 
 set @audit_action='Deleted -- After Delete Trigger.';

 insert into Employee_Test_Audit
(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
 values(@empid,@empname,@empsal,@audit_action,getdate());

 PRINT 'AFTER DELETE TRIGGER fired.'
GO


In this trigger, the deleted record’s data is picked from the logical deleted table and inserted into the audit table. 


Let’s fire a delete on the main table. 


A record has been inserted into the audit table as:- 
 6  Chris 1550.00  Deleted -- After Delete Trigger.  2008-04-26 12:52:13.867 

All the triggers can be enabled/disabled on the table using the statement 


ALTER TABLE Employee_Test {ENABLE|DISBALE} TRIGGER ALL Specific Triggers can be enabled or disabled as :-
ALTER TABLE Employee_Test DISABLE TRIGGER trgAfterDelete
 
This disables the After Delete Trigger named trgAfterDelete on the specified table. 


(ii) Instead Of Triggers

These can be used as an interceptor for anything that anyonr tried to do on our table or view. If you define an Instead Of trigger on a table for the Delete operation, they try to delete rows, and they will not actually get deleted (unless you issue another delete instruction from within the trigger)
INSTEAD OF TRIGGERS can be classified further into three types as:-

(a) INSTEAD OF INSERT Trigger.
(b) INSTEAD OF UPDATE Trigger.
(c) INSTEAD OF DELETE Trigger.

(a) Let’s create an Instead Of Delete Trigger as:-
CREATE TRIGGER trgInsteadOfDelete ON [dbo].[Employee_Test] 
INSTEAD OF DELETE
AS
 declare @emp_id int;
 declare @emp_name varchar(100);
 declare @emp_sal int;
 
 select @emp_id=d.Emp_ID from deleted d;
 select @emp_name=d.Emp_Name from deleted d;
 select @emp_sal=d.Emp_Sal from deleted d;

 BEGIN
  if(@emp_sal>1200)
  begin
   RAISERROR('Cannot delete where salary > 1200',16,1);
   ROLLBACK;
  end
  else
  begin
   delete from Employee_Test where Emp_ID=@emp_id;
   COMMIT;
   insert into Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
   values(@emp_id,@emp_name,@emp_sal,'Deleted -- Instead Of Delete Trigger.',getdate());
   PRINT 'Record Deleted -- Instead Of Delete Trigger.'
  end
 END
GO

 This trigger will prevent the deletion of records from the table where 
Emp_Sal > 1200. If such a record is deleted, the Instead Of Trigger 
will rollback the transaction, otherwise the transaction will be 
committed. 


Now, let’s try to delete a record with the Emp_Sal >1200 as:- 



delete from Employee_Test where Emp_ID=4 

This will print an error message as defined in the

RAISE ERROR statement as:-


Server: Msg 50000, Level 16, State 1, Procedure trgInsteadOfDelete, Line 15 Cannot delete where salary > 1200 
   
And this record will not be deleted.
In a similar way, you can code Instead of Insert and Instead Of Update triggers on your tables.




Ref : Code Project

Tuesday, November 5, 2013

ASP.NET MVC (Model View Controller) Architecture

   




         “M” “V” “C” stands for “MODEL” “VIEW” “CONTROLLER”. ASP.NET MVC is an architecture to develop ASP.NET web applications in a different manner than the traditional ASP.NET web development. Web applications developed with ASP.NET MVC are even more SEO (Search Engine) friendly. 

Developing ASP.NET MVC application requires Microsoft .NET Framework 3.5 or higher. 

MVC Interaction with Browser

 Like a normal web server interaction, MVC application also accepts requests and responds to the web browser in the same way.

Inside MVC Architecture

The entire ASP.NET MVC architecture is based on Microsoft .NET Framework 3.5 and in addition uses LINQ to SQL Server.

What is a Model?

  1. MVC model is basically a C# or VB.NET class
  2. A model is accessible by both controller and view
  3. A model can be used to pass data from Controller to view
  4. A view can use model to display data in page.

What is a View?

  1. View is an ASPX page without having a code behind file
  2. All page specific HTML generation and formatting can be done inside view
  3. One can use Inline code (server tags ) to develop dynamic pages
  4. A request to view (ASPX page) can be made only from a controller’s action method
What is a Controller?
  1. Controller is basically a C# or VB.NET class which inherits system.mvc.controller
  2. Controller is a heart of the entire MVC architecture
  3. Inside Controller’s class action methods can be implemented which are responsible for responding to browser OR calling views.
  4. Controller can access and use model class to pass data to views
  5. Controller uses ViewData to pass any data to view



MVC File Structure & File Naming Standards

MVC uses a standard directory structure and file naming standards which are a very important part of MVC application development.
Inside the ROOT directory of the application, there must be 3 directories each for model, view and Controller.
Apart from 3 directories, there must have a Global.asax file in root folder, and a web.config like a traditional ASP.NET application.
  • Root [directory]
    • Controller [directory]
      • Controller CS files
    • Models [directory]
      • Model CS files
    • Views [directory]
      • View aspx/ascx files
    • Global.asax
    • Web.config

ASP.NET MVC Execution Life Cycle

Here is how MVC architecture executes the requests to browser and objects interactions with each other.
A step by step process is explained below [Refer to the figure as given below]:



Browser Request (Step 1)

Browser request happens with a specific URL. Let’s assume that the user enters URL like: [xyz.com]/home/index/

Job of Global.asax – MVC routing (Step 2)

The specified URL will first get parsed via application_start() method inside Global.asax file. From the requested URL, it will parse the Controller, Action and ID.
So for [xyz.com]/home/index/:
  • Controller = home
  • Action = index()
  • ID = empty — we have not specified ID in [xyz.com]/home/index/, so it will consider as empty string

Controller and Action methods (Step 3)

MVC now finds the home controller class in controller directory. A controller class contains different action methods,
There can be more than one action method, but MVC will only invoke the action method which has been parsed from the URL, its index() in our case.
So something like: homeController.index() will happen inside MVC controller class.
Invoking action method can return plain text string OR rendered HTML by using view.

Call to View (Step 4)

Invoking view will return view(). A call to view will access the particular ASPX page inside the view directory and generate the rendered HTML from the ASPX and will respond back to the browser.
In our case, controller was home and action was index(). So calling view() will return a rendered HTML from the ASPX page located at /views/home/index.aspx.


 Reference :Code poroject

Thursday, October 24, 2013

SQL Server database Triggers


Overview

                 Implementing business rules as well as performing validation or data modifications, triggers are the best use for this purpose when other methods are not sufficient. Triggers are normally used in two areas: creating audit records and reflecting changes to crucial business tables, and validating changes against a set of business rules coded in T-SQL.

In this blog, I would like to demonstrate how to create triggers, use of triggers, different types of triggers and performance considerations.

 What is a Trigger?


   A database trigger is a stored procedure that is invoked automatically when a predefined event occurs. Database triggers enable DBAs (Data Base Administrators) to create additional relationships between separate databases. In other ways, a trigger can be defined to execute before or after an INSERT, UPDATE, or DELETE operation, either once per modified row, or once per SQL statement. If a trigger event occurs, the trigger's function is called at the appropriate time to handle the event.

     Triggers can be assigned to tables or views. However, although there are two types of triggers, INSTEAD OF and AFTER, only one type of trigger can be assigned to views. An INSTEAD OF trigger is the one that is usually associated with a view, and runs on an UPDATE action placed on that view. An AFTER trigger fires after a modification action has occurred.
From a performance viewpoint, the fewer the triggers, the better, as we will invoke less processes. Therefore, do not think that having one trigger per action to make things modular will not incur performance degradation. A trigger's main overhead is referencing either two specialist tables that exist in triggers – deleted and inserted or other tables for business rules. Modularizing triggers to make the whole process easier to understand will incur multiple references to these tables, and hence a greater overhead.

Note: It is not possible to create a trigger to fire when a data modification occurs in two or more tables. A trigger can be associated only with a single table.


Why Use Triggers?

To improve data integrity, trigger can be used. When an action is performed on data, it is possible to check if the manipulation of the data concurs with the underlying business rules, and thus avoids erroneous entries in a table. For example:

    We might want to ship a free item to a client with the order, if it totals more than $1000. A trigger will be built to check the order total upon completion of the order, to see if an extra order line needs to be inserted.
    In a banking scenario, when a request is made to withdraw cash from a cash point, the stored procedure will create a record on the client's statement table for the withdrawal, and the trigger will automatically reduce the balance as required. The trigger may also be the point at which a check is made on the client's balance to verify that there is enough balance to allow the withdrawal. By having a trigger on the statement table, we are secure in the knowledge that any statement entry made, whether withdrawal or deposit, will be validated and processed in one central place.

Note: We discuss only data integrity here, and not referential integrity.

Another use of triggers can be to carry out an action when a specific criterion has been met. One example of this is a case where an e-mail requesting more items to be delivered is sent, or an order for processing could be placed, when stock levels reach a preset level. However, if we insert data into another table from within a trigger, we have to be careful that the table we insert into doesn't have a trigger that will cause this first trigger to fire. It is possible to code triggers that result in an endless loop, as we can define a trigger on TableA, which inserts into TableB, and a trigger for TableB, which updates TableA. This scenario will ultimately end in an error being generated by the SQL Server. The following diagram will demonstrate this:
 



Figure 1

    A stored procedure, A, updates TableA.
    This fires a trigger from TableA.
    The defined trigger on TableA updates TableB.
    TableB has a trigger which fires.
    This trigger from TableB updates TableA.


Creating and Using a Trigger 

A trigger is a special kind of stored procedure that automatically executes when an event occurs in the database server. DML triggers execute when a user tries to modify data through a data manipulation language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view. More details can be found at this link.
CREATE TRIGGER Statement

The CREATE TRIGGER statement defines a trigger in the database.
Invocation

This statement can be embedded in an application program or issued through the use of dynamic SQL statements. It is an executable statement that can be dynamically prepared only if DYNAMICRULES run behavior is in effect for the package (SQLSTATE 42509).
Authorization

The privileges held by the authorization ID of the statement must include at least one of the following:

    ALTER privilege on the table on which the BEFORE or AFTER trigger is defined
    CONTROL privilege on the view on which the INSTEAD OF TRIGGER is defined
    Definer of the view on which the INSTEAD OF trigger is defined
    ALTERIN privilege on the schema of the table or view on which the trigger is defined
    SYSADM or DBADM authority and one of:
        IMPLICIT_SCHEMA authority on the database, if the implicit or explicit schema name of the trigger does not exist
        CREATEIN privilege on the schema, if the schema name of the trigger refers to an existing schema

If a trigger definer can only create the trigger because the definer has SYSADM authority, the definer is granted explicit DBADM authority for the purpose of creating the trigger.


Syntax of a Trigger


CREATE TRIGGER name ON table
   [WITH ENCRYPTION]
   [FOR/AFTER/INSTEAD OF]
   [INSERT, UPDATE, DELETE]
   [NOT FOR REPLICATION]
AS
BEGIN
--SQL statements
...
END  

Sample Example 

Let’s take an example. We have a table with some columns. Our goal is to create a TRIGGER which will be fired on every modification of data in each column and track the number of modifications of that column. The sample example is given below:


-- ==========================================================
-- Author: Md. Marufuzzaman
-- Create date:
-- Description: Alter count for any modification 
-- ===========================================================
CREATE TRIGGER [TRIGGER_ALTER_COUNT] ON [dbo].[tblTriggerExample]
FOR INSERT, UPDATE
AS
BEGIN
DECLARE @TransID  VARCHAR(36)
 SELECT @TransID = TransactionID FROM INSERTED
 UPDATE [dbo].[tblTriggerExample] SET AlterCount = AlterCount + 1
          ,LastUpdate = GETDATE()
    WHERE TransactionID = @TransID
END 




Types of Triggers

There are three main types of triggers that fire on INSERT, DELETE, or UPDATE actions. Like stored procedures, these can also be encrypted for extra security. More details can be found at this link.
Good Practice

The most important point is to keep the trigger as short as possible to execute quickly, just like stored procedures. The longer a trigger takes to fire, the longer the locks will be held on the underlying tables. To this end, we could place cursors within a trigger, but good practice dictates that we don't. Cursors are not the fastest of objects within a database, and we should try and revisit the problem with a different solution, if we feel the need for cursors. One way around the problem may be to run two, or perhaps, three updates, or even use a temporary table instead.

Use triggers to enforce business rules, or to complete actions that have either a positive effect on the organization, or if an action will stop problems with the system. An example of this is creation of a trigger that will e-mail a client when an order is about to be shipped, giving details of the order, and so on.

Reference :Code poroject