Sei sulla pagina 1di 86

Interview question Answer

1.

how remove duplicate rows in sql

Ans:
1. WITH TempEmp (Name,duplicateRecCount)
2. AS
3. (
4. SELECT Name,ROW_NUMBER() OVER(PARTITION by Name, Salary ORDER BY Name)
5. AS duplicateRecCount
6. FROM dbo.Employee
7. )
8. --Now Delete Duplicate Records
9. DELETE FROM TempEmp
10. WHERE duplicateRecCount > 1
2. How add logic before action?
You can override the OnActionExecuting or OnActionExecuted method to provide common
behavior for all actions in a controller. If you want it to apply to multiple controllers you can
create a base controller class with this override and have those controllers that need this
behavior derive from the base controller.
public override void OnActionExecuting( ActionExecutingContext filterContext )
{
... common code here...
}
public override void OnActionExecuted( ActionExecutedContext filterContext )
{
If (filterContext.Result is ViewResult)
{
... Common code here ...
}
}
3. What is Areas in asp.net MVC?
Ans: Areas are logical grouping of Controller, Models and Views and other related folders for a
module in MVC applications. By convention, a top Areas folder can contain multiple areas.
Using areas, we can write more maintainable code for an application cleanly separated
according to the modules.
1. protected void Application Start()
2. {
3. //Register all application Areas
4. AreaRegistration.RegisterAllAreas();
5.
6. WebApiConfig.Register(GlobalConfiguration.Configuration);
7. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

8. RouteConfig.RegisterRoutes(RouteTable.Routes);
9. BundleConfig.RegisterBundles(BundleTable.Bundles);
10.
11. }
4.

Get second highest salary.

Ans: SELECT TOP 1 compensation FROM (


SELECT TOP 2 compensation FROM employees
ORDER BY compensation DESC
) AS em ORDER BY compensation ASC
5. What is difference Tempdata and viewbag
View Data
1.

ViewData is a dictionary object that is derived from ViewDataDictionary class.


1. public ViewDataDictionary ViewData { get; set; }

2.

ViewData is a property of ControllerBase class.

3.

ViewData is used to pass data from controller to corresponding view.

4.

Its life lies only during the current request.

5.

If redirection occurs then its value becomes null.

6.

Its required typecasting for getting data and check for null values to avoid error.
ViewBag

1.

ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.

2.

Basically it is a wrapper around the ViewData and also used to pass data from controller to
corresponding view.
1. public Object ViewBag { get; }

3.

ViewBag is a property of ControllerBase class.

4.

Its life also lies only during the current request.

5.

If redirection occurs then its value becomes null.

6.

It doesnt required typecasting for getting data.


7. difference between WCF and web API ? why prefer Web API
Web Service

1.

It is based on SOAP and return data in XML form.

2.

It support only HTTP protocol.

3.

It is not open source but can be consumed by any client that understands xml.

4.

It can be hosted only on IIS.


WCF

1.

It is also based on SOAP and return data in XML form.

2.

It is the evolution of the web service (ASMX) and support various protocols like TCP, HTTP, HTTPS,
Named Pipes, and MSMQ.

3.

The main issue with WCF is, its tedious and extensive configuration.

4.

It is not open source but can be consumed by any client that understands xml.

5.

It can be hosted with in the application or on IIS or using window service.


WCF Rest

1.

To use WCF as WCF Rest service you have to enable webHttpBindings.

2.

It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.

3.

To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular
verb on .svc files

4.

Passing data through parameters using a WebGet needs configuration. The UriTemplate must be
specified

5.

It support XML, JSON and ATOM data format.


Web API

1.

This is the new framework for building HTTP services with easy and simple way.

2.

Web API is open source an ideal platform for building REST-ful services over the .NET Framework.

3.

Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching,
versioning, various content formats)

4.

It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC
container or dependency injection, unit testing that makes it more simple and robust.

5.

It can be hosted with in the application or on IIS.

6.

It is light weight architecture and good for devices which have limited bandwidth like smart phones.

7.

Responses are formatted by Web APIs MediaTypeFormatter into JSON, XML or whatever format you
want to add as a MediaTypeFormatter.
Why to choose Web API ?

1.

If we need a Web Service and dont need SOAP, then ASP.Net Web API is best choice.

2.

It is Used to build simple, non-SOAP-based HTTP Services on top of existing WCF message pipeline.

3.

It doesn't have tedious and extensive configuration like WCF REST service.

4.

Simple service creation with Web API. With WCF REST Services, service creation is difficult.

5.

It is only based on HTTP and easy to define, expose and consume in a REST-ful way.

6.

It is light weight architecture and good for devices which have limited bandwidth like smart phones.

7.

It is open source.
7. Which is performance is better Array or Array List

Ans:

The

Where

as,

An

Array

Where

capacity
can

ArrayList
is

as,
is
as,

An

Array

can

Where

as,

can
is

hold

in

the

of

has
an

types.

namespace.

Collections

namespace.
dimensions.

one
of

dimension.

an
is

ArrayList

Array.

always

zero.

is faster and that is because ArrayList uses a fixed amount of array.

Array

However when you add an element to the ArrayList


new

different

exactly

bound

of

items.

multiple

lower

bound

dynamically.

similar
of

System.

fixed.

size

System

have

the
lower

decrease

item

the

always

ArrayList
set

and

the

List

is

Array

collection

can

as,

We

increase

in

Array

Where

an

ArrayList

Array
Where

of

Array

You

and

will

copies
only

every

element

feel

this

Since the add from ArrayList

from
if

the

and it overflows. It creates a


old

you

one

to

add

the
to

is O(n) and the add to the Array

new

one.
often.

is O(1).

However because ArrayList uses an Array is faster to search O(1) in it than normal lists O(n).
8.

mvc filter

Typically, Filters are used to perform the following common functionalities in your ASP.NET MVC
application.
1.

Custom Authentication

2.

Custom Authorization(User based or Role based)

3.

Error handling or logging

4.

User Activity Logging

5.

Data Caching

6.

Data Compression
Types of Filters
The ASP.NET MVC framework provides five types of filters.

1.

Authentication filters (New in ASP.NET MVC5)

2.

Authorization filters

3.

Action filters

4.

Result filters

5.

Exception filters
Authentication Filters
This filter is introduced with ASP.NET MVC5. The IAuthenticationFilter interface is used to create
CustomAuthentication filter. The definition of this interface is given below-

1. public interface IAuthenticationFilter


2. {
3. void OnAuthentication(AuthenticationContext filterContext);
4.
5. void OnAuthenticationChallenge(AuthenticationChallengeContext filterContex
t);
6. }
You can create your CustomAuthentication filter attribute by implementing IAuthenticationFilter as
shown below1. public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthen
ticationFilter
2. {
3. public void OnAuthentication(AuthenticationContext filterContext)
4. {
5. //Logic for authenticating a user
6. }
7. //Runs after the OnAuthentication method
8. public void OnAuthenticationChallenge(AuthenticationChallengeContext filte
rContext)
9. {
10. //TODO: Additional tasks on the request
11. }
12. }
Authorization Filters
The ASP.NET MVC Authorize filter attribute implements the IAuthorizationFilter interface. The definition
of this interface is given below1. public interface IAuthorizationFilter
2. {
3. void OnAuthorization(AuthorizationContext filterContext);
4. }
The AuthorizeAttribute class provides the following methods to override in the CustomAuthorize
attribute class.
1. public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
2. {
3. protected virtual bool AuthorizeCore(HttpContextBase httpContext);
4. protected virtual void HandleUnauthorizedRequest(AuthorizationContext filt
erContext);
5. public virtual void OnAuthorization(AuthorizationContext filterContext);
6. protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBas
e httpContext);
7. }
In this way you can make your CustomAuthorize filter attribute either by implementing
IAuthorizationFilter interface or by inheriting and overriding above methods of AuthorizeAttribute class.

Action Filters
Action filters are executed before or after an action is executed. The IActionFilter interface is used to
create an Action Filter which provides two methods OnActionExecuting and OnActionExecuted which
will be executed before or after an action is executed respectively.
1. public interface IActionFilter
2. {
3. void OnActionExecuting(ActionExecutingContext filterContext);
4. void OnActionExecuted(ActionExecutedContext filterContext);
5. }
Result Filters
Result filters are executed before or after generating the result for an action. The Action Result type can
be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult,
FileResult and EmptyResult which derives from the ActionResult class. Result filters are called after the
Action filters. The IResultFilter interface is used to create an Result Filter which provides two methods
OnResultExecuting and OnResultExecuted which will be executed before or after generating the result
for an action respectively.
1. public interface IResultFilter
2. {
3. void OnResultExecuted(ResultExecutedContext filterContext);
4. void OnResultExecuting(ResultExecutingContext filterContext);
5. }
Exception Filters
Exception filters are executed when exception occurs during the actions execution or filters execution.
The IExceptionFilter interface is used to create an Exception Filter which provides OnException method
which will be executed when exception occurs during the actions execution or filters execution.
1. public interface IExceptionFilter
2. {
3. void OnException(Exception Context filterContext);
4. }
ASP.NET MVC HandleErrorAttribute filter is an Exception filter which implements IExceptionFilter. When
HandleErrorAttribute filter receives the exception it returns an Error view located in the Views/Shared
folder of your ASP.NET MVC application.
Order of Filter Execution
All ASP.NET MVC filter are executed in an order. The correct order of execution is given below:
1.

Authentication filters

2.

Authorization filters

3.

Action filters

4.

Result filters
Configuring Filters
You can configure your own custom filter into your application at following three levels:
1.

Global level

By registering your filter into Application_Start event of Global.asax.cs file with the help of FilterConfig
class.
1. protected void Application_Start()
2. {
3. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
4. }
2.

Controller level

By putting your filter on the top of the controller name as shown below1. [Authorize(Roles="Admin")]
2. public class AdminController : Controller
3. {
4. //
5. }
3.

Action level

By putting your filter on the top of the action name as shown below1. public class UserController : Controller
2. {
3. [Authorize(Users="User1,User2")]
4. public ActionResult LinkLogin(string provider)
5. {
6. // TODO:
7. return View();
8. }
9. }
10. security authetication from MVC
ans: Introduction
In this article i would like to explain some security measures that you should be aware of while
developing an secure ASP.NET MVC application. Here i am explaining about

Authentication
Authorization
XSS
CSRF(Cross Site Request Forgery)
Authentication
When you authenticate a user, you are verifying the identity of a user. If you need to verify a user in
an MVC application it is probably because you are building an application that restricts access to

specific users. This is completely separate from authorization, which is determining whether a specific
person is allowed to do certain action.
There are two authentication mechanisms in MVC:

Forms Authentication
Windows Authentication
Forms Authentication
Form based authentication is providing an input form where users can enter the username and
password with accompanying logic in the application needed to validate those credential. MVC
provides a lot of infrastructure support for Forms Authentication. Forms authentication is highly
customizable, you can customize everything from the sign in form, to where the credentials are
stored and how those credentials are validated. Forms Authentication in ASP.NET relies on cookies
by default. Once the user is signed in to an Application the runtime can issue a cookie on the browser.
The browser will then send the cookie with every subsequent request to the application. ASP.NET will
see the cookie and know that the user is already authenticate and does not need to sign on again.
Note: word of warning, SSL is required to make Forms authentications secured. If you are running the
application over http anybody snooping the network can see the users credentials.
Windows Authentication
Windows Authentication is also known as integrated authentication because user
components that built in to the Windows operating system are used to authenticate users. Once a
user is logged in to a domain, windows can automatically authenticate them in to application.
Windows Authentication is commonly used in Intranet Apps that run inside a company's firewall
where all of the users are logged in-to a windows domain. It will provide a single sign on experience.
They sign on once in a domain and can be authenticate to several intranet apps.
When we choose a Forms Authentication and Windows Authentication?

