What are the ASP.NET default handlers? | ASP.Net Interview Question | ASP.NET Programmer Guide

, ,
ASP.NET default handlers:

        1.Page Handler (.aspx) - Handles Web pages
        2.User Control Handler (.ascx) - Handles Web user control pages
        3.Web Service Handler (.asmx) - Handles Web service pages
        4.Trace Handler (trace.axd) - Handles trace functionality

What is HTTP handler? | ASP.Net Interview Question | ASP.NET Programmer Guide

, ,
                Every request into an ASP.NET application is handled by a specialized component known as an HTTP handler. The HTTP handler is the most important ingredient while handling ASP.NET requests.

What are the advantages of Web Farm and Web Garden? | ASP.Net Interview Question | ASP.NET Programmer Guide

,
Advantages of Web Farm

                  •It provides high availability. If any of the servers in the farm goes down, Load balancer can redirect the requests to other servers.
                  •Provides high performance response for client requests.
                  •Provides better scalability of the web application and reduces the failure of the application.
                  •Session and other resources can be stored in a centralized location to access by all the servers.

Advantages of Web Garden

                  •Provides better application availability by sharing requests between multiple worker process.
                  •Web garden uses processor affinity where application can be swapped out based on preference and tag setting.
                  •Less consumption of physical space for web garden configuration.
 

What is the difference between FirstOrDefault and SingleOrDefault inlinq? | Linq Interview Question | ASP.NET Programmer Guide

,

Single() / SingleOrDefault()
First () / FirstOrDefault()
Single() - There is exactly 1 result, an exception is thrown if no result is returned or more than one result. 
SingleOrDefault() – Same as Single(), but it can handle the null value.
First() - There is at least one result, an exception is thrown if no result is returned.
FirstOrDefault() - Same as First(), but not thrown any exception or return null when there is no result.
Single() asserts that one and only one element exists in the sequence.
First() simply gives you the first one.
When to use
Use Single / SingleOrDefault() when you sure there is only one record present in database or you can say if you querying on database with help of primary key of table.
When to use
Developer may use First () / FirstOrDefault() anywhere,  when they required single value from collection or database.
Single() or SingleOrDefault() will generate a regular TSQL like "SELECT ...".
The First() or FirstOrDefault() method will generate the TSQL statement like "SELECT TOP 1..."
In the case of First / FirstOrDefault, only one row is retrieved from the database so it performs slightly better than single / SingleOrDefault. such a small difference is hardly noticeable but when table contain large number of column and row, at this time performance is noticeable.

What is an Application Pool? | ASP.NET Interview Question | ASP.NET Programmer Guide

,
What is an Application Pool?

An Application Pool can contain one or more applications and allows us to configure a level of isolation between different Web applications. For example, if you want to isolate all the Web applications running in the same computer, you can do this by creating a separate application pool for every Web application and placing them in their corresponding application pool. Because each application pool runs in its own worker process, errors in one application pool will not affect the applications running in other application pools. Deploying applications in application pools is a primary advantage of running IIS 6.0 in worker process isolation mode because you can customize the application pools to achieve the degree of application isolation that you need.

When you configure application pools for optimum availability, you also should consider how to configure application pools for application security. For example, you might need to create separate application pools for applications that require a high level of security, while allowing applications that require a lower level of security to share the same application pool.
 

What is tuple in c#? | New features in C# 5.0 | ASP.NET C# Interview Question | ASP.NET Programmer Guide

, ,
Tuple

Tuples allow you to group related values without the need of a class. It’s more flexible than the KeyValuePair because it can store up to 8 values. A nice thing about Tuples is also the fact that they take on the aggregate equality of the values of the items they hold. Meaning that a Tuple<int, int> with values 1 and 2 equals any other Tuple<int, int> with 1 and 2 as values when you call Equals to compare them, plus they both return the same GetHashCode value.


Here’s a small example of how you can instantiate a Tuple using declarative notation and type inference:

// Create one using the constructor
var tupleOne = new Tuple<int, string, double>(3, "John", 2.13);

// Or using type inference
var tupleTwo = Tuple.Create(3, "John", 2.13);


If you’re thinking of using this for more than 3 items, consider using a class instead because you’re code will end up messy.

