What is LINQ?
It stands for Language Integrated Query. LINQ is collection of standard query operators that provides the query facilities into .NET framework language like C# , VB.NET.
Why Select clause comes after from clause in LINQ?
The reason is, LINQ is used with C# or other programming languages, which requires all the variables to be declared first. From clause of LINQ query just defines the range or conditions to select records. So that’s why from clause must appear before Select in LINQ.
How LINQ is beneficial than Stored Procedures?
There are couple of advantage of LINQ over stored procedures.
1. Debugging - It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you can use visual studio's debugger to debug the queries.
2. Deployment - With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy.
3. Type Safety - LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception!
What is a Lambda expression?
A Lambda expression is nothing but an Anonymous Function, can contain expressions and statements. Lambda expressions can be used mostly to create delegates or expression tree types. Lambda expression uses lambda operator => and read as 'goes to' operator.
Left side of this operator specifies the input parameters and contains the expression or statement block at the right side.
Example: myExp = myExp/10;
Now, let see how we can assign the above to a delegate and create an expression tree:
delegate int myDel(int intMyNum);
static void Main(string[] args)
{
//assign lambda expression to a delegate:
myDel myDelegate = myExp => myExp / 10;
int intRes = myDelegate(110);
Console.WriteLine("Output {0}", intRes);
Console.ReadLine();
//Create an expression tree type
//This needs System.Linq.Expressions
Expression myExpDel = myExp => myExp /10;
}
No te:
The => operator has the same precedence as assignment (=) and is right-associative.
Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where
Note: If any of the Action filters are added to the filter collection in Global.asax, then the scope of the filter is the application.
Filter Types
The asynchronous controller enables you to write asynchronous action methods. It allows you to perform long running operation(s) without making the running thread idle. It does not mean it will take lesser time to complete the action. If a request make a service call that require two seconds to complete it, the request will take two seconds whether it is performed synchronously or asynchronously. However, during asynchronous call, the server is not blocked from responding to the other requests.
It stands for Language Integrated Query. LINQ is collection of standard query operators that provides the query facilities into .NET framework language like C# , VB.NET.
Why Select clause comes after from clause in LINQ?
The reason is, LINQ is used with C# or other programming languages, which requires all the variables to be declared first. From clause of LINQ query just defines the range or conditions to select records. So that’s why from clause must appear before Select in LINQ.
How LINQ is beneficial than Stored Procedures?
There are couple of advantage of LINQ over stored procedures.
1. Debugging - It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you can use visual studio's debugger to debug the queries.
2. Deployment - With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy.
3. Type Safety - LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception!
What is a Lambda expression?
A Lambda expression is nothing but an Anonymous Function, can contain expressions and statements. Lambda expressions can be used mostly to create delegates or expression tree types. Lambda expression uses lambda operator => and read as 'goes to' operator.
Left side of this operator specifies the input parameters and contains the expression or statement block at the right side.
Example: myExp = myExp/10;
Now, let see how we can assign the above to a delegate and create an expression tree:
delegate int myDel(int intMyNum);
static void Main(string[] args)
{
//assign lambda expression to a delegate:
myDel myDelegate = myExp => myExp / 10;
int intRes = myDelegate(110);
Console.WriteLine("Output {0}", intRes);
Console.ReadLine();
//Create an expression tree type
//This needs System.Linq.Expressions
Expression myExpDel = myExp => myExp /10;
}
No te:
The => operator has the same precedence as assignment (=) and is right-associative.
Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where
ViewData
- ViewData is a dictionary object that is derived from ViewDataDictionary class.
- ViewData is used to pass data from controller to corresponding view.
- It’s life lies only during the current request.
- If redirection occurs then it’s value becomes null.
- It’s required typecasting for complex data type and check for null values to avoid error.
ViewBag
- ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
- Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
- It’s life also lies only during the current request.
- If redirection occurs then it’s value becomes null.
- It doesn’t required typecasting for complex data type.
TempData
- TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
- TempData is used to pass data from current request to subsequent request means incase of redirection.
- It’s life is very short and lies only till the target view is fully loaded.
- It’s required typecasting for complex data type and check for null values to avoid error.
- It is used to store only one time messages like error messages, validation messages.
ViewData, ViewBag and TempData Current Request Example
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- var emp = new Employee
- {
- EmpID=101,
- Name = "Deepak",
- Salary = 35000,
- Address = "Delhi"
- };
- ViewData["emp"] = emp;
- ViewBag.Employee = emp;
- TempData["emp"] = emp;
- return View(); }
- }
WCF Rest
- To use WCF as WCF Rest service you have to enable webHttpBindings.
- It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
- To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
- Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified
- It support XML, JSON and ATOM data format.
Web API
- This is the new framework for building HTTP services with easy and simple way.
- Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
- Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)
- 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.
- It can be hosted with in the application or on IIS.
- It is light weight architecture and good for devices which have limited bandwidth like smart phones.
- Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.
To whom choose between WCF or WEB API
- Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.
- Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.
- Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
- Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.
RESTful service
RESTful services are those which follow the REST (Representational State Transfer) architectural style.
Before implementing your first RESTful service, lets first understand the concept behind it. As we know that WCF allows us to make calls and exchange messages using SOAP over a variety of protocols i.e. HTTP, TCP, Named Pipes and MSMQ etc. In a scenario, if we are using SOAP over HTTP, we are just utilizing HTTP as a transport. But HTTP is much more than just a transport. So, when we talk about REST architectural style, it dictates that “Instead of using complex mechanisms like CORBA, RPC or SOAP for communication, simply HTTP should be used for making calls”.
RESTful architecture use HTTP for all CRUD operations like (Read/Create/Update/Delete) using simple HTTP verbs like (GET, POST, PUT, and DELETE). It’s simple as well as lightweight. For the sake of simplicity, I am going to implement only a GET request for which service will return certain types of data (i.e. Product data) in XML format
Before implementing your first RESTful service, lets first understand the concept behind it. As we know that WCF allows us to make calls and exchange messages using SOAP over a variety of protocols i.e. HTTP, TCP, Named Pipes and MSMQ etc. In a scenario, if we are using SOAP over HTTP, we are just utilizing HTTP as a transport. But HTTP is much more than just a transport. So, when we talk about REST architectural style, it dictates that “Instead of using complex mechanisms like CORBA, RPC or SOAP for communication, simply HTTP should be used for making calls”.
RESTful architecture use HTTP for all CRUD operations like (Read/Create/Update/Delete) using simple HTTP verbs like (GET, POST, PUT, and DELETE). It’s simple as well as lightweight. For the sake of simplicity, I am going to implement only a GET request for which service will return certain types of data (i.e. Product data) in XML format
Action Filters
There are a set of Action filters available with ASP.NET MVC 3 to
filter actions. Action filters are defined as attributes and applied to
an Action or controller.
1. Authorize
Authorize filters ensure that the corresponding Action will be called
by an authorized user only. If the user is not authorized, he will be
redirected to the login page.[Authorize]
public ActionResult About()
{
return View();
}
If the user is not authorized and invoke the About action, then he will redirected to the log on page.
2. HandleError
HandleError
will handle the various exceptions thrown by
the application and display user friendly message to the user. By
default, this filter is registered in Global.asax.Note: If any of the Action filters are added to the filter collection in Global.asax, then the scope of the filter is the application.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
For verifying a filter, let us enable a custom error in web.config:Filter Types
- 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.
Asynchronous Controller
The AsyncController
class enables you to write asynchronous action methods. You can use
asynchronous action methods for long-running, non-CPU bound requests.
This avoids blocking the Web server from performing work while the
request is being processed. A typical use for the AsyncController class is long-running Web service calls. The asynchronous controller enables you to write asynchronous action methods. It allows you to perform long running operation(s) without making the running thread idle. It does not mean it will take lesser time to complete the action. If a request make a service call that require two seconds to complete it, the request will take two seconds whether it is performed synchronously or asynchronously. However, during asynchronous call, the server is not blocked from responding to the other requests.
Asynchronous Controller
Asynchronous action methods are useful when an action must
perform several independent long running operations. Suppose we have
three operations which takes 500, 600 and 700 milliseconds. With the
synchronous call, total response time would be slightly more than 1800
milliseconds. However, if the calls are made asynchronously (in
parallel), total response time would be slightly more than 700
milliseconds, because that is the duration of longest task/operation.
How to create Asynchronous Controller
- Inherits MVC controller with AsyncController instead of Controller.
- Asynchronous action methods are useful when an action must perform several independent long running operations. Suppose we have three operations which takes 500, 600 and 700 milliseconds. With the synchronous call, total response time would be slightly more than 1800 milliseconds. However, if the calls are made asynchronously (in parallel), total response time would be slightly more than 700 milliseconds, because that is the duration of longest task/operation.
public class AsynchronuosTestingController : AsyncController
{
private readonly object _lock = new object();
public void IndexAsync()
{
AsyncManager.OutstandingOperations.Increment(2);
Operation1();
Operation2();
}
public ActionResult IndexCompleted(string Operation1, string Operation2)
{
ViewData["Operation1"] = Operation1;
ViewData["Operation2"] = Operation2;
return View("Index");
}
void Operation1()
{
lock (_lock)
{
AsyncManager.Parameters["Operation1"] = "Result1";
}
//last line of this method
AsyncManager.OutstandingOperations.Decrement();
}
void Operation2()
{
lock (_lock)
{
AsyncManager.Parameters["Operation2"] = "Result2";
}
//last line of this method
AsyncManager.OutstandingOperations.Decrement();
}
}
1.
What is MVC?
MVC
is a framework methodology that divides an application’s implementation into
three component roles: models, views, and controllers.
Main
components of an MVC application?
1.
M - Model
2.
V - View
3.
C - Controller
“Models”
in a MVC based application are the components of the application that are
responsible for maintaining state. Often this state is persisted inside a
database (for example: we might have a Product class that is used to represent
order data from the Products table inside SQL).
“Views”
in a MVC based application are the components responsible for displaying the
application’s user interface. Typically this UI is created off of the model
data (for example: we might create an Product “Edit” view that surfaces textboxes,
dropdowns and checkboxes based on the current state of a Product object).
“Controllers”
in a MVC based application are the components responsible for handling end user
interaction, manipulating the model, and ultimately choosing a view to render
to display UI. In a MVC application the view is only about displaying
information – it is the controller that handles and responds to user input and
interaction.
2-
What does Model, View and Controller represent in an MVC application?
Model: Model
represents the application data domain. In short the applications business
logic is contained with in the model.
View: Views
represent the user interface, with which the end users interact. In short the
all the user interface logic is contained with in the UI.
Controller: Controller
is the component that responds to user actions. Based on the user actions, the
respective controller, work with the model, and selects a view to render that
displays the user interface. The user input logic is contained with in the
controller.
3-
In which assembly is the MVC framework defined?
System.Web.Mvc
4-
What is the greatest advantage of using asp.net mvc over asp.net webforms?
It
is difficult to unit test UI with webforms, where views in mvc can be very
easily unit tested.
5-
Which approach provides better support for test driven development - ASP.NET
MVC or ASP.NET Webforms?
ASP.NET
MVC
6-
What is Razor View Engine?
Razor
view engine is a new view engine created with ASP.Net MVC model using specially
designed Razor parser to render the HTML out of dynamic server side code. It
allows us to write Compact, Expressive, Clean and Fluid code with new syntax to
include server side code in to HTML.
7-
What are the advantages of ASP.NET MVC?
Advantages
of ASP.NET MVC:
1.
Extensive support for TDD. With asp.net MVC, views can also be very easily unit
tested.
2.
Complex applications can be easily managed
3. Separation of
concerns. Different aspects of the application can be divided into Model, View
and Controller.
4.
ASP.NET MVC views are light weight, as they don't use viewstate.
8-
Is it possible to unit test an MVC application without running the controllers
in an ASP.NET process?
Yes,
all the features in an asp.net MVC application are interface based and hence
mocking is much easier. So, we don't have to run the controllers in an ASP.NET
process for unit testing.
9-
What is namespace of ASP.NET MVC?
ASP.NET
MVC namespaces and classes are located in the System.Web.Mvc assembly.
System.Web.Mvc
namespace
Contains
classes and interfaces that support the MVC pattern for ASP.NET Web
applications. This namespace includes classes that represent controllers,
controller factories, action results, views, partial views, and model binders.
System.Web.Mvc.Ajax
namespace
Contains
classes that support Ajax scripts in an ASP.NET MVC application. The namespace
includes support for Ajax scripts and Ajax option settings.
System.Web.Mvc.Async
namespace
Contains
classes and interfaces that support asynchronous actions in an ASP.NET MVC
application.
System.Web.Mvc.Html
namespace
Contains
classes that help render HTML controls in an MVC application. The namespace
includes classes that support forms, input controls, links, partial views, and
validation.
10-
Is it possible to share a view across multiple controllers?
Yes,
put the view into the shared folder. This will automatically make the view available
across multiple controllers.
11-
What is the role of a controller in an MVC application?
The
controller responds to user interactions, with the application, by selecting
the action method to execute and selecting the view to render.
12-
Where are the routing rules defined in an asp.net MVC application?
In
Application_Start event in Global.asax
13-
Name a few different return types of a controller action method?
The
following are just a few return types of a controller action method. In general
an action method can return an instance of a any class that derives from
ActionResult class.
1.
ViewResult
2.
JavaScriptResult
3.
RedirectResult
4.
ContentResult
5.
JsonResult
14-
What is the ‘page lifecycle’ of an ASP.NET MVC?
Following
process are performed by ASP.Net MVC page:
1)
App initialization
2)
Routing
3)
Instantiate and execute controller
4)
Locate and invoke controller action
5)
Instantiate and render view
15-
What is the significance of NonActionAttribute?
In
general, all public methods of a controller class are treated as action
methods. If you want prevent this default behavior, just decorate the
public method with NonActionAttribute.
16-
What is the significance of ASP.NET routing?
ASP.NET
MVC uses ASP.NET routing, to map incoming browser requests to controller action
methods. ASP.NET Routing makes use of route table. Route table is created when
your web application first starts. The route table is present in the
Global.asax file.
17-
How route table is created in ASP.NET MVC?
When
an MVC application first starts, the Application_Start() method is called. This
method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method
creates the route table.
18-
What are the 3 segments of the default route, that is present in an ASP.NET MVC
application?
1st
Segment - Controller Name
2nd
Segment - Action Method Name
3rd
Segment - Parameter that is passed to the action method
Example:
http://google.com/search/label/MVC
Controller
Name = search
Action
Method Name = label
Parameter
Id = MVC
19-
ASP.NET MVC application, makes use of settings at 2 places for routing to work
correctly. What are these 2 places?
1.
Web.Config File : ASP.NET routing has to be enabled here.
2.
Global.asax File : The Route table is created in the application Start event
handler, of the Global.asax file.
20-
What is the adavantage of using ASP.NET routing?
In
an ASP.NET web application that does not make use of routing, an incoming
browser request should map to a physical file. If the file does not exist, we
get page not found error.
An
ASP.NET web application that does make use of routing, makes use of URLs that
do not have to map to specific files in a Web site. Because the URL does not
have to map to a file, you can use URLs that are descriptive of the user's
action and therefore are more easily understood by users.
21-
What are the 3 things that are needed to specify a route?
1.
URL Pattern - You can include placeholders in a URL pattern so that variable
data can be passed to the request handler without requiring a query string.
2.
Handler - The handler can be a physical file such as an .aspx file or a
controller class.
3.
Name for the Route - Name is optional.
22-
Is the following route definition a valid route definition?
{controller}{action}/{id}
No,
the above definition is not a valid route definition, because there is no
literal value or delimiter between the placeholders. Therefore, routing cannot
determine where to separate the value for the controller placeholder from the
value for the action placeholder.
23-
What is the use of the following default route?
{resource}.axd/{*pathInfo}
This
route definition, prevent requests for the Web resource files such as
WebResource.axd or ScriptResource.axd from being passed to a controller.
24-
What is the difference between adding routes, to a webforms application and to
an mvc application?
To
add routes to a webforms application, we use MapPageRoute() method of the
RouteCollection class, where as to add routes to an MVC application we use
MapRoute() method.
25-
How do you handle variable number of segments in a route definition?
Use
a route with a catch-all parameter. An example is shown below. * is referred to
as catch-all parameter.
controller/{action}/{*parametervalues}
26-
What are the 2 ways of adding constraints to a route?
1.
Use regular expressions
2.
Use an object that implements IRouteConstraint interface
27-
Give 2 examples for scenarios when routing is not applied?
1.
A Physical File is Found that Matches the URL Pattern - This default behaviour
can be overriden by setting the RouteExistingFiles property of the
RouteCollection object to true.
2.
Routing Is Explicitly Disabled for a URL Pattern - Use the
RouteCollection.Ignore() method to prevent routing from handling certain
requests.
28-
What is the use of action filters in an MVC application?
Action
Filters allow us to add pre-action and post-action behavior to controller
action methods.
29-
If I have multiple filters implemented, what is the order in which these
filters get executed?
1.
Authorization filters
2.
Action filters
3.
Response filters
4.
Exception filters
30-
What are the different types of filters, in an asp.net mvc application?
1.
Authorization filters
2.
Action filters
3.
Result filters
4.
Exception filters
31-
Give an example for Authorization filters in an asp.net mvc application?
1.
RequireHttpsAttribute
2.
AuthorizeAttribute
32-
Which filter executes first in an asp.net mvc application?
Authorization
filter
33-
What are the levels at which filters can be applied in an asp.net mvc
application?
1.
Action Method
2.
Controller
3.
Application
34-
Is it possible to create a custom filter?
Yes
35-
What filters are executed in the end?
Exception
Filters
36-
Is it possible to cancel filter execution?
Yes
37-
What type of filter does OutputCacheAttribute class represents?
Result
Filter
38-
What are the 2 popular asp.net mvc view engines?
1.
Razor
2.
.aspx
39-
What is difference between Viewbag and Viewdata in ASP.NET MVC?
The
basic difference between ViewData and ViewBag is that in ViewData instead
creating dynamic properties we use properties of Model to transport the Model
data in View and in ViewBag we can create dynamic properties without using
Model data.
40-
What symbol would you use to denote, the start of a code block in razor views?
@
41-
What symbol would you use to denote, the start of a code block in aspx views?
<%=
%>
In
razor syntax, what is the escape sequence character for @ symbol?
The
escape sequence character for @ symbol, is another @ symbol
42-
When using razor views, do you have to take any special steps
to protect your asp.net mvc application from cross site scripting
(XSS) attacks?
No,
by default content emitted using a @ block is automatically HTML encoded to
protect from cross site scripting (XSS) attacks.
43-
When using aspx view engine, to have a consistent look and feel, across all
pages of the application, we can make use of asp.net master pages. What is
asp.net master pages equivalent, when using razor views?
To
have a consistent look and feel when using razor views, we can make use of
layout pages. Layout pages, reside in the shared folder, and are named as
_Layout.cshtml
44-
What are sections?
Layout
pages, can define sections, which can then be overriden by specific views
making use of the layout. Defining and overriding sections is optional.
45-
What are the file extensions for razor views?
1.
.cshtml - If the programming lanugaue is C#
2.
.vbhtml - If the programming lanugaue is VB
46-
How do you specify comments using razor syntax?
Razor
syntax makes use of @* to indicate the begining of a comment and *@ to indicate
the end.
47-
What is Routing?
A
route is a URL pattern that is mapped to a handler. The handler can be a
physical file, such as an .aspx file in a Web Forms application. Routing module
is responsible for mapping incoming browser requests to particular MVC controller
actions.
48-
Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web
application?
Yes,
it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web
application.
49.
How do you avoid XSS Vulnerabilities in ASP.NET MVC?
Use
the syntax in ASP.NET MVC instead of using .net framework 4.0.
very informative blog and useful article thank you for sharing with us , keep
ReplyDeleteposting
.NET Online Course Hyderabad