If you want to build a public websites then Forms Authentication is best because it can be used
outside of a windows domain.
If you want to build an Intranet application which runs with windows identity use Windows
Authentication?
How is Forms Authentication configure?
First we need to change the configuration in web.config like below

This bit of configuration tells runtime when we need to authenticate the user redirect the
browser/Account/Logon. This Account controller and this Logon view as well as some other view allow
me to register on site. These things are provided by default in ASP.NET MVC internet template.
Everything needed for the Forms Authentications are along with this template.

Selecting the Forms Authentication template


Open Visual Studio 2010 >> New Project >> Select ASP.NET MVC4 Web Application and Click Ok

And then select Internet Application Template which gives us to everything needed for the Forms
Authentication like Account Controller, Views etc. and then click OK.

Authorize

The Authorize attribute doesnt really care about how we authenticate a user. We can use a
Form Authentication or Windows Authentication. All authorize cares about that the user does have an
identity and we know whom they are and its not going to let a anonymous user get in to the Index
action. When we going to take an index action without authenticating it automatically redirect
to Account/Logon because the user has no account in this application. So we need to register for to
Logon.
How we are Authenticate with Windows Authentication?
First we need to change a little bit in the configuration section like below in the web.config
file.

Then apply the authorize attribute to the index action

You can apply authorize filter to an individual action method or to a controller. When you apply a filter
to a controller, it works as though you had applied it to every action method in the controller class
applied the Authorize filter to the class, so all of the action methods in the Account controller are
available only to authenticated users.
In order for windows integrated authentication works we need to enable windows
authentication in IIS Express else we got the below error and this is the scenario you commonly face in
todays server configuration.

Server programs like Web services and Database services typically have features turn off by
default to reduce the attack surface. If we want to become Windows Authentication works we need to
turn it on.
Go to Document >> IISExpress >> config >> applicationhost.config file and windows
authentication enable to true.

You can take authentication details like below

Authorization
The authorize attribute also allows you to set some parameters to enforce authorization
rules. First we need to know the users identity and then we can say only the specific identities to allow
accessing these actions.

Authorize attribute also allows you to specify the Roles. In Windows Authentication by default
map to Windows groups on server or groups configured in the active directory. You can put roles like
below

In Forms Authentication ASP.NET has a role provider. By using these you can store, manage
roles in a SqlServer database. These can configured in the application by default. The easiest way to
do that is use the below button in the solution explorer

It launches ASP.NET configuration tool .This is the tool you are only going use in the local
development machine. Its going to look in the web.config location and use the same application
services database as that Form Authentication provider of using that is already configured inside of
there. You can add , manage roles from here. While doing these it automatically map to db we are
configured in the web.config file.

XSS
There are some specific threats we will face. One popular attack of this phase is Cross Site
scripting attack or XSS. In Cross scripting attack the malicious user will try to have your website load a
malicious script in to the users browser. It could be a malicious script, active-x control and even some
malicious html. The malicious scripts can theft the cookie, Modify user settings, Download Malware,
Modify content. One of the worst cross site script attack is Account Hijacking; the malicious users can
access the users credentials and personal information.

Once this happen, your users become vulnerable to any number of problems.
Demo

This is a simple application for saving employee information. Let I am putting some html tag
like I am from <em>India</em> and then I try to save this , ASP.NET automatically reject this request
to prevent Cross site scripting attack because the ASP.NET is going to look for anything that
resembles the html and just reject the request. Actually there is no wrong with the emphasis tag but
ASP.NET is not trying to make a distinction here anything that looks like html is going to be rejected.

Sometimes user need to upload some html in to the server then there are always circumvents
this request validation. You have to extremely careful. One option is put ValidationInput attribute to
the destiny here in Create action.

So you can successfully process this request

Now we can have a problem that html encoded here this is because razor is going to
encode everything by default which is good. There is another defense against the cross site scripting
and we can fix that easily however the validate input false is completely disabling the check for cross
site scripting malicious html and really we only need html inside of one specific property. So you can
allow html to one property using AllowHtml attribute. Also some changes need to be done, remove
ValidateInput attribute from the Create action and also make sure that we should pass
EmployeeViewModel class as action parameter that means model binding will takes place will move
the html in to that property. Also one change in the view to show the html without encoding by
putting ViewData in Html.Raw helper.

And then again going to save one more and display the ViewData in the same view contain html tag.

Anti XSS Library


Someone come to a form and enter some script like below

Its also more malicious. Fortunately Microsoft provide a library for prevent this. You can
download it via nugget or Library Package Manager Console (Visual Studio>>Tools>>Library Package
Manager>>Package Manager Console and type Install-Package AntiXSS and press enter).
What I am going to do I am putting a line of code in the below Edit action post method

And this code will remove all the malicious things.

Cross Site Request Forgery


Cross Site Request Forgery is a dangerous and extremely major attack. Imagine a user come
in to site and trying to update some information that requires authentication before they are allowed
to perform update. Once the user logs in the Form Authentication your site will be sent the users
browser an authentication cookie and every subsequent request of the site the users browser will send
that cookie along and ASP.NET will see the user is already be authenticated. There is nothing wrong
with the browser to sending the cookie along this is how the browser and cookie works that means
the user doesnt need to enter the username and password in every single request they make. They
authenticate themselves once and the cookie will allow them to remain authenticated at least for the
duration of the session
Then what is the problem?
If the user visit some other site or strict in picking up some html from a malicious
source which had bad intention , then this malicious source can and provide a form just like a form
that our application would given to the user and then if the user submit the form the call again will be
authenticated because the authentication cookie be gave to the users browser always travel along
every request and will save the information in to the database like we always do one we have
authenticated request. Only the information in the request probably is in something user wants to
submit. Someone strict the user in to transferring money or editing their account. The problem here is

that not simply say we need the user to be authenticated when submit some information. We also
have to be checking the information that the user is submitting coming from a form that our
application presented to the user. We want to be preventing them when submitting the form from a
malicious source.
Demo
To demonstrate a CSRF I am applying the authorize attribute to my two Edit action methods
of my application.

I can save, edit the records because I had already authenticated. Below is a sample record that
I had saved in to the database successfully

In the developer point of view we are confident that I having authorized attribute in place for
preventing malicious user from edit an Employee details.
Watch would happen that I logged in as a user. Come across an interesting link in my
system

May be this link will you get from an email or from another website or some other areas of
internet. Now I am going to click the link and seen a page will up.

Now look at the record that we had saved earlier has changed. What happen?

Look at the source code of the link

Look at the action that form point to which has the same URL where the employee is posted.
The form contains all of the input needed for to complete the request and also at the bottom some
line of JavaScript for automatically submitting the form when the page loads.
How can we prevent this?
Use @Html.AntiForgeryToken() inside the form tag. This token will add a hidden input value
that is unique to browsing session. Also sending a matching value in a cookie to the users browser so
the user has accepts this cookie and that something malicious website would not be able to do.
Also you should put an attribute ValidateAntiForgeryToken for matching the form value and
cookie value

11. what is extention methods.


Introduction
Extension methods are a new feature in C# 3.0. An extension method enables us to add methods to
existing types without creating a new derived type, recompiling, or modify the original types. We can
say that it extends the functionality of an existing type in .NET. An extension method is
a static method to the existing staticclass. We call an extension method in the same general way;
there is no difference in calling.

Feature and Property of Extension Methods


The following list contains basic features and properties of extension methods:
1.
2.
3.
4.
5.
6.
7.
8.

It is a static method.
It must be located in a static class.
It uses the "this" keyword as the first parameter with a type in .NET and this method will be called by
a given type instance on the client side.
It also shown by VS intellisense. When we press the dot (.) after a type instance, then it comes in VS
intellisense.
An extension method should be in the same namespace as it is used or you need to import the
namespace of the class by a using statement.
You can give any name for the class that has an extension method but the class should be static.
If you want to add new methods to a type and you don't have the source code for it, then the solution
is to use and implement extension methods of that type.
If you create extension methods that have the same signature methods as the type you are extending,
then the extension methods will never be called.
Using the Code
We create an extension method for a string type so string will be specified as a parameter for this
extension method and that method will be called by a string instance using the dot operator.

In the above method WordCount(), we are passing a string type with this so it will be called by
the string type variable, in other words a string instance.
Now we create a static class and two static methods, one for the total word count in
a string and another for the total number of characters in a string without a space.
Hide Copy Code
using System;
namespace ExtensionMethodsExample
{
public static class Extension
{
public static int WordCount(this string str)
{
string[] userString = str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries);
int wordCount = userString.Length;
return wordCount;
}
public static int TotalCharWithoutSpace(this string str)
{
int totalCharWithoutSpace = 0;
string[] userString = str.Split(' ');
foreach (string stringValue in userString)

{
totalCharWithoutSpace += stringValue.Length;
}
return totalCharWithoutSpace;
}
}
}
Now we create an executable program that has a string as an input and uses an extension method
to count the total words in that string and the total number of characters in that string then show
the result in a console screen.
Hide Copy Code
using System;
namespace ExtensionMethodsExample
{
class Program
{
static void Main(string[] args)
{
string userSentance = string.Empty;
int totalWords = 0;
int totalCharWithoutSpace = 0;
Console.WriteLine("Enter the your sentance");
userSentance = Console.ReadLine();
//calling Extension Method WordCount
totalWords = userSentance.WordCount();
Console.WriteLine("Total number of words is :"+ totalWords);
//calling Extension Method to count character
totalCharWithoutSpace = userSentance.TotalCharWithoutSpace();
Console.WriteLine("Total number of character is
:"+totalCharWithoutSpace);
Console.ReadKey();
}
}
}
12. Trigger in sql server
Ans: What are triggers:
Triggers are a special type of stored procedure which are executed automatically based
on the occurrence of a database event. These events can be categorized as
1. Data Manipulation Language (DML) and
2. Data Definition Language (DDL) events.
The benefits derived from triggers is based in their events driven nature. Once created,
the trigger automatically fires without user intervention based on an event in the
database.
A) Using DML Triggers:

DML triggers are invoked when any DML commands like INSERT, DELETE, and UPDATE
happen on the data of a table and or view.
Points to remember:
1. DML triggers are powerful objects for maintaining database integrity and
consistency.
2. DML triggers evaluate data before it has been committed to the database.
3. During this evaluation following actions are performed.

Compare before and after versions of data

Roll back invalid modification

Read from other tables ,those in other database

Modify other tables, including those in other database.

Execute local and remote stored procedures.

4. We cannot use following commands in DML trigger


o

ALTER DATABASE

CREATE DATABASE

DISK DATABASE

LOAD DATABASE

RESTORE DATABASE

5. Using the sys.triggers catalog view is a good way to list all the triggers in a
database. To use it, we simply open a new query editor window in SSMS and
select all the rows from the view as shown below;
select * from sys.triggers
So let us create DML trigger.
You can create and manage triggers in SQL Server Management Studio or directly via
Transact-SQL (T-SQL) statements.
1) Using AFTER triggers:

An AFTER trigger is the original mechanism that SQL Server created to provide an
automated response to data modifications

AFTER triggers fire after the data modification statement completes but before
the statement's work is committed to the databases.

The trigger has the capability to roll back its actions as well as the actions of the
modification statement that invoked it.

For all examples shared below I have used Pubs database. You can download its msi file
from here and then attach .mdf file in your SQL Server 2008.
CREATE TRIGGER tr_au_upd ON authors