What is Named and Optional Arguments in C#? | New features in C# 5.0 | ASP.NET C# Interview Question | ASP.NET Programmer Guide

, ,
Named and Optional Arguments

Named and optional arguments allows a lot of calling options (with defaults) but without the need of littering your code with overloads. Named Parameters allow you to specify  your parameters in any order and omit any parameters with defaults as long as everything without a default value is specified.


Here’s an example of a method with named arguments:

public void ShowNamedArguments()
{
    ShowValue(message: "Hello");
    ShowValue(message: "Hello", newLine: false);
}

public void ShowValue(bool newLine = true, string message = "Default", string extraFooter = "")
{
    Debug.Write(message);
    if (newLine) Debug.Write(Environment.NewLine);
    if (!string.IsNullOrEmpty(extraFooter)) Debug.Write(extraFooter);
}
 

New features in C# 5.0 | What is Parallel.ForEach and the Task Parallel Library | ASP.NET C# Interview Question | ASP.NET Programmer Guide

,
Parallel.ForEach and the Task Parallel Library

The Task Parallel Library or TPL is a collection of classes designed to make multi-threading and parallel coding a lot easier and safer now that we have multi-core processors widely available.
One of the feature in the TPL is the Parallel.ForEach which will let you parallelize your loop if order of execution is not important. It will let you parallelize your work in no time without the need of starting up and handling threads on your own.


public void ParallelForEach()
{
    var testList = new List<string> { "One", "Two", "Three", "Four", "Five" };
    System.Threading.Tasks.Parallel.ForEach(testList, item => Console.WriteLine(item));
}

New features in C# 4.5 and C# 5.0 | ASP.NET C# Interview Question | C# Programmer Guide

,
BigInteger

The is a new DLL called System.Numerics that holds 2 public types. One of these types is the BigInteger struct. If you ever feel the need for some scientific programming you can resort to this struct. BigInteger is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds.


BigInteger bigIntFromDouble = new BigInteger(156487.4645);
Console.WriteLine(bigIntFromDouble);

BigInteger bigIntFromInt64 = new BigInteger(465789487421);
Console.WriteLine(bigIntFromInt64);

What is Routing in ASP.NET MVC? | ASP.NET MVC Interview Question | ASP.NET MVC Programmer Guide

, ,
In case of a typical ASP.NET application, incoming requests are mapped to physical files such as .aspx file. ASP.NET MVC framework uses friendly URLs that more easily describe user’s action but are not mapped to physical files.

ASP.NET MVC framework uses a routing engine, that maps URLs to controller classes. We can define routing rules for the engine, so that it can map incoming request URLs to appropriate controller.

Practically, when a user types a URL in a browser window for an ASP.NET MVC application and presses “go” button, routing engine uses routing rules that are defined in Global.asax file in order to parse the URL and find out the path of corresponding controller.

When to use IEnumerable, ICollection, IList and List? | Scenarions for IEnumerable, ICollection, IList and List | C# Interview Question | C# Programmer Guide

,
The below diagram clearly defines the difference between IEnumerable, ICollection, IList and List by listing the methods available in each of them.

Scenarions for IEnumerable, ICollection, IList

The following table provides various scenarios to use IEnumerable, ICollection, IList and List and it will help you to decide which type you should use.
InterfaceScenario
IEnumerable, IEnumerable<T>The only thing you want is to iterate over the elements in a collection. You only need read-only access to that collection.
ICollection, ICollection<T>You want to modify the collection or you care about its size.
IList, IList<T>You want to modify the collection and you care about the ordering and / or positioning of the elements in the collection.
List, List<T>Since in object oriented design you want to depend on abstractions instead of implementations, you should never have a member of your own implementations with the concrete type List/List.

How to avoid Sending Stack Trace of Unhandled Exception in ASP.NET Web API? | ASP.NET Web API Interview Question | ASP.NET Web API Programmer Guide

,
When an exception is thrown and it is not handled, ASP.NET Web API returns a 500 Internal Server Error. This response will have the stack trace details in the response body. However, sending a stack trace is a security risk.

ASP.NET Web API Stack Trace of unhandled exceptions can be avoided by specifying the Never option for the error details inclusion policy in WebApiConfig.cs under the App_Start folder, the stack trace can be stopped from getting to the client.

