Professional Documents
Culture Documents
User makes a request for accessing application resource, a page. Browser sends
this request to the web server.
A unified pipeline receives the first request and the following events take place:
Page request - When ASP.NET gets a page request, it decides whether to parse
and compile the page, or there would be a cached version of the page;
accordingly the response is sent.
Starting of page life cycle - At this stage, the Request and Response objects
are set. If the request is an old request or post back, the IsPostBack property of
the page is set to true. The UICulture property of the page is also set.
Page initialization - At this stage, the controls on the page are assigned
unique ID by setting the UniqueID property and the themes are applied. For a
new request, postback data is loaded and the control properties are restored to
the view-state values.
Page load - At this stage, control properties are set using the view state and
control state values.
Page rendering - At this stage, view state for the page and all controls are
saved. The page calls the Render method for each control and the output of
rendering is written to the OutputStream class of the Response property of
page.
Unload - The rendered page is sent to the client and page properties, such as
Response and Request, are unloaded and all cleanup done.
PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack
property and determines whether the page is a postback. It sets the themes
and master pages, creates dynamic controls, and gets and sets profile property
values. This event can be handled by overloading the OnPreInit method or
creating a Page_PreInit handler.
Init - Init event initializes the control property and the control tree is built. This
event can be handled by overloading the OnInit method or creating a Page_Init
handler.
PreLoad - PreLoad occurs before the post back data is loaded in the controls.
This event can be handled by overloading the OnPreLoad method or creating a
Page_PreLoad handler.
Load - The Load event is raised for the page first and then recursively for all
child controls. The controls in the control tree are created. This event can be
handled by overloading the OnLoad method or creating a Page_Load handler.
PreRender - The PreRender event occurs just before the output is rendered. By
handling this event, pages and controls can perform any updates before the
output is rendered.
UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the
UnLoad event for all controls recursively and lastly for the page itself. Final
cleanup is done and all resources and references, such as database connections,
are freed. This event can be handled by modifying the OnUnLoad method or
creating a Page_UnLoad handler.
Another reason is that it is easier to control a state of a private field/property. For example,
in the sample code above, imagine StartEngine is performing some tasks, then
assigning true to this.isEngineStarted. If isEngineStarted is public, another class would be
able to set it to true, without performing tasks made by StartEngine. In this case, the value
of isEngineStarted will be unreliable.
Once you have done the insert don't forget to turn identity_insert off
EXEC sp_msforeachdb
'if exists(select 1 from [?].sys.objects where name=''loadDocuments'')
select ''?'' as FoundInDatabase from [?].sys.objects where name=''loadDocuments'''
Basic Difference
1. Function must return a value but in Stored Procedure it is optional (Procedure can return zero or n values).
2. Functions can have only input parameters for it whereas Procedures can have input/output parameters.
3. Functions can be called from Procedure whereas Procedures cannot be called from Function.
Advance Difference
1. Procedure allows SELECT as well as DML (INSERT/UPDATE/DELETE) statement in it whereas Function allows
only SELECT statement in it.
2. Procedures cannot be utilized in a SELECT statement whereas Function can be embedded in a SELECT
statement.
3. Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section
whereas Function can be.
4. The most important feature of stored procedures over function is to retention and reuse the execution plan while
in case of function it will be compiled every time.
5. Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables.
6. Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset
operations.
7. Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a
Function.
8. We can go for Transaction Management in Procedure whereas we can't go in Function.
Differences between Stored Procedure and User Defined Function in SQL Server
Sr.No
User Defined Function Stored Procedure
.
1 Function must return a value. Stored Procedure may or not return values.
Will allow only Select statements, it will not Can have select statements as well as DML statements such
2
allow us to use DML statements. as insert, update, delete and so on
It will allow only input parameters, doesn't
3 It can have both input and output parameters.
support output parameters.
4 It will not allow us to use try-catch blocks. For exception handling we can use try catch blocks.
5 Transactions are not allowed within functions. Can use transactions within Stored Procedures.
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:
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.
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.
Hide Copy Code
CREATE TABLE Employee_Test_Audit
(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)
Hide Copy Code
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);
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:
Hide Copy Code
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:
Hide Copy Code
6 Chris 1500.00 Inserted Record -- After Insert Trigger. 2008-04-26 12:00:55.700
Hide Copy Code
CREATE TRIGGER trgAfterUpdate ON [dbo].[Employee_Test]
FOR UPDATE
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;
if update(Emp_Name)
set @audit_action='Updated Record -- After Update Trigger.';
if update(Emp_Sal)
set @audit_action='Updated Record -- After Update Trigger.';
The AFTER UPDATE Trigger is created in which the updated record is inserted into the audit table.
There is no logical table updated like the logical table inserted. We can obtain the updated value
of a field from theupdate(column_name) function. In our trigger, we have used, if
update(Emp_Name) to check if the column Emp_Name has been updated. We have similarly
checked the column Emp_Sal for an update.
Hide Copy Code
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);
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:
All the triggers can be enabled/disabled on the table using the statement
This disables the After Delete Trigger named trgAfterDelete on the specified table.
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:
Answer: Magic tables are nothing but inserted and deleted which are temporary object created by
server internally to hold the recently inserted values in the case of insert and to hold recently deleted
values in the case of delete, to hold before updating values or after updating values in the case of
update.
SELECT 1 + GETDATE() + 1
SELECT TOP 1 * FROM Table1 ORDER BY NEWID()
E.g. : HttpHandler components are good for situations in which you want to return XML,
simple text or binary data to the user.
Server.Transfer() method is used for posting the data from one page to another.
In cross page posting, data collected from different pages and will be displayed in single
page. So, for doing this we need to set “PostBackUrl” property of the control, in which
target page is specified and in target page we can use “PreviousPage” property. For
doing this we need to set the directive - @PreviousPageType. Previous page control can
be accessed from the method – “FindControl()”.
89) What exactly happens when ASPX page is requested from Browser?
Following are the steps which will occur when we request an ASPX page from web
server –
The browser sends the request to the webserver. Let’s assume the webserver at the
other end is IIS.
Once IIS receives the request, it looks for engine where it can serve this request.
When engine means it’s the DLL which can parse this page or compile and send a
response back to browser. The request which is to be mapped is decided by file
extension of the page requested.
Some File extension mapping given below -
<configuration>
<system.web>
<compilation debug="true"/>
<httpHandlers>
<add verb="*" path="*.xsl" type="Handler" />
</httpHandlers>
</system.web>
</configuration>
Mapping will be done for the requests to appropriate handlers based on URL and HTTP
request verb.
53) How can we determine action invoked from HTTP GET or HTTP POST?
Use class – “HttpRequestBase” and use the method – “HttpMethod” to determine the
action request type.
if (Request.HttpMethod == "POST")
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Operation()
{
// insert here the GET logic
return SomeView(...)
}
[AcceptVerbs(HttpVerbs.Post)]
public ViewResult Operation(SomeModel model)
{
// insert here the POST logic
return SomeView(...);
}