AFTER UPDATE,INSERT,DELETE
AS
PRINT 'TRIGGER OUTPUT' + CONVERT(VARCHAR(5),@@ROWCOUNT)
+ 'ROW UPDATED'
GO
UPDATE Statement
UPDATE authors
SET au_fname = au_fname
WHERE state ='UT'
Result:
---------------------------------------------------TRIGGER OUTPUT2ROW UPDATED
(2 row(s) affected)
Point to remember:
1) If we have a constraint and trigger defined on the same column, any violations to the
constraint abort the statement and the trigger execution does not occur. For example, if
we have a foreign key constraint on a table that ensures referential integrity and a
trigger that that does some validation on that same foreign key column then the trigger
validation will only execute if the foreign key validation is successful.
Can we create more than one trigger on one table?

We can create more than one trigger on a table for each data modification action.
In other words, we can have multiple triggers responding to an INSERT, an
UPDATE, or a DELETE command.

The sp_settriggerorder procedure is the tool we use to set the trigger order. This
procedure takes the trigger name, order value (FIRST, LAST, or NONE), and
action (INSERT, UPDATE, or DELETE) as parameters.
sp_settriggerorder tr_au_upd, FIRST, 'UPDATE'

AFTER triggers can only be placed on tables, not on views.

A single AFTER trigger cannot be placed on more than one table.

The text, ntext, and image columns cannot be referenced in the AFTER trigger
logic.

How to see inserted and deleted rows through Trigger:

We can find rows modified in the inserted and deleted temporary tables.
For AFTER trigger, these temporary memories resident tables contains the
rows modified by the statement.
With the INSTEAD OF trigger, the inserted and deleted tables are actually
temporary tables created on-the-fly.

Lets us try and see how this works;


a) Create a table titles_copy

SELECT *
INTO titles_copy
FROM titles
GO
b) Create a trigger on this table
CREATE TRIGGER tc_tr ON titles_copy
FOR INSERT , DELETE ,UPDATE
AS
PRINT 'Inserted'
SELECT title_id, type, price FROM inserted -- THIS IS TEMPORARY TABLE
PRINT 'Deleted'
SELECT title_id, type, price FROM deleted -- THIS IS TEMPORARY TABLE
--ROLLBACK TRANSACTION
c) Let us UPDATE rows. After which trigger will get fired.
We have written two statements in trigger, so these rows get printed. The inserted and
deleted tables are available within the trigger after INSERT, UPDATE, and DELETE.
PRINT 'Inserted'
SELECT title_id, type, price FROM inserted -- THIS IS TEMPORARY TABLE
PRINT 'Deleted'
SELECT title_id, type, price FROM deleted -- THIS IS TEMPORARY TABLE
Result is based on below rule.
Statement Contents of inserted
Contents of deleted
----------------------------------------------------------------INSERT
Rows added
Empty
UPDATE
New rows
Old rows
DELETE
Empty
Rows deleted
2) INSTEAD OF Trigger:
1.
2.
3.

4.

Provides an alternative to the AFTER trigger that was heavily utilized in prior
versions of SQL Server.
It performs its actions instead of the action that fired it.
This is much different from the AFTER trigger, which performs its actions after the
statement that caused it to fire has completed. This means you can have an
INSTEAD OF update trigger on a table that successfully completes but does not
include the actual update to the table.
INSTEAD OF Triggers fire instead of the operation that fires the trigger, so if you
define an INSTEAD OF trigger on a table for the Delete operation, they try to
delete rows, they will not actually get deleted (unless you issue another delete
instruction from within the trigger) as in below example:

Let us create INSTEAD OF trigger.


if exists (select * from sysobjects
where id = object_id('dbo.cust_upd_orders')
and sysstat & 0xf = 8)
drop trigger dbo.cust_upd_orders
go

CREATE TRIGGER trI_au_upd ON authors


INSTEAD OF UPDATE
AS
PRINT 'TRIGGER OUTPUT: '
+CONVERT (VARCHAR (5), @@ROWCOUNT) + ' rows were updated.'
GO
Let us write an UPDATE statement now;
UPDATE authors
SET au_fname = 'Rachael'
WHERE state = 'UT'
----------------------------------------------------TRIGGER OUTPUT: 2 rows were updated.
(2 row(s) affected)
Let us see what has been updated
SELECT au_fname, au_lname FROM authors
WHERE state = 'UT'
au_fname au_lname
---------------------Anne Ringer
Albert Ringer
Lets see another example;
Create a Table
CREATE TABLE nayan (Name varchar(32))
GO
Create trigger with INSTEAD.
CREATE TRIGGER tr_nayan ON nayan
INSTEAD OF DELETE
AS
PRINT 'Sorry - you cannot delete this data'
GO
INSERT into nayan table
INSERT nayan
SELECT 'Cannot' union
SELECT 'Delete' union
SELECT 'Me'
GO
Run the SQL DELETE statement.
DELETE nayan
GO

------------------------------Sorry - you cannot delete this data


(3 row(s) affected)
Run SELECT statement
SELECT * FROM nayan
GO
Result is below;
Name
----------------Cannot
Delete
Me
Points to remember:
1.

As you can see from the results of the SELECT statement, the first name
(au_fname) column is not updated to 'Rachael'. The UPDATE statement is correct,
but the INSTEAD OF trigger logic does not apply the update from the statement
as part of its INSTEAD OF action. The
only action the trigger carries out is to print its message.

2.

The important point to realize is that after you define an INSTEAD OF trigger on a
table, you need to include all the logic in the trigger to perform the actual
modification as well as any other actions that the trigger might need to carry out.

3.

Triggering action-The INSTEAD OF trigger fires instead of the triggering action. As


shown earlier, the actions of the INSTEAD OF trigger replace the actions of the
original data modification that fired the trigger.

4.

Constraint processing-Constraint processing-including CHECK constraints,


UNIQUE constraints, and PRIMARY KEY constraints-happens after the INSTEAD
OF trigger fires.

5.

If you were to print out the contents of the inserted and deleted tables from
inside an Instead Of trigger, you would see they behave in exactly the same way
as normal. In this case, the deleted table holds the rows you were trying to
delete, even though they will not get deleted.

Benefits of INSTEAD Triggers:

We can define an INSTEAD OF trigger on a view (something that will not work
with AFTER triggers) and this is the basis of the Distributed Partitioned Views that
are used so split data across a cluster of SQL Servers.
We can use INSTEAD OF triggers to simplify the process of updating multiple
tables for application developers.
Mixing Trigger Types.

B) Using DDL Triggers:


1.

These triggers focus on changes to the definition of database objects as opposed


to changes to the actual data.

2.

This type of trigger is useful for controlling development and production database
environments.

Let us create DDL trigger now;


Below is the syntax.
CREATE TRIGGER trigger name
ON { ALL SERVER | DATABASE }
[ WITH <ddl_trigger_option> [ ,...n ] ]
{ FOR | AFTER } { event_type | event_group } [ ,...n ]
AS { sql_statement [ ; ] [ ...n ] | EXTERNAL NAME < method specifier > [ ; ] }
CREATE TRIGGER tr_TableAudit
ON DATABASE
FOR CREATE_TABLE,ALTER_TABLE,DROP_TABLE
AS
PRINT 'You must disable the TableAudit trigger in order
to change any table in this database'
ROLLBACK
GO
Other way of writing the same query in more optimized way is below;
IF EXISTS(SELECT * FROM sys.triggers
WHERE name = N'tr_TableAudit' AND parent_class=0)
DROP TRIGGER [tr_TableAudit] ON DATABASE
GO
CREATE TRIGGER tr_TableAudit ON DATABASE
FOR DDL_TABLE_EVENTS
AS
PRINT 'You must disable the TableAudit trigger in
order to change any table in this database'
ROLLBACK
GO
Let us try to run a DDL command. See the result in below figure
Now let us look at an example that applies to server-level events. Above example was
scoped at database level.
Let us create a trigger which prevents changes to the server logins. When this trigger is
installed, it displays a message and rolls back any login changes that are attempted.
CREATE TRIGGER tr_LoginAudit
ON ALL SERVER
FOR CREATE_LOGIN,ALTER_LOGIN,DROP_LOGIN
AS
PRINT'You must disable the tr_LoginAudit trigger before making login changes'
ROLLBACK
GO
C) Using CLR Trigger:
1.
2.

CLR triggers are trigger based on CLR.


CLR integration is new in SQL Server 2008. It allows for the database objects
(such as trigger) to be coded in .NET.

Object that have heavy computation or require reference to object outside SQL
are coded in the CLR.
We can code both DDL and DML triggers by using a supported CLR language like
C#.

3.
4.

Let us follow below simple steps to create a CLR trigger;


Step 1: Create the CLR class. We code the CLR class module with reference to the
namespace required to compile CLR database objects.
Add below reference;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
So below is the complete code for class;
using
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Data.Sql;
System.Data.SqlClient;
Microsoft.SqlServer.Server;
System.Data.SqlTypes;
System.Text.RegularExpressions;

namespace CLRTrigger
{
public class CLRTrigger
{
public static void showinserted()
{
SqlTriggerContext triggContext = SqlContext.TriggerContext;
SqlConnection conn = new SqlConnection(" context connection =true ");
conn.Open();
SqlCommand sqlComm = conn.CreateCommand();
SqlPipe sqlP = SqlContext.Pipe;
SqlDataReader dr;
sqlComm.CommandText = "SELECT pub_id, pub_name from inserted";
dr = sqlComm.ExecuteReader();
while (dr.Read())
sqlP.Send((string)dr[0] + "," + (string)dr[1]);
}
}
}
Step 2: Compile this class and in the BIN folder of project we will get CLRTrigger.dll
generated. After compiling for CLRTrigger.dll, we need to load the assembly into SQL

Server
Step 3: Now we will use T-SQL command to execute to create the assembly for
CLRTrigger.dll. For that we will use CREATE ASSEMBLY in SQL Server.
CREATE ASSEMBLY

triggertest

FROM 'C:\CLRTrigger\CLRTrigger.dll'
WITH PERMISSION_SET = SAFE
Step 4: The final step is to create the trigger that references the assembly. Now we will
write below T-SQL commands to add a trigger on the publishers table in the Pubs
database.
CREATE TRIGGER tri_Publishes_clr
ON publishers
FOR INSERT
AS
EXTERNAL NAME triggertest.CLRTrigger.showinserted
If you get some compatibility error message run the below command to set
compatibility.
ALTER DATABASE pubs
SET COMPATIBILITY_LEVEL = 100
Step 5: Enable CLR Stored procedure on SQL Server. For this run the below code;
EXEC sp_configure 'show advanced options' , '1';
reconfigure;
EXEC sp_configure 'clr enabled' , '1' ;
reconfigure;
EXEC sp_configure 'show advanced options, '0';
reconfigure;
Step 6: Now we will run INSERT statement to the publishers table that fires the newly
created CLR trigger.
INSERT publishers
(pub_id, pub_name)
values ('9922','Vishal Nayan')
The trigger simply echoes the contents of the inserted table. The output from the trigger
is based on the insertion above.
----------------------------------------------------9922,Vishal Nayan

(1 row(s) affected)
The line of code which is printing the query result is actually below code written in a
managed environment.
while (dr.Read())
sqlP.Send((string)dr[0] + "," + (string)dr[1]);
Conclusion:
The tri_Publishes_clr trigger demonstrates the basic steps for creating a CLR trigger. The
true power of CLR triggers lies in performing more complex calculations, string
manipulations and things of this nature that the can be done much more efficiently with
CLR programming languages than they can in T-SQL.
13. diff between local and global variable
ans: Differentiate between Global & Local variables with examples
Local Variable

Global Variable

Local variables are declared inside a function.

Global Variables are declared before the main


function.

Local Variables cannot be accessed outside the


function.

Global Variables can be accessed in any function.

Local Variables are alive only for a function.

Global Variables are alive till the end of the program.

Example of local variable.