config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Never;

Brief about HTTP Transaction? | ASP.Net Web API Interview Question | ASP.Net Web API Programmer Guide

,

HTTP is an application layer protocol based on a reliable transport layer protocol (read TCP). The two endpoints of the communication based on HTTP are a server and a client. The client sends a request to the server; the server processes the request and sends a response back to the client that includes a status code denoting if the processing is successful or not. These steps constitute an HTTP transaction. The client typically is a web browser such as Internet Explorer, and the server is a web server such as IIS. A web server services multiple clients simultaneously. The HTTP client initiates an HTTP request by connecting to a port (typically 80) on the web server.
Web servers host resources that are uniquely identified through an identifier called the Uniform Resource Identifier (URI). The Uniform Resource Locator (URL) is a URI—it identifies a resource but it also specifies how a representation of a resource can be obtained. For example, http://www.server.com/home.html is a URL that includes three parts.
  1.  Scheme, which is http://. The scheme denotes the protocol used (HTTP).
  2. Server, which is www.server.com. The server is the server that hosts the resource.
  3. Resource path, which is /home.html. The resource path is the path of the resource on the server.


A client requests the server to take an action on a resource. There is a noun and a verb associated with the request. The noun is the resource identified by the URI. The verb is the action or the HTTP method. In the above figure, the client requests GET on /home.html. The server responds with a 200 OK status code and sends the text/html representation of the resource. The server specifies the representation (text/html) in the Content-Type response header. The content type is also called the media type.

How to Build a Service that Satisfies RESTful constraints using the ASP.NET Web API framework? | ASP.NET Web API Interview Question | ASP.NET Web API Programmer Guide

,
In my previous article, I have explained about the what is RESTful service and the constraints involved. Now let us see how the ASP.Net Web API satisfies those constraints.

Client-server constraint is an easy one to satisfy out of the box. ASP.NET Web API is all about responding to the client request with the data, without bothering about client state or how data will be presented to the end user.

Stateless constraint can also be easily satisfied out of the box, unless something horrible is done such as using the ASP.NET session state from the web API. ASP.NET MVC supports the OutputCache attribute that can be used to control output caching. ASP.NET Web API has no support out of the box, but it is easy to roll out our own action filter attribute. The bottom line is that the Cache-Control response header is the lever ASP.NET Web API can use to label a response as cacheable or not. By default, Cache-Control is set to no-cache and the response is not cached.

Layered constraint is more along the infrastructure line—proxies, firewalls, and so on. There is nothing special that needs to be done from ASP.NET Web API to satisfy this constraint.

Uniform interface constraint includes the following four constraints and is a key factor in deciding if an HTTP service is RESTful or not.

  1. Identification of resources
  2. Manipulation of resources through representations
  3. Self-descriptive messages
  4. Hypermedia as the engine of application state (HATEOAS) 

What Is a RESTful Service? | ASP.NET Web API Interview Question | RESTful Service Programmer Guide

,
Representational State Transfer (REST) is an architectural style. The term REST was introduced and defined by Roy T. Fielding in his doctoral dissertation in the year 2000. A service that conforms to the REST constraints is referred to as being RESTful. To be RESTful, a service has to conform to the following mandatory constraints.

  1. Client-server constraint, which is based on the separation of concerns, is about separating user interface concerns from data storage concerns. Clients are not concerned with data storage, which is a concern of servers, and servers are not concerned with the user interface or user state, which are concerns of clients.
  2. Stateless constraint is about each request being an independent self-contained unit with all the necessary information for the server to service the request without looking at anything else for the context.
  3. Cache constraint is about the server being able to label a response as cacheable or not,  so that the client handles the response appropriately from the point of view of later use.
  4. Layered constraint is about composing the system into layers, with each layer being  able to see and interact with only its immediate neighbor. A layer cannot see through  its neighbor. Between the client and server, there could be any number of  intermediaries—caches, tunnels, proxies, and so on.
  5. Uniform interface constraint is about providing a uniform interface for identification of resources, manipulation of resources through representations, self-descriptive messages, and hypermedia as the engine of application state.

Why Web API? | A Journey from Web Services (ASMX) to WCF to ASP.Net WebAPI | History of Internet Protocol | Origin of Internet

