,C#,MVC, Sqlserver, Jquery, WCF Interview Question Answer
,C#,MVC, Sqlserver, Jquery, WCF Interview Question Answer
1.
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.
2.
3.
4.
5.
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.
4.
5.
6.
1.
2.
3.
It is not open source but can be consumed by any client that understands xml.
4.
1.
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.
1.
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.
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.
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.
Array
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
from
if
the
you
one
to
add
the
to
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.
3.
4.
5.
Data Caching
6.
Data Compression
Types of Filters
The ASP.NET MVC framework provides five types of filters.
1.
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-
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.
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.
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.
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.
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.
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
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 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
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.
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'
The text, ntext, and image columns cannot be referenced in the AFTER trigger
logic.
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.
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:
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.
4.
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.
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.
2.
This type of trigger is useful for controlling development and production database
environments.
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.
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
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
interface
methods
methods
abstract methods
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:
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
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
}
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
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
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
}
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.
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.
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:
Output:
Output:
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.
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
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";
}
When you click on the Submit Button the output with EnableViewState="false":
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".
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.
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.
- 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.
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:
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:
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:
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:
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.
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:
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:
{
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.
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:
};
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:
// OR
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.
Before I conclude this post, it would be interesting to see a small thing about how RedirectToAction()
deals with query string and route parameters.
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
private
protected
internal
protected internal
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:
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();
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:
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)
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.
expression,
object
topic = value;
}
}
public HelpAttribute(string url)
{
this.Url = url;
}
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
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).
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 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
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 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).
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.
In the next section, we'll see how you can implement each of these different methods.
System;
System.Diagnostics;
System.Web.Mvc;
System.Web.Routing;
namespace MvcApplication1.ActionFilters
{
public class LogActionFilter : ActionFilterAttribute
{
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
Srikant singh
9013870872