//program to add any two integers
void main()
{
int a,b,sum;
clrscr();
printf("Enter any two integer value");
scanf("%d%d",&a,&b);
sum=a+b;
printf("\nSum of two integers %d and %d is %d",a,b,sum);
}
Here, a,b, and sum are local variables which are declared in main function.

Example of global variable.


//program to find the sum and difference between two numbers
int a,b,result;
void main()
{
clrscr();
sum();
sub();
getch();
}
sum()
{
printf("Enter two numbers to find their sum");
scanf("%d%d",&a,&b);
result=a+b;
printf("\n the sum of two numbers is %d",result);
return 0;
}
sub()
{
printf("Enter two numbers to find their difference");
scanf("%d%d",&a,&b);
result=a-b;
printf("\n the difference between two numbers is %d",result);
return0;
}
Difference between Abstract Class and Interface in Java
I have already covered basics of Abstract class and Interface while discussing OOPs concepts and
in following posts:

abstract Classes

Interfaces

abstract class can extend only one class or one abstract interface can extend any number
1
class at a time

of interfaces at a time

abstract class can extend from a class or from an

interface can extend only from an

abstract class

interface

abstract class can have both abstract and concrete

interface can have only abstract

methods

methods

A class can implement any number


4 A class can extend only one abstract class
of interfaces

In an interface keyword abstract


In abstract class keyword abstract is mandatory to
5

is optional to declare a method as


declare a method as an abstract
an abstract

abstract class can have protected , public and public

Interface can have only public

abstract methods

abstract methods i.e. by default

abstract class can have static, final or static

interface can have only static final

final variable with any access specifier

(constant) variable i.e. by default

Each of the above difference between Abstract class vs Interfaceis explained with an example
below
Abstract class vs interface
Difference No.1:
Abstract class can extend only one class or one abstract class at a time

class Example1{
public void display1(){
System.out.println("display1 method");
}
}
abstract class Example2{
public void display2(){
System.out.println("display2 method");
}
}
abstract class Example3 extends Example1{
abstract void display3();
}
class Example4 extends Example2{
public void display3(){
System.out.println("display3 method");
}
}
class Demo{
public static void main(String args []){
Example4 obj=new Example4();
obj.display3 ();
}

}
Output:

display3 method
Interface can extend any number of interfaces at a time

//first interface
interface Example1{
public void display1();
}
//second interface
interface Example2 {
public void display2();
}
//This interface is extending both the above interfaces
interface Example3 extends Example1,Example2{
}
class Example4 implements Example3{
public void display1(){
System.out.println("display2 method");
}
public void display2(){
System.out.println("display3 method");
}
}
class Demo{
public static void main(String args[]){
Example4 obj=new Example4();
obj.display1();
}
}
Output:

display2 method
Difference No.2:

Abstract class can be inherited by a class or an abstract class

class Example1{
public void display1(){
System.out.println("display1 method");
}
}
abstract class Example2{
public void display2(){
System.out.println("display2 method");
}
}
abstract class Example3 extends Example2{
abstract void display3();
}
class Example4 extends Example3{
public void display2(){
System.out.println("Example4-display2 method");
}
public void display3(){
System.out.println("display3 method");
}
}
class Demo{
public static void main(String args[]){
Example4 obj=new Example4();
obj.display2();
}
}
Output:

Example4-display2 method
Interfaces can be extended only by interfaces. Classes has to implement them instead of
extend

interface Example1{
public void display1();
}
interface Example2 extends Example1{
}
class Example3 implements Example2{
public void display1(){
System.out.println("display1 method");
}
}
class Demo{
public static void main(String args[]){
Example3 obj=new Example3();
obj.display1();
}
}
Output:

display1 method
Difference No.3
Abstract class can have both abstract and concrete methods

abstract class Example1 {


abstract void display1();
public void display2(){
System.out.println("display2 method");
}
}
class Example2 extends Example1{
public void display1(){
System.out.println("display1 method");
}
}
class Demo{
public static void main(String args[]){

Example2 obj=new Example2();


obj.display1();
}
}
Interface can only have abstract methods, they cannot have concrete methods

interface Example1{
public abstract void display1();
}
class Example2 implements Example1{
public void display1(){
System.out.println("display1 method");
}
}
class Demo{
public static void main(String args[]){
Example2 obj=new Example2();
obj.display1();
}
}
Difference No.4
A class can extend only one abstract class at a time

abstract class Example1{


public void display1(){
System.out.println("display1 method");
}
}
abstract class Example2{
abstract void display2();
}
class Example3 extends Example1{
public void display3(){
System.out.println("display3 method");
}

}
class Demo{
public static void main(String args[]){
Example3 obj=new Example3();
obj.display3();
}
}
A class can implement any number of interfaces at a time

interface Example1{
public void display1();
}
interface Example2{
public void display2();
}
class Example3 implements Example1,Example2{
public void display1(){
System.out.println("display1 method");
}
public void display2(){
System.out.println("display2 method");
}
public void display3(){
System.out.println("display3 method");
}
}
class Demo{
public static void main(String args[]){
Example3 obj=new Example3();
obj.display1();
obj.display3();
}
}
Difference No.5
In abstract class, the keyword abstract is mandatory to declare a method as an abstract

abstract class Example1{


public abstract void display1();
}

class Example2 extends Example1{


public void display1(){
System.out.println("display1 method");
}
public void display2(){
System.out.println("display2 method");
}
}
class Demo{
public static void main(String args[]){
Example2 obj=new Example2();
obj.display1();
}
}
In interfaces, the keyword abstract is optional to declare a method as an abstract because all
the methods are abstract by default

interface Example1{
public void display1();
}
class Example2 implements Example1{
public void display1(){
System.out.println("display1 method");
}
public void display2(){
System.out.println("display2 method");
}
}
class Demo{
public static void main(String args[]){
Example2 obj=new Example2();

obj.display1();
}
}
Difference No.6
Abstract class can have protected , public and public abstract methods

abstract class Example1{


protected abstract void display1();
public abstract void display2();
public abstract void display3();
}
class Example2 extends Example1{
public void display1(){
System.out.println("display1 method");
}
public void display2(){
System.out.println("display2 method");
}
public void display3(){
System.out.println("display3 method");
}
}
class Demo{
public static void main(String args[]){
Example2 obj=new Example2();
obj.display1();
}
}
Interface can have only public abstract methods i.e. by default

interface Example1{
void display1();
}
class Example2 implements Example1{
public void display1(){

System.out.println("display1 method");
}
public void display2(){
System.out.println("display2 method");
}
}
class Demo{
public static void main(String args[]){
Example2 obj=new Example2();
obj.display1();
}
}
Difference No.7
Abstract class can have static, final or static final variables with any access specifier

abstract class Example1{


private int numOne=10;
protected final int numTwo=20;
public static final int numThree=500;
public void display1(){
System.out.println("Num1="+numOne);
}
}
class Example2 extends Example1{
public void display2(){
System.out.println("Num2="+numTwo);
System.out.println("Num2="+numThree);
}
}
class Demo{
public static void main(String args[]){
Example2 obj=new Example2();
obj.display1();
obj.display2();
}

}
Interface can have only static final (constant) variable i.e. by default

interface Example1{
int numOne=10;
}
class Example2 implements Example1{
public void display1(){
System.out.println("Num1="+numOne);
}
}
class Demo{
public static void main(String args[]){
Example2 obj=new Example2();
obj.display1();
}
}
14. Difference between overloading and overriding in C#
There are many differences between method overloading and method overriding in java. A list of
differences between method overloading and method overriding are given below:
No.
Method Overloading
Method Overriding
1)
Method overloading is used to increase the readability of the program.
Method overriding is used to provide the specific implementation of the method that is already
provided by its super class.
2)
Method overloading is performed within class.
Method overriding occurs in two classes that have IS-A (inheritance) relationship.
3)
In case of method overloading, parameter must be different.
In case of method overriding, parameter must be same.
4)
Method overloading is the example of compile time polymorphism.
Method overriding is the example of run time polymorphism.
5)
In java, method overloading can't be performed by changing return type of the method only. Return

type can be same or different in method overloading. But you must have to change the parameter.
Return type must be same or covariant in method overriding.
Java Method Overloading example

1. class OverloadingExample{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
Java Method Overriding example
1.
2.
3.
4.
5.
6.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
}
15. what is Encapsulation

4. INTRODUCTION:
5. The object oriented programming will give the impression very unnatural to a
programmer with a lot of procedural programming experience. In Object Oriented
programming Encapsulation is the first pace. Encapsulation is the procedure of
covering up of data and functions into a single unit (called class). An
encapsulated object is often called an abstract data type. In this article let us see
about it in a detailed manner.
6. NEED FOR ENCAPSULATION:
7. The need of encapsulation is to protect or prevent the code (data) from accidental
corruption due to the silly little errors that we are all prone to make. In Object
oriented programming data is treated as a critical element in the program
development and data is packed closely to the functions that operate on it and
protects it from accidental modification from outside functions.
8. Encapsulation provides a way to protect data from accidental corruption. Rather
than defining the data in the form of public, we can declare those fields as
private. The Private data are manipulated indirectly by two ways. Let us see some
example programs in C# to demonstrate Encapsulation by those two methods.
The first method is using a pair of conventional accessor and mutator methods.
Another one method is using a named property. Whatever be the method our aim
is to use the data with out any damage or change.
9. ENCAPSULATION USING ACCESSORS AND MUTATORS:
10. Let us see an example of Department class. To manipulate the data in that class
(String departname) we define an accessor (get method) and mutator (set
method).
11. using system;
public class Department

{
private string departname;
.......
// Accessor.
public string GetDepartname()
{
return departname;
}
// Mutator.
public void SetDepartname( string a)
{
departname=a;
}
}
12.
Like the above way we can protect the private data from the outside world. Here
we use two separate methods to assign and get the required data.
13. public static int Main(string[] args)
{
Department d = new Department();
d.SetDepartname("ELECTRONICS");
Console.WriteLine("The Department is :"+d.GetDepartname());
return 0;
}
14. In the above example we can't access the private data departname from an
object instance. We manipulate the data only using those two methods.
15. ENCAPSULATION USING PROPERTIES:
16. Properties are a new language feature introduced with C#. Only a few languages
support this property. Properties in C# helps in protect a field in a class by
reading and writing to it. The first method itself is good but Encapsulation can be
accomplished much smoother with properties.
17. Now let's see an example.
18. using system;
public class Department
{
private string departname;
public string Departname
{
get
{
return departname;
}
set
{

departname=value;
}
}
}
public class Departmentmain
{
public static int Main(string[] args)
{
Department d= new Department();
d.departname="Communication";
Console.WriteLine("The Department is :{0}",d.Departname);
return 0;
}
}
19. From the above example we see the usage of Encapsulation by using properties.
The property has two accessor get and set. The get accessor returns the value of
the some property field. The set accessor sets the value of the some property
field with the contents of "value". Properties can be made read-only. This is
accomplished by having only a get accessor in the property implementation.
20. READ ONLY PROPERTY:
21. using system;
public class ReadDepartment
{
private string departname;
public ReadDepartment(string avalue)
{
departname=avalue;
}
public string Departname
{
get
{
return departname;
}
}
}
public class ReadDepartmain
{
public static int Main(string[] args)
{
ReadDepartment d= new ReadDepartment("COMPUTERSCIENCE");
Console.WriteLine("The Department is: {0}",d.Departname);
return 0;

}
}
22. In the above example we see how to implement a read-only property. The class
ReadDepartment has a Departname property that only implements a get
accessor. It leaves out the set accessor. This particular class has a constructor,
which accepts a string parameter. The Main method of the ReadDepartmain class
creates a new object named d. The instantiation of the d object uses the
constructor of the ReadDepartment that takes a string parameter. Since the
above program is read-only, we cannot set the value to the field departname and
we only read or get the value of the data from the field. Properties can be made
also Write-only. This is accomplished by having only a set accessor in the
property implementation.
23. WRITE ONLY PROPERTY:
24. using system;
public class WriteDepartment
{
private string departname;
public string Departname
{
set
{
departname=value;
Console.WriteLine("The Department is :{0}",departname);
}
}
}
public class WriteDepartmain
{
public static int Main(string[] args)
{
WriteDepartment d= new WriteDepartment();
d.departname="COMPUTERSCIENCE";
return 0;
}
}
25. In the above example we see how to implement a Write-only property. The class
WriteDepartment has now has a Departname property that only implements a set
accessor. It leaves out the get accessor. The set accessor method is varied a little
by it prints the value of the departname after it is assigned.
26. CONCLUSION:
The Encapsulation is the first footstep towards the object-oriented programming.
This article gives you a little bit information about Encapsulation. Using accessor
and mutator methods we can make encapsulation. Another one method is using a