,
It all started with the launch of Sputnik in 1957, by the Union of Soviet Socialist Republics (USSR). The United States, under the leadership of then President Eisenhower, started the Advanced Research Projects Agency (ARPA) to advance the United States in the technology race, in the light of the Sputnik launch. One of the ARPA-funded projects was ARPANET, the world’s first operational packet switching network. ARPANET led to the development of protocols that allowed networks to be joined together into a network of networks that evolved into the ubiquitous Internet of today.

The terms Internet and World Wide Web or simply Web, are generally used interchangeably, but they are separate although related things. The Internet is the infrastructure on which the World Wide Web has been built. The Internet connects islands of smaller and bigger networks into one huge network. 

The World Wide Web builds on this network by providing a model to share data or information with the computer users who are all part of the Internet. Servers or web servers serve data in the form of documents or web pages to the clients, called web browsers, which display the documents in a format readable by human beings. Typically, a web page is created in a language called Hyper Text Markup Language (HTML) and is served to a browser by the web server as a result of both parties following a protocol, Hyper Text Transfer Protocol (HTTP). The Web is just one of the ways information can be shared over the Internet. Just like HTTP, there is Simple Mail Transfer Protocol (SMTP) for e-mail, File Transfer Protocol (FTP) for transfer of information in the form of files, and so on. 

Initially, web pages were just static pages existing in the file system of some computer with data that hardly changed. As the World Wide Web started to grow and the user base started to expand, there was a need for web pages to be generated on the fly. Web servers started delegating this responsibility to engines such as the Common Gateway Interface (CGI) to generate web pages on the fly. The dynamic web pages and the introduction of the client-side JavaScript scripting language led to a new generation of software applications called web applications. The end user of a web application is a human being with an objective of performing a task.

Because the end user of a web application is a human being, there is a user interface associated with a web application. The browser is what provides this interactive interface for a user. In addition, there is a need for nonhuman entities such as a machine running some software to communicate and exchange data over the World Wide Web. Enter the web service. Although not mandated, a web service uses HTTP to exchange data. Unlike a web application, which is mainly about HTML over HTTP, for a web service it is mainly Extensible Markup Language (XML) over HTTP. A client sends a request in XML, and the server responds with an XML response. This XML can be Plain Old XML (POX), which is typically a nonstandard XML only the client and server will be able to make sense out of, or it can be standard Simple Object Access Protocol (SOAP). 

To appreciate the value SOAP brings to the table, let us pretend we got some XML response representing an employer in an organization, as shown in below response XML:

<employee>         <firstname>John</firstname>         <lasttname>Human</lastname>         <salary>2000</salary>         <doj>06/01/1998<doj>         <lastlogin>10/20/2012 09:30:00</lastlogin>
</employee>

To do anything useful with this in our application, this XML might need to be loaded into some data structure, say an object as defined by a class in the case of an object-oriented programming (OOP) language. If I’m programming, how will I define the data type of the field to store salary? Will it be an integer or a fractional number? What if my request to get the employee fails because there is no such employee or there is some other problem? How will I know where to look in the XML if the request has failed? SOAP helps us with questions like these by providing a basic messaging framework on which web services can be built. SOAP has Microsoft roots, although it is currently maintained by the World Wide Web Consortium (W3C).

Microsoft technologies such as the ASMX-based web service, which is currently a legacy technology, and its successor Windows Communication Foundation (WCF) all have great affinity toward SOAP. An ASMX-based web service allows the exchange of SOAP messages over HTTP and that’s pretty much it. WCF builds on this and tries to abstract away the infrastructure from the programming. If I have an Employee service that returns the details of an employee, I can host the service to be consumed over HTTP, over Transmission Control Protocol (TCP), through Microsoft Message Queuing (MSMQ), or any combinations thereof. By having the same contract with the client, I can have multiple binding for multiple ways my service can be reached. In both cases, though, the payload will be SOAP, by default. An important aspect of SOAP-based web services is the availability of a Web Service Definition Language (WSDL) file, which allows tooling to be built that helps in consumption of services. For example, Microsoft Visual Studio can generate proxy classes reading WSDL definitions, and the client trying to consume the services (i.e., the programmer writing the client code) can directly work with the generated classes, with the whole existence of the web service hidden from the programmer.