named property. The benefit of properties is that the users of your objects are
able to manipulate the internal data point using a single named item.
17. What is polymorphism and explain in details.
Polymorphism is one of the fundamental concepts of OOP.
Polymorphism provides following features:

It allows you to invoke methods of derived class through base class reference
during runtime.

It has the ability for classes to provide different implementations of methods that
are called through the same name.

Polymorphism is of two types:


1. Compile time polymorphism/Overloading
2. Runtime polymorphism/Overriding
Compile Time Polymorphism
Compile time polymorphism is method and operators overloading. It is also called early
binding.
In method overloading method performs the different task at the different input
parameters.
Runtime Time Polymorphism
Runtime time polymorphism is done using inheritance and virtual functions. Method
overriding is called runtime polymorphism. It is also called late binding.
When overriding a method, you change the behavior of the method for the derived
class. Overloading a method simply involves having another method with the same
prototype.
Caution: Don't confused method overloading with method overriding, they are different,
unrelated concepts. But they sound similar.
Method overloading has nothing to do with inheritance or virtual methods.
Following are examples of methods having different overloads:
void area(int side);
void area(int l, int b);
void area(float radius);
Practical example of Method Overloading (Compile Time Polymorphism)
using System;
namespace method_overloading
{

class Program

{
public class Print
{
public void display(string name)
{
Console.WriteLine ("Your name is : " + name);
}
public void display(int age, float marks)
{
Console.WriteLine ("Your age is : " + age);
Console.WriteLine ("Your marks are :" + marks);
}
}
static void Main(string[] args)
{
Print obj = new Print ();
obj.display("George");
obj.display(34, 76.50f);
Console.ReadLine();
}
}
}

Note: In the code if you observe display method is called two times. Display method will
work according to the number of parameters and type of parameters.
When and why to use method overloading
Use method overloading in situation where you want a class to be able to do something,
but there is more than one possibility for what information is supplied to the method that
carries out the task.
You should consider overloading a method when you for some reason need a couple of
methods that take different parameters, but conceptually do the same thing.

Method Overloading showing many forms.


using System;
namespace method_overloading_polymorphism
{
class Program
{
public class Shape
{
public void Area(float r)
{
float a = (float)3.14 * r;
// here we have used function overload with 1 parameter.
Console.WriteLine("Area of a circle: {0}",a);
}
public void Area(float l, float b)
{
float x = (float)l* b;
// here we have used funtion overload with 2 parameters.
Console.WriteLine("Area of a rectangle: {0}",x);
}
public void Area(float a, float b, float c)
{
float s = (float)(a*b*c)/2;
// here we have used funtion overload with 3 parameters.
Console.WriteLine("Area of a circle: {0}", s);
}
}

static void Main(string[] args)


{

Shape ob = new Shape();


ob.Area(2.0f);
ob.Area(20.0f,30.0f);
ob.Area(2.0f,3.0f,4.0f);
Console.ReadLine();
}
}
}
Things to keep in mind while method overloading
If you use overload for method, there are couple of restrictions that the compiler
imposes.
The rule is that overloads must be different in their signature, which means the name
and the number and type of parameters.
There is no limit to how many overload of a method you can have. You simply declare
them in a class, just as if they were different methods that happened to have the same
name.
Conclusion
You can read my other article on inheritance explaining method overriding.
Hope the article would have helped you in understanding polymorphism. Please feel free
to contact me for feedback or comments you may have about this article.
18. Differences Among Method Overriding, Method Hiding (new Keyword) and Method
Shadowing in C#.
Ans: This article explains the main differences among overriding, hiding and shadowing in C#. I am
mainly focusing on the main points and not detailed descriptions. So you will finish this very quickly.
Also some examples to understand the concepts better are provided.
1. The "override" modifier extends the base class method, and the "new" modifier hides it.
2. The "virtual" keyword modifies a method, property, indexer, or event declared in the base
class and allows it to be overridden in the derived class.
3. The "override" keyword extends or modifies a virtual/abstract method, property, indexer, or
event of the base class into the derived class.
4. The "new" keyword is used to hide a method, property, indexer, or event of the base class into
the derived class.
5. If a method is not overriding the derived method then it is hiding it. A hiding method must be
declared using the new keyword.

6. Shadowing is another commonly used term for hiding. The C# specification only uses "hiding"
but either is acceptable. Shadowing is a VB concept.
What are the differences between method hiding and overriding in C#?
1. For hiding the base class method from derived class simply declare the derived class method
with the new keyword.
Whereas in C#, for overriding the base class method in a derived class, you need to declare
the base class method as virtual and the derived class method as overriden.
2. If a method is simply hidden then the implementation to call is based on the compile-time
type of the argument "this".
Whereas if a method is overridden then the implementation to be called is based on the runtime type of the argument "this".
3. New is reference-type specific, overriding is object-type specific.
What are the differences between method hiding and method shadowing?
1. Shadowing is a VB concept. In C#, this concept is called hiding.
2. The two terms mean the same in C#.
Method hiding == shadowing
3. In short, name "hiding" in C# (new modifier) is called shadowing in VB.NET (keyword
Shadows).
4. In C# parlance, when you say "hiding" you're usually talking about inheritance, where a more
derived method "hides" a base-class method from the normal inherited method call chain.
5. When you say "shadow" you're usually talking about scope; an identifier in an inner scope is
"shadowing" an identifier at a higher scope.
6. In other languages, what is called "hiding" in C# is sometimes called "shadowing" as well.
Examples 1: Simple one

Output:

Example 2: Method hiding with warning

Output:

Example 3: Overriding, Hiding and Shadowing

Output:

Example 4 : Method Overriding and Method Hiding:

Output:

19. how to show base class method by child class object (base class inherited by child class).
Ans: don't know if this is possible, but I am trying to get the Base Class instance from a Derived
Class. In C#, I can use the base keyword to access properties and methods of the Base Class (of
course), but I want to use base itself. Attempting to do so results in a "Use of keyword 'base' is not
valid in this context" error.
Example Code
public class SuperParent
{
public int SPID;
public SuperParent()
{
}
}
public class SubChild : SuperParent
{
public SubChild(int pSPID)
{
base.SPID = pSPID;
}
public int BaseSPID
{
get
{
SuperParent sp = base;
return sp.SPID;
}
}
}
20. what is page life cycle in mvc and asp.net both
Note: - There is nothing as such called as MVC life cycle. I think lot of people are obsessed with ASP.NET
page life cycle and they think there is life cycle in MVC as well. To be specific the MVC request goes through
various steps of execution and that's what is termed as MVC application life cycle.

Any web application has two main execution steps first understanding the request and depending on
the type of the request sending out appropriate response. MVC application life cycle is not different it
has two main phases first creating the request object and second sending our response to the browser.
Creating Response object: - The request object creation has four major steps. Below is the detail
explanation of the same.
Step 1 Fill route: - MVC requests are mapped to route tables which in turn specify which controller and
action to be invoked. So if the request is the first request the first thing is to fill the route table with routes
collection. This filling of route table happens in the global.asax file.
Step 2 Fetch route:- Depending on the URL sent "UrlRoutingModule" searches the route table to
create "RouteData" object which has the details of which controller and action to invoke.
Step 3 Request context created: - The "RouteData" object is used to create the "RequestContext"
object.
Step 4 Controller instance created: - This request object is sent to "MvcHandler" instance to create
the controller class instance. Once the controller class object is created it calls the "Execute" method of
the controller class.
Creating Response object: - This phase has two steps executing the action and finally sending the
response as a result to the view.
Step 5 Execute Action: - The "ControllerActionInvoker" determines which action to executed and
executes the action.
Step 6 Result sent: - The action method executes and creates the type of result which can be a view
result , file result , JSON result etc.
So in all there are six broad steps which get executed in MVC application life cycle.
Page Life Cycle With Examples in ASP.Net
When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of
processing steps. These include initialization, instantiating controls, restoring and maintaining state,
running event handler code, and rendering. The following are the various stages or events of ASP.Net
page life cycle.
PreInit
1. Check the IsPostBack property to determine whether this is the first time the page is being
processed.
2. Create or re-create dynamic controls.
3. Set a master page dynamically.
4. Set the Theme property dynamically.

Note: If the request is a postback then the values of the controls have not yet been restored from the
view state. If you set a control property at this stage, its value might be overwritten in the next event.
Init
1. This event fires after each control has been initialized.
2. Each control's UniqueID is set and any skin settings have been applied.
3. Use this event to read or initialize control properties.
4. The "Init" event is fired first for the bottom-most control in the hierarchy, and then fired up
the hierarchy until it is fired for the page itself.

InitComplete
1. Until now the viewstate values are not yet loaded, hence you can use this event to make
changes to the view state that you want to ensure are persisted after the next postback.
2. Raised by the Page object.
3. Use this event for processing tasks that require all initialization to be complete.

OnPreLoad
1. Raised after the page loads view state for itself and all controls, and after it processes
postback data that is included with the Request instance.
2. Before the Page instance raises this event, it loads view state for itself and all controls, and
then processes any postback data included with the Request instance.
3. Loads ViewState: ViewState data are loaded to controls.
4. Loads Postback data: Postback data are now handed to the page controls.

Load
1. The Page object calls the OnLoad method on the Page object, and then recursively does the
same for each child control until the page and all controls are loaded. The Load event of
individual controls occurs after the Load event of the page.
2. This is the first place in the page lifecycle that all values are restored.
3. Most code checks the value of IsPostBack to avoid unnecessarily resetting state.

4. You may also call Validate and check the value of IsValid in this method.
5. You can also create dynamic controls in this method.
6. Use the OnLoad event method to set properties in controls and establish database
connections.

Control PostBack Event(s)


1. ASP.NET now calls any events on the page or its controls that caused the PostBack to occur.
2. Use these events to handle specific control events, such as a Button control's Click event or a
TextBox control's TextChanged event.
3. In a postback request, if the page contains validator controls, check the IsValid property of the
Page and of individual validation controls before performing any processing.
4. This is just an example of a control event. Here it is the button click event that caused the
postback.

LoadComplete
1. Raised at the end of the event-handling stage.
2. Use this event for tasks that require that all other controls on the page be loaded.

OnPreRender
1. Raised after the Page object has created all controls that are required in order to render the
page, including child controls of composite controls.
2. The Page object raises the PreRender event on the Page object, and then recursively does the
same for each child control. The PreRender event of individual controls occurs after the
PreRender event of the page.
3. The PreRender event of individual controls occurs after the PreRender event of the page.
4. Allows final changes to the page or its control.
5. This event takes place before saving ViewState, so any changes made here are saved.
6. For example: After this event, you cannot change any property of a button or change any
viewstate value.
7. Each data bound control whose DataSourceID property is set calls its DataBind method.

8. Use the event to make final changes to the contents of the page or its controls.

OnSaveStateComplete
1. Raised after view state and control state have been saved for the page and for all controls.
2. Before this event occurs, ViewState has been saved for the page and for all controls.
3. Any changes to the page or controls at this point will be ignored.
4. Use this event perform tasks that require the view state to be saved, but that do not make any
changes to controls.

Render Method
1. This is a method of the page object and its controls (and not an event).
2. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language
(DHTML), and script that are necessary to properly display a control at the browser.
UnLoad
1. This event is used for cleanup code.
2. At this point, all processing has occurred and it is safe to dispose of any remaining objects,
including the Page object.
3. Cleanup can be performed on:
o

Instances of classes, in other words objects

Closing opened files

Closing database connections.

4. This event occurs for each control and then for the page.
5. During the unload stage, the page and its controls have been rendered, so you cannot make
further changes to the response stream.
6. If you attempt to call a method such as the Response.Write method then the page will throw
an exception.

EXAMPLES
Example 1: Control Values
In the following code, I have assigned the values to the label control on each event. When you run the
code, you will see that in the "Page_UnLoad", the values are not assigned to the label. WHY? Because,
during the unload stage, the page and its controls have been rendered, so you cannot change the
values.
Please observe the code comments and output. It will help you to clearly understand the concepts.
public partial class PageLiftCycle : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
//Work and It will assign the values to label.
lblName.Text = lblName.Text + "<br/>" + "PreInit";
}
Protected void Page_Init (object sender, EventArgs e)
{
//Work and It will assign the values to label.
lblName.Text = lblName.Text + "<br/>" + "Init";
}
protected void Page_InitComplete(object sender, EventArgs e)
{
//Work and It will assign the values to label.
lblName.Text = lblName.Text + "<br/>" + "InitComplete";
}
protected override void OnPreLoad(EventArgs e)
{
//Work and It will assign the values to label.
//If the page is post back, then label contrl values will be loaded from view state.
//E.g: If you string str = lblName.Text, then str will contain viewstate values.
lblName.Text = lblName.Text + "<br/>" + "PreLoad";
}
protected void Page_Load(object sender, EventArgs e)
{
//Work and It will assign the values to label.
lblName.Text = lblName.Text + "<br/>" + "Load";
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Work and It will assign the values to label.
lblName.Text = lblName.Text + "<br/>" + "btnSubmit_Click";
}

protected void Page_LoadComplete(object sender, EventArgs e)


{
//Work and It will assign the values to label.
lblName.Text = lblName.Text + "<br/>" + "LoadComplete";
}
protected override void OnPreRender(EventArgs e)
{
//Work and It will assign the values to label.
lblName.Text = lblName.Text + "<br/>" + "PreRender";
}
protected override void OnSaveStateComplete(EventArgs e)
{
//Work and It will assign the values to label.
//But "SaveStateComplete" values will not be available during post back. i.e. View state.
lblName.Text = lblName.Text + "<br/>" + "SaveStateComplete";
}
protected void Page_UnLoad(object sender, EventArgs e)
{
//Work and it will not effect label contrl, view stae and post back data.
lblName.Text = lblName.Text + "<br/>" + "UnLoad";
}
}
Output
The first time the Page Load is output:

When you click on the Submit Button output:

During the first time of the page load with EnableViewState="false":

When you click on the Submit Button output with EnableViewState="false":

Example 2: ViewState Values


Please observe the code comments and output. It will help you to clearly understand the concepts.
public partial class PageLiftCycle : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
//Work and It will assign the values to label.
//Note : If page is post back or first time call and you have not set any values to
ViewState["value"], then
//Convert.ToString(ViewState["value"]) is always empty.
ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "PreInit";
lblName.Text = Convert.ToString(ViewState["value"]);
}
protected void Page_Init(object sender, EventArgs e)
{
//Work and It will assign the values to label.
//Note : If page is post back or first time call and you have not set any values to
ViewState["value"] in privious events, then
//Convert.ToString(ViewState["value"]) is always empty.
ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "Init";
lblName.Text = Convert.ToString(ViewState["value"]);
}
protected void Page_InitComplete(object sender, EventArgs e)
{
//Work and It will assign the values to label.
//Note : If page is post back or first time call and you have not set any values to
ViewState["value"] in privious events, then
//Convert.ToString(ViewState["value"]) is always empty.
ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "InitComplete";
lblName.Text = Convert.ToString(ViewState["value"]);
}
protected override void OnPreLoad(EventArgs e)
{
//Work and It will assign the values to label.
//Note : If page is post back and you have set or not set any values to ViewState["value"] in
privious events, then
//Convert.ToString(ViewState["value"]) will always have post back data.
//E.g: If you string str = Convert.ToString(ViewState["value"]), then str will contain post back
values.
ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "PreLoad";
lblName.Text = Convert.ToString(ViewState["value"]);
}

protected void Page_Load(object sender, EventArgs e)


{
//Work and It will assign the values to label.
ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "Load";
lblName.Text = Convert.ToString(ViewState["value"]);
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Work and It will assign the values to label.
ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "btnSubmit_Click";
lblName.Text = Convert.ToString(ViewState["value"]);
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
//Work and It will assign the values to label.
ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "LoadComplete";
lblName.Text = Convert.ToString(ViewState["value"]);
}
protected override void OnPreRender(EventArgs e)
{
//Work and It will assign the values to label.
ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "PreRender";
lblName.Text = Convert.ToString(ViewState["value"]);
}
protected override void OnSaveStateComplete(EventArgs e)
{
//Work and It will assign the values to label.
//But "SaveStateComplete" values will not be available during post back. i.e. View state.
ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "SaveStateComplete";
lblName.Text = Convert.ToString(ViewState ["value"]);
}
protected void Page_UnLoad(object sender, EventArgs e)
{
//Work and it will not effect label contrl values, view state and post back data.
ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "UnLoad";
lblName.Text = Convert.ToString(ViewState["value"]);
}
}
Output
During the first the Time Page Load is output:

When you click on the Submit Button output:

During the first time the page loads with EnableViewState="false":

When you click on the Submit Button the output with EnableViewState="false":

Example 3: ViewState Values


Please observe the code comments and output. It will help you to clearly understating the concepts.
Public partial class PageLiftCycle : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
Response.Write("<br/>" + "PreInit");
}
protected void Page_Init(object sender, EventArgs e)
{
Response.Write("<br/>" + "Init");
}
protected void Page_InitComplete(object sender, EventArgs e)
{
Response.Write("<br/>" + "InitComplete");
}
protected override void OnPreLoad(EventArgs e)
{
Response.Write("<br/>" + "PreLoad");
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("<br/>" + "Load");
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
Response.Write("<br/>" + "LoadComplete");
}

protected override void OnPreRender(EventArgs e)


{
Response.Write("<br/>" + "PreRender");
}
protected override void OnSaveStateComplete(EventArgs e)
{
Response.Write("<br/>" + "SaveStateComplete");
}
protected void Page_UnLoad(object sender, EventArgs e)
{
//Runtime Error : Response is not available in this context.
//Response.Write("<br/>" + "UnLoad"); //Error
}
}
Output

Note: If you write Response.Write("<br/>" + "UnLoad"); in the Page_UnLoad event, then it will
genenrate the Runtime Error "Response is not available in this context".

21. Difference between Stored Procedure and Function in SQL Server


Stored Procedures are pre-compile objects which are compiled for first time and its compiled format is
saved which executes (compiled code) whenever it is called. But Function is compiled and executed
every time when it is called. For more about stored procedure and function refer the articles Different
types of Stored Procedure andDifferent types of Function.
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 can not 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.

Functions that return tables can be treated as another rowset. This can be used in JOINs with other
tables.

5.

Inline Function can be though of as views that take parameters and can be used in JOINs and other
Rowset operations.

6.

Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in
a Function.

7.

We can go for Transaction Management in Procedure whereas we can't go in Function.

22. Difference between Primary Key and Unique Key .


Difference between Primary Key & Unique Key
Primary Key
Unique Key
Primary Key can't accept null values.
Unique key can accept only one null value.
By default, Primary key is clustered index and data in the database table is physically organized in the
sequence of clustered index.
By default, Unique key is a unique non-clustered index.
We can have only one Primary key in a table.
We can have more than one unique key in a table.
Primary key can be made foreign key into another table.
In SQL Server, Unique key can be made foreign key into another table.
Primary key can be made foreign key into another table.
Define Primary key and Unique key
1.
2.
3.
4.
5.
6.
7.

CREATE TABLE Employee


(
EmpID int PRIMARY KEY, --define primary key
Name varchar (50) NOT NULL,
MobileNo int UNIQUE, --define unique key
Salary int NULL
)

What is the difference between a Local and a Global temporary table?


Temporary tables are used to allow short term use of data in SQL Server. They are of 2 types:
Local

- Only available to the current Db connection for current user and are cleared when connection is
closed.
- Multiple users cant share a local temporary table.
Global
- Available to any connection once created. They are cleared when the last connection is closed.
- Can be shared by multiple user sessions.

What is the difference between a Local and a Global temporary table?


A local temporary table lives until the connection is valid or until the duration of a compound
statement.
A global temporary table is permanently present in the database. However, the rows of the table are
present until the connection is existent. Once the connection is closed, the data in the global
temporary table disappears. However, the table definition remains with the database for access when
database is opened next time.
Passing Data From One Controller To Another In ASP.NET MVC

At times you need to pass data from an action method belonging to one controller to an action method
belonging to another controller. There are three ways to accomplish this task. They are:

Pass data as query string parameters

Pass data in TempData dictionary

Pass data as route parameters

Let's quickly see how each of these three approaches work.

Pass data as query string parameters

This approach is possibly the most primitive one and involves no special consideration from your side.
The action method sending the data can use Redirect() method or RedirectToAction() method to
transfer the control to the receiving action method. The following code shows how this is done:

public ActionResult Index()


{
Customer data = new Customer()
{
CustomerID = 1,
CustomerName = "Abcd",

Country = "USA"
};
string url=string.Format ("/home2/index?customerid={0}
&customername={1}&country={2}",
data.CustomerID, data.CustomerName,data.Country);
return Redirect(url);
}

The above code shows Index() action from Home1 controller. The Index action method instantiates
Customer object - the model class - that looks like this:

public class Customer


{
public int CustomerID { get; set; }
public string CustomerName { get; set; }
public string Country { get; set; }
}

It then forms a URL pointing to the Index() action from Home2 controller. Notice how data from
Customer object is transferred in the form of query string parameters. In the above example there is no
logic for generating model data but in a more realistic case you may have such a logic in this method.
And once the data is generated you can pass it to the another controller using query string. The
Redirect() method then takes the control to the Index() action of Home2 controller.

The Index() action of Home2 can receive the data as shown below:

public ActionResult Index ()