A web API is a service. Technically, there is no difference. What is different is the manner in which a web API is intended to be used. Let’s say I have a web application where a user can post his thoughts in the form of a short message. A user can log in to my application from a browser, add new posts or update the ones she posted in the recent past, or even delete the old ones. In other words, users can perform create, read, update, and delete (CRUD) operations on their posts using my web application. My application became so popular that there are folks who want to integrate this CRUD functionality into their mobile apps so that users can perform CRUD operations from their mobile devices without logging on to my web application while they are away from their normal computers.

I can now create a web service to support the CRUD operations. Technically it is a web service, but it is an application programming interface (API) to interact with my web application, except that it is over the Web. Traditionally, APIs are a bunch of classes with properties and methods that are part of a reusable component to interact with another application. This scenario is exactly that, except that my API is not available in the form of a software component, but over the Web instead. It is a web API.

Although it is fundamentally a web service, the intention is to use it to manipulate application data, and that is what makes it an API. One important characteristic of most of the typical web APIs in use, although not a defining characteristic, is that web APIs tend to be RESTful web services as compared with SOAP-based web services. A web service can very well be REST based, so this is not the defining characteristic. By using REST, a web API tends to be lightweight and embraces HTTP. For example, a web API leverages HTTP methods to present the actions a user would like to perform and the application entities would become resources these HTTP methods can act on. Although SOAP is not used, messages—requests and responses—are either in XML or JavaScript Object Notation (JSON).

Why Token Based Authentication? | Authentication Programmer Guide

Token based approach to implement authentication between the front-end application and the back-end API, as we all know the common and old way to implement authentication is the cookie-based approach were the cookie is sent with each request from the client to the server, and on the server it is used to identify the authenticated user.
With the evolution of front-end frameworks and the huge change on how we build web applications nowadays the preferred approach to authenticate users is to use signed token as this token sent to the server with each request, some of the benefits for using this approach are:
  • Scalability of Servers: The token sent to the server is self contained which holds all the user information needed for authentication, so adding more servers to your web farm is an easy task, there is no dependent on shared session stores.
  • Loosely Coupling: Your front-end application is not coupled with specific authentication mechanism, the token is generated from the server and your API is built in a way to understand this token and do the authentication.
  • Mobile Friendly: Cookies and browsers like each other, but storing cookies on native platforms (Android, iOS, Windows Phone) is not a trivial task, having standard way to authenticate users will simplify our life if we decided to consume the back-end API from native applications.

Types of Web API Action Return Types | Return Types in Web API Action | ASP.NET Web API Interview Question | ASP.NET Web API Programmer Guide

,
Web API supports three types of possible action return values (well, four, if you count void):
  • – HttpResponseMessage
  • – IHttpActionResult
  • – any other type, subject to content negotiation

What are the core security concepts supported by WCF? | WCF Interview Question

,
There are four core security Features
Confidentiality: It’s a confirmation about the recipient. Only the valid recipient can read the message when it passed between service and client.
Integrity: is to ensure that message received is not being tempered or changed during exchange.
Authentication: is a way for the parties (sender and receiver) to identify each other.
Authorization: ensures that what actions an authenticated user can perform?

What is a fault contract in WCF? | WCF Interview Question

, ,
Normally, by default, when some exception occurs at a WCF service level, it will not expose as it is to client. Reason is that WCF exception is a CLR exception and it doesn’t make sense to expose it outside CLR because it contains internal details of service code like stack trace. So, WCF handles and returns error details to client using Fault Contract.“So, fault contract is a contract that contains the details of possible exception(s) that might occur in a service code.”
 [ServiceContract]
 public interface IService1
 {
        [OperationContract]
        [FaultContract(typeof(MyFaultDetails))]
        int MyOperation1();
 }
 [DataContract]
  public class MyFaultDetails
  {
        [DataMember]
        public string ErrorDetails { get; set; }
  }
In implementing service…..
  public int MyOperation1()
  {
       Try{               //Do something……       }catch()
       {
                  MyFaultDetails ex = new MyFaultDetails();
                  ex.ErrorDetails = “Specific error details here.“;
                  throw new FaultException(ex,“Reason: Testing…..“);
       }
  }