{
Customer data = new Customer();
data.CustomerID = int.Parse (Request.QueryString ["CustomerID"]);
data. CustomerName = Request.QueryString ["CustomerName"];
data.Country = Request.QueryString ["Country"];
return View(data);

As you can see Request.QueryString collection is being used to read the values passed in the query
string. Once a Customer object is formed, it is passed to the Index view.

This technique has an advantage that it is quite simple and requires no additional configuration.
However, it's bit crude technique and you should avoid it if any of the other techniques can be used.

Pass data using TempData dictionary

In this technique you store the data to be passed in the TempData dictionary in the sender action
method. The receiving action method reads the data from the TempData dictionary. You might be aware
that TempData dictionary can hold data till it is read and this can carry data across multiple requests.
The following code shows how this is done:

public ActionResult Index()


{
Customer data = new Customer()
{
CustomerID = 1,
CustomerName = "Abcd",
Country = "USA"
};
TempData["mydata"] = data;
return RedirectToAction("Index", "Home2");
}

As you can see Index() action instantiates a Customer object as before. This time, however, it stores
the Customer object in a TempData key named mydata. The RedirectToAction() method is then used
to take the control to the Index() action of Home2 controller.

Inside the Index() of Home2, you can read the value as follows:

public ActionResult Index()

{
Customer data = TempData["mydata"] as Customer;
return View(data);
}

The above code reads the Customer object from TempData dictionary and passes it to the Index view.

The TempData technique doesn't require any additional setup but it requires that session state be
enabled. Also, TempData is designed to store arbitrary pieces of data. If you are planning to send model
objects through TempData, that may be a deviation from standard design practices.

Pass data as route parameters

In this technique you need to do an additional work of defining a route in the system. For example, if
you wish to pass the Customer data in the form of route parameters you need to define a route like this:

routes.MapRoute(
name: "Default2",
url: "{controller}/{action}/
{customerid}/{customername}/{country}",
defaults: new { controller = "Home2", action = "Index" }
);

As shown above, the route includes {customerid}, {customername}, and {country} route parameters and
the route is mapped with Index() action of Home2 controller. Once the above configuration is done you
can pass data from the sender action as follows:

public ActionResult Index1()


{
Customer data = new Customer()
{
CustomerID = 1,
CustomerName = "Abcd",
Country = "USA"

};
return RedirectToAction("Index", "Home2", data);
}

Notice that, this time the Customer object is passed as the third parameter of RedirectToAction()
method. This way Customer data will be passed in the form of route parameter values. To receive this
data the receiver action method should write something like this:

public ActionResult Index()


{
Customer data = new Customer();
UpdateModel(data);
return View(data);
}

// OR

public ActionResult Index(Customer data)


{
return View(data);
}

As shown above you can either use UpdateModel() method to transfer values from the route to the
Customer object or you can have a parameter to the Index() action method.

This technique is quite clean and makes use of MVC specific parts (route and route parameters). It
doesn't have any dependency on session state as in the case of TempData technique. On the other
hand you need to create a route to deal with the route parameters.

Note about query string and route parameters

Before I conclude this post, it would be interesting to see a small thing about how RedirectToAction()
deals with query string and route parameters.

Let's assume that your sender action is like this:

public ActionResult Index()


{
Customer data = new Customer()
{
CustomerID = 1,
CustomerName = "Abcd",
Country = "USA"
};
return RedirectToAction("Index", "Home2", data);
}

Notice that RedirectToAction () method passes Customer data object to Index() of Home2 as the third
parameter.

The interesting thing to note is - If you haven't defined any route to match the data MVC sends it as
query string. And if you have defined a route, it passes the values as route parameters. You can confirm
this by observing the browser address bar once the Index() of Home2 renders the view. The following
figure shows the difference:

That also means in the query string technique discussed earlier, you could have used exactly same
code in the receiving action as in the case of route parameter technique.
24. Access modifiers are keywords used to specify the declared accessibility of a member
or a type.
Why to use access modifiers?
Access modifiers are an integral part of object-oriented programming. They support the
concept of encapsulation, which promotes the idea of hiding functionality. Access
modifiers allow you to define who does or doesn't have access to certain features.
In C# there are 5 different types of Access Modifiers.
Modifier

Description

public

There are no restrictions on accessing public members.

private

Access is limited to within the class definition. This is the


default access modifier type if none is formally specified

protected

Access is limited to within the class definition and any


class that inherits from the class

internal

Access is limited exclusively to classes defined within the


current project assembly

protected internal

Access is limited to the current assembly and types


derived from the containing class. All members in current
project and all members in derived class can access the
variables.

public
The public keyword is an access modifier for types and type members. Public access is
the most permissive access level.
There are no restrictions on accessing public members.
Accessibility:

Can be accessed by objects of the class

Can be accessed by derived classes

Example: In the following example num1 is direct access.


using System;
namespace AccessModifiers
{
class Program
{
class AccessMod
{
public int num1;
}
static void Main(string[] args)
{
AccessMod ob1 = new AccessMod();

//Direct access to public members


ob1.num1 = 100;
Console.WriteLine("Number one value in main {0}", ob1.num1);
Console.ReadLine();
}
}
}
private
Private access is the least permissive access level.
Private members are accessible only within the body of the class or the struct in which
they are declared.
Accessibility:

Cannot be accessed by object

Cannot be accessed by derived classes

Example: In the following example num2 is not accessible outside the class.
using System;
namespace AccessModifiers
{
class Program
{
class AccessMod
{
public int num1;
int num2;
}
static void Main(string[] args)
{
AccessMod ob1 = new AccessMod();

//Direct access to public members


ob1.num1 = 100;
//Access to private member is not permitted
ob1.num2 = 20;
Console.WriteLine("Number one value in main {0}", ob1.num1);
Console.ReadLine();
}
}
}
The above program will give compilation error, as access to private is not permissible. In
the below figure you can see the private member num2 is not available.

protected
A protected member is accessible from within the class in which it is declared, and from
within any class derived from the class that declared this member.
A protected member of a base class is accessible in a derived class only if the access
takes place through the derived class type.
Accessibility:

Cannot be accessed by object

By derived classes

using System;
namespace AccessModifiers
{
class Program
{
class Base

{
protected int num1;
}
class Derived : Base
{
public int num2;
static void Main(string[] args)
{
Base ob1 = new Base();
Derived ob2 = new Derived();
ob2.num1 = 20;
// Access to protected member as it is inhertited by the Derived class
ob2.num2 = 90;
Console.WriteLine("Number2 value {0}", ob2.num2);
Console.WriteLine("Number1 value which is protected {0}", ob2.num1);
Console.ReadLine();
}
}
}
}
In the above program we try to access protected member in main it is not available as
shown in the picture below that num1 is not listed in intellisense.

internal

The internal keyword is an access modifier for types and type members. We can declare
a class as internal or its member as internal. Internal members are accessible only within
files in the same assembly (.dll).
In other words, access is limited exclusively to classes defined within the current project
assembly.
Accessibility:
In same assembly (public)

Can be accessed by objects of the class

Can be accessed by derived classes

In other assembly (internal)

Cannot be accessed by object

Cannot be accessed by derived classes

protected internal
The protected internal accessibility means protected OR internal, not protected AND
internal.
In other words, a protected internal member is accessible from any class in the same
assembly, including derived classes.
The protected internal access modifier seems to be a confusing but is a union of
protected and internal in terms of providing access but not restricting. It allows:

Inherited types, even though they belong to a different assembly, have access to
the protected internal members.

Types that reside in the same assembly, even if they are not derived from the
type, also have access to the protected internal members.

Default access
A default access level is used if no access modifier is specified in a member declaration.
The following list defines the default access modifier for certain C# types:
enum: The default and only access modifier supported is public.
class: The default access for a class is private. It may be explicitly defined using any of
the access modifiers.

interface: The default and only access modifier supported is public.


struct: The default access is private with public and internal supported as well.
The default access may suffice for a given situation, but you should specify the access
modifier you want to use to ensure proper application behavior.
Self Join SQL Example
SELECT e1.employee_name
FROM employee e1, employee e2
WHERE e1.employee_location = e2.employee_location
AND e2.employee_name="Joe";

25. What is Textbox for and Textbox in MVC

TextBox() method signature:


MvcHtmlString Html.TextBox(string name, string value, object htmlAttributes)
TextBox method has many overloads. Please visit MSDN to know all the overloads of
TextBox () method.
The TextBox() method is a loosely typed method because name parameter is a string. The
name parameter can be a property name of model object. It binds specified property with
textbox. So it automatically displays a value of the model property in a textbox and visaversa.
Example: Html.TextBox() in Razor View
@model Student
@Html.TextBox("StudentName", null, new { @class = "form-control" })
TextBoxFor:
TextBoxFor helper method is a strongly typed extension method. It generates a text input
element for the model property specified using a lambda expression. TextBoxFor method
binds a specified model object property to input text. So it automatically displays a value
of the model property in a textbox and visa-versa.

TextBoxFor() method Signature:


MvcHtmlString
TextBoxFor(Expression<Func<TModel,TValue>>
htmlAttributes)
Visit MSDN to know all the overloads of TextBoxFor() method.
Example: TextBoxFor() in Razor View
@model Student

expression,

object

@Html.TextBoxFor(m => m.StudentName, new { @class = "form-control" })


Declaring an Attribute Class
Declaring an attribute in C# is simple it takes the form of a class declaration that inherits
from System.Attribute and has been marked with theAttributeUsage attribute as shown below:
using System;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute
{
public readonly string Url;
public string Topic
{
get
{
return topic;
}
set
{

// Topic is a named parameter

topic = value;
}
}
public HelpAttribute(string url)
{
this.Url = url;
}

// url is a positional parameter

private string topic;


}
Code Discussion

The attribute AttributeUsage specifies the language elements to which the attribute can be
applied.
Attributes classes are public classes derived from System.Attribute that have at least one
public constructor.
Attribute classes have two types of parameters:
Positional parameters must be specified every time the attribute is used. Positional
parameters are specified as constructor arguments to the attribute class. In the
example above, url is a positional parameter.
Named parameters are optional. If they are specified when the attribute is used, the
name of the parameter must be used. Named parameters are defined by having a
nonstatic field or property. In the example above, Topic is a named parameter.
Attribute parameters are restricted to constant values of the following types:
Simple types (bool, byte, char, short, int, long, float, and double)
string
System.Type
enums
object (The argument to an attribute parameter of type object must be a constant
value of one of the above types.)
One-dimensional arrays of any of the above types

Parameters for the AttributeUsage Attribute


The attribute AttributeUsage provides the underlying mechanism by which attributes are declared.
AttributeUsage has one positional parameter:

AllowOn, which specifies the program elements that the attribute can be assigned to (class,
method, property, parameter, and so on). Valid values for this parameter can be found in
the System.Attributes.AttributeTargets enumeration in the .NET Framework. The default
value for this parameter is all program elements (AttributeElements.All).

AttributeUsage has one named parameter:

AllowMultiple, a Boolean value that indicates whether multiple attributes can be specified for
one program element. The default value for this parameter is False.

Using an Attribute Class


Here's a simple example of using the attribute declared in the previous section:
[HelpAttribute ("http://localhost/MyClassInfo")]
class MyClass
{
}
In this example, the HelpAttribute attribute is associated with MyClass.
Note By convention, all attribute names end with the word "Attribute" to distinguish them from
other items in the .NET Framework. However, you do not need to specify the attribute suffix when
using attributes in code. For example, you can specify HelpAttribute as follows:
[Help("http://localhost/MyClassInfo")] // [Help] == [HelpAttribute]
class MyClass
{
}
Accessing Attributes Through Reflection
Once attributes have been associated with program elements, reflection can be used to query their
existence and values. The main reflection methods to query attributes are contained in
the System.Reflection.MemberInfo class (GetCustomAttributes family of methods). The following
example demonstrates the basic way of using reflection to get access to attributes:
class MainClass
{
public static void Main()
{
System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i ++)
{
System.Console.WriteLine (attributes[i]);
}
}
}
Example
The following is a complete example where all pieces are brought together.
// AttributesTutorial.cs
// This example shows the use of class and method attributes.

using System;
using System.Reflection;
using System.Collections;
// The IsTested class is a user-defined custom attribute class.
// It can be applied to any declaration including
// - types (struct, class, enum, delegate)
// - members (methods, fields, events, properties, indexers)
// It is used with no arguments.
public class IsTestedAttribute : Attribute
{
public override string ToString()
{
return "Is Tested";
}
}
// The AuthorAttribute class is a user-defined attribute class.
// It can be applied to classes and struct declarations only.
// It takes one unnamed string argument (the author's name).
// It has one optional named argument Version, which is of type int.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class AuthorAttribute : Attribute
{
// This constructor specifies the unnamed arguments to the attribute
class.
public AuthorAttribute(string name)
{
this.name = name;
this.version = 0;
}
// This property is readonly (it has no set accessor)
// so it cannot be used as a named argument to this attribute.
public string Name
{
get
{
return name;
}
}
// This property is read-write (it has a set accessor)
// so it can be used as a named argument when using this
// class as an attribute class.
public int Version
{
get
{
return version;
}
set

{
version = value;
}
}
public override string ToString()
{
string value = "Author : " + Name;
if (version != 0)
{
value += " Version : " + Version.ToString();
}
return value;
}
private string name;
private int version;
}
// Here you attach the AuthorAttribute user-defined custom attribute to
// the Account class. The unnamed string argument is passed to the
// AuthorAttribute class's constructor when creating the attributes.
[Author("Joe Programmer")]
class Account
{
// Attach the IsTestedAttribute custom attribute to this method.
[IsTested]
public void AddOrder(Order orderToAdd)
{
orders.Add(orderToAdd);
}
private ArrayList orders = new ArrayList();
}
// Attach the AuthorAttribute and IsTestedAttribute custom attributes
// to this class.
// Note the use of the 'Version' named argument to the AuthorAttribute.
[Author("Jane Programmer", Version = 2), IsTested()]
class Order
{
// add stuff here ...
}
class MainClass
{
private static bool IsMemberTested(MemberInfo member)
{
foreach (object attribute in member.GetCustomAttributes(true))
{
if (attribute is IsTestedAttribute)
{
return true;

}
}
return false;
}
private static void DumpAttributes(MemberInfo member)
{
Console.WriteLine("Attributes for : " + member.Name);
foreach (object attribute in member.GetCustomAttributes(true))
{
Console.WriteLine(attribute);
}
}
Public static void Main ()
{
// display attributes for Account class
DumpAttributes(typeof(Account));
// display list of tested members
foreach (MethodInfo method in (typeof (Account)).GetMethods())
{
if (IsMemberTested(method))
{
Console.WriteLine("Member {0} is tested!", method.Name);
}
else
{
Console.WriteLine ("Member {0} is NOT tested!",
method.Name);
}
}
Console.WriteLine();
// display attributes for Order class
DumpAttributes(typeof(Order));
// display attributes for methods on the Order class
foreach (MethodInfo method in (typeof(Order)).GetMethods())
{
if (IsMemberTested(method))
{
Console.WriteLine("Member {0} is tested!", method.Name);
}
else
{
Console.WriteLine("Member {0} is NOT tested!", method.Name);
}
}
Console.WriteLine();
}
}
Output

Attributes for : Account


Author : Joe Programmer
Member GetHashCode is NOT tested!
Member Equals is NOT tested!
Member ToString is NOT tested!
Member AddOrder is tested!
Member GetType is NOT tested!
Attributes for: Order
Author: Jane Programmer Version: 2
Is Tested
Member GetHashCode is NOT tested!
Member Equals is NOT tested!
Member ToString is NOT tested!
Member GetType is NOT tested!
How can I get the ID of an element using jQuery?
<div id="test"></div>
$(document).ready(function() {
alert($('#test').id);
});
Get class name using jQuery
<div class="myclass"></div>
var className = $('.myclass').attr('class');
Understanding Action Filters
The goal of this tutorial is to explain action filters. An action filter is an attribute that you can apply to
a controller action -- or an entire controller -- that modifies the way in which the action is executed.
The ASP.NET MVC framework includes several action filters:

OutputCache This action filter caches the output of a controller action for a specified amount of
time.

HandleError This action filter handles errors raised when a controller action executes.

Authorize This action filter enables you to restrict access to a particular user or role.

You also can create your own custom action filters. For example, you might want to create a custom
action filter in order to implement a custom authentication system. Or, you might want to create an
action filter that modifies the view data returned by a controller action.
In this tutorial, you learn how to build an action filter from the ground up. We create a Log action filter
that logs different stages of the processing of an action to the Visual Studio Output window.

Using an Action Filter


An action filter is an attribute. You can apply most action filters to either an individual controller action
or an entire controller.
For example, the Data controller in Listing 1 exposes an action named Index () that returns the
current time. This action is decorated with theOutputCache action filter. This filter causes the value
returned by the action to be cached for 10 seconds.
Listing 1 Controllers\DataController.cs
using System;

using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
Public class DataController : Controller
{
[OutputCache(Duration=10)]
Public string Index ()
{
return DateTime.Now.ToString("T");
}
}
}
If you repeatedly invoke the Index() action by entering the URL /Data/Index into the address bar of
your browser and hitting the Refresh button multiple times, then you will see the same time for 10
seconds. The output of the Index () action is cached for 10 seconds (see Figure 1).

Figure 01: Cached time (Click to view full-size image)


In Listing 1, a single action filter the OutputCache action filter is applied to the Index () method.
If you need, you can apply multiple action filters to the same action. For example, you might want to
apply both the OutputCache and HandleError action filters to the same action.
In Listing 1, the OutputCache action filter is applied to the Index () action. You also could apply this
attribute to the DataController class itself. In that case, the result returned by any action exposed by
the controller would be cached for 10 seconds.

The Different Types of Filters


The ASP.NET MVC framework supports four different types of filters:
1. Authorization filters Implements the IAuthorizationFilter attribute.
2. Action filters Implements the IActionFilter attribute.
3. Result filters Implements the IResultFilter attribute.
4. Exception filters Implements the IExceptionFilter attribute.
Filters are executed in the order listed above. For example, authorization filters are always executed
before action filters and exception filters are always executed after every other type of filter.
Authorization filters are used to implement authentication and authorization for controller actions. For
example, the Authorize filter is an example of an Authorization filter.
Action filters contain logic that is executed before and after a controller action executes. You can use
an action filter, for instance, to modify the view data that a controller action returns.

Result filters contain logic that is executed before and after a view result is executed. For example, you
might want to modify a view result right before the view is rendered to the browser.
Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised
by either your controller actions or controller action results. You also can use exception filters to log
errors.
Each different type of filter is executed in a particular order. If you want to control the order in which
filters of the same type are executed then you can set a filter's Order property.
The base class for all action filters is the System.Web.Mvc.FilterAttribute class. If you want to
implement a particular type of filter, then you need to create a class that inherits from the base Filter
class and implements one or more of the IAuthorizationFilter,IActionFilter, IResultFilter,
or ExceptionFilter interfaces.

The Base ActionFilterAttribute Class


In order to make it easier for you to implement a custom action filter, the ASP.NET MVC framework
includes a base ActionFilterAttributeclass. This class implements both
the IActionFilter and IResultFilter interfaces and inherits from the Filter class.
The terminology here is not entirely consistent. Technically, a class that inherits from the
ActionFilterAttribute class is both an action filter and a result filter. However, in the loose sense, the
word action filter is used to refer to any type of filter in the ASP.NET MVC framework.
The base ActionFilterAttribute class has the following methods that you can override:
OnActionExecuting This method is called before a controller action is executed.

OnActionExecuted This method is called after a controller action is executed.

OnResultExecuting This method is called before a controller action result is executed.

OnResultExecuted This method is called after a controller action result is executed.

In the next section, we'll see how you can implement each of these different methods.

Creating a Log Action Filter


In order to illustrate how you can build a custom action filter, we'll create a custom action filter that
logs the stages of processing a controller action to the Visual Studio Output window.
Our LogActionFilter is contained in Listing 2.
Listing 2 ActionFilters\LogActionFilter.cs
using
using
using
using

System;
System.Diagnostics;
System.Web.Mvc;
System.Web.Routing;

namespace MvcApplication1.ActionFilters
{
public class LogActionFilter : ActionFilterAttribute
{

public override void OnActionExecuting(ActionExecutingContext


filterContext)
{
Log("OnActionExecuting", filterContext.RouteData);
}
public override void OnActionExecuted(ActionExecutedContext
filterContext)
{
Log("OnActionExecuted", filterContext.RouteData);
}
public override void OnResultExecuting(ResultExecutingContext
filterContext)
{
Log("OnResultExecuting", filterContext.RouteData);
}
public override void OnResultExecuted(ResultExecutedContext
filterContext)
{
Log("OnResultExecuted", filterContext.RouteData);
}

private void Log(string methodName, RouteData routeData)


{
var controllerName = routeData.Values["controller"];
var actionName = routeData.Values["action"];
var message = String.Format("{0} controller:{1} action:{2}",
methodName, controllerName, actionName);
Debug.WriteLine(message, "Action Filter Log");
}
}
}
In Listing 2, the OnActionExecuting(), OnActionExecuted(), OnResultExecuting(),
and OnResultExecuted() methods all call the Log()method. The name of the method and the
current route data is passed to the Log() method. The Log() method writes a message to the Visual
Studio Output window (see Figure 2).

Figure 02: Writing to the Visual Studio Output window (Click to view full-size image)
The Home controller in Listing 3 illustrates how you can apply the Log action filter to an entire
controller class. Whenever any of the actions exposed by the Home controller are invoked either
the Index() method or the About() method the stages of processing the action are logged to the
Visual Studio Output window.
Listing 3 Controllers\HomeController.cs
using System.Web.Mvc;
using MvcApplication1.ActionFilters;
namespace MvcApplication1.Controllers
{
[LogActionFilter]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
}
}
Filtering in ASP.NET MVC
In ASP.NET MVC, controllers define action methods that usually have a one-to-one relationship with
possible user interactions, such as clicking a link or submitting a form. For example, when the user
clicks a link, a request is routed to the designated controller, and the corresponding action method is
called.
Sometimes you want to perform logic either before an action method is called or after an action
method runs. To support this, ASP.NET MVC provides filters. Filters are custom classes that provide
both a declarative and programmatic means to add pre-action and post-action behavior to controller
action methods.
A Visual Studio project with source code is available to accompany this topic: Download.
ASP.NET MVC Filter Types
ASP.NET MVC supports the following types of action filters:
Authorization filters. These implement IAuthorizationFilter and make security decisions about
whether to execute an action method, such as performing authentication or validating
properties of the request. The AuthorizeAttribute class and the RequireHttpsAttribute class are
examples of an authorization filter. Authorization filters run before any other filter.
Action filters. These implement IActionFilter and wrap the action method execution.
The IActionFilter interface declares two
methods:OnActionExecuting and OnActionExecuted. OnActionExecuting runs before the
action method. OnActionExecuted runs after the action method and can perform additional
processing, such as providing extra data to the action method, inspecting the return value, or
canceling execution of the action method.
Result filters. These implement IResultFilter and wrap execution of
the ActionResult object. IResultFilter declares two

methods:OnResultExecuting and OnResultExecuted. OnResultExecuting runs before


the ActionResult object is executed. OnResultExecuted runs after the result and can perform
additional processing of the result, such as modifying the HTTP response.
The OutputCacheAttribute class is one example of a result filter.
Exception filters. These implement IExceptionFilter and execute if there is an unhandled
exception thrown during the execution of the ASP.NET MVC pipeline. Exception filters can be
used for tasks such as logging or displaying an error page. The HandleErrorAttribute class is
one example of an exception filter.
The Controller class implements each of the filter interfaces. You can implement any of the filters for a
specific controller by overriding the controller's On<Filter> method. For example, you can override
the OnAuthorization method. The simple controller included in the downloadable sample overrides
each of the filters and writes out diagnostic information when each filter runs. You can implement the
following On<Filter>methods in a controller:
OnAuthorization
OnException
OnActionExecuting
OnActionExecuted
OnResultExecuting
OnResultExecuted
Filters Provided in ASP.NET MVC
ASP.NET MVC includes the following filters, which are implemented as attributes. The filters can be
applied at the action method, controller, or application level.
AuthorizeAttribute. Restricts access by authentication and optionally authorization.
HandleErrorAttribute. Specifies how to handle an exception that is thrown by an action
method.

Srikant singh
9013870872

Potrebbero piacerti anche