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 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);
}
 

Building a Single Page Application with ASP.NET and AngularJS | ASP.NET Video Tutorial | AngularJS Video Tutorial

,
In this video tutorial, we’ll see how to power an AngularJS Single Page Application using both ASP.NET Web API and SignalR for back-end data services. From this video tutorial, you’ll learn how to get started building web applications with AngularJS, how to leverage HTML5 features like local storage and pushState, providing efficient server resources via HTTP and web sockets (using SignalR), important routing configuration concerns, testing and deployment.

Scenario Of Using Caching In An ASP.NET Or ASP.NET MVC Application | AppFabric Tutorial | AppFabric Reference Guide

,
ASP.NET applications are among the most important clients for AppFabric Caching Services. As just described, the data stored in an ASP.NET Session object is an obvious candidate for caching. In fact, the service provides built-in support for this—the developer just sets a configuration option, and the Session object will be transparently stored in the cache cluster. Notice what this means: ASP.NET developers can get the benefits of caching without changing any of their code. This allows using replicated Web servers, each running an instance of the same ASP.NET application, without either storing session state in SQL Server or requiring sticky sessions. Below figure shows how this looks.


Figure: An ASP.NET application can use AppFabric Caching Services to store Session object data.

This simple scenario begins with the user supplying some information that the ASP.NET application stores in the Session object for this user (step 1). The Web server that handles this request has been configured to cache Session objects in an AppFabric Caching Services cluster, and so the user’s data is written to one or more cache servers (step 2). The next request from this user relies on the data supplied in step 1, but it’s handled by a different Web server (step 3). The ASP.NET code on this Web server refers to the same Session object, which transparently accesses the cache cluster to retrieve the data (step 4). This makes the information provided in step 1 available to the application once again. Notice that there’s no need to access the application database here, since the Session object wasn’t stored there, nor must the user access the same Web server instance for each request. The result is an ASP.NET application with better performance and improved scalability.

Main Components Of AppFabric Caching Services | AppFabric Tutorial | AppFabric Reference Guide

,
The main components of AppFabric Caching Services are a cache client, such as an ASP.NET page, that accesses a cache cluster containing some number of cache server machines. Each cache server runs an instance of AppFabric Caching Services, and each maintains some cached data. Each cache client can also maintain its own local cache, using software provided as part of AppFabric Caching Services. Figure 1 illustrates these components.


Figure: AppFabric Caching Services speeds up access to frequently accessed data.

When the cache client first acquires some item of data, such as information supplied by the user of an ASP.NET application or values read from a database, it can use an AppFabric Caching Services client library to explicitly store this information in the cache cluster under a unique name. (As described later, ASP.NET applications can also do this transparently through the Session object, so using caching needn’t require any code changes.) To the client, all of the cache servers in the cluster appear as a single logical store—the client neither knows nor cares which physical server winds up holding the cached data. If it chooses to, the client can also store the data item in its own local cache.

When the client needs to access the same data item again, it asks for it using the item’s name. This query first checks the local cache (if one is being used). If the item is found, the client uses this cached value. If the data item isn’t in the local cache, the query is then sent to the cache cluster. If the item is found here, the client uses the value returned from the cluster. All of this is transparent to the client—it just requests the item, and AppFabric Caching Services takes care of the rest. If the item isn’t found in either the local cache or the cache cluster, the client needs to look elsewhere for the information, such as in the application database.

AppFabric Caching Services was originally code-named “Velocity”, a name that suggests exactly what the technology does: It makes repeated access to the same data faster. Rather than forcing an application to make repetitive calls to the database, it instead allows access to data directly from memory, either locally or on one of the cache servers. For applications that frequently access the same data—a large category—caching improves both performance and scalability.

AppFabric Caching Services are designed to be used by .NET applications, and so a cached data item can be any serialized .NET object. Once an object is in the cache, applications can update this cached version or explicitly delete it. Cached data items are also removed by the caching service itself, either through expiration of a configurable time-out period or by being evicted to make room for more frequently accessed information. Data items in the local cache can expire as well, and they can also be set to synchronize automatically with any changes made to the same item in the cache cluster.

Multiple cache clients can share the same cache cluster. This makes sense, since a scalable application will likely replicate its business logic (such as ASP.NET pages) across multiple machines, each of which needs to access the cache. It also raises security issues, however. To make this sharing less risky, all data sent between cache clients and cache servers can be digitally signed and encrypted, and an administrator can limit which accounts have access to each cache. Still, an organization must make sure that all clients using the same cache are trusted, since they can potentially access each other’s data.

Caching is useful with various kinds of data. For example, caching makes good sense for unchanging data that’s accessed simultaneously by multiple clients, such as catalog information for an online retailer. Another good use of caching is to store data that changes but is accessed by only one client at a time, such as the information in an ASP.NET Session object. Once again, the problem of controlling concurrent access to the cached data doesn’t arise.

But what about data that both changes and is accessed simultaneously by multiple clients? Caching can be used here as well, but life gets a little more complicated: Concurrency control is required. To address this situation, AppFabric Caching Services provides both optimistic concurrency control, based on a version number assigned to each cached object, and pessimistic concurrency control, relying on explicit locks.

Features Of ASP.NET Identity System | ASP.NET Tips And Tricks

,
ASP.NET Identity is the new membership system for building ASP.NET web applications. ASP.NET Identity allows you to add login features to your application and makes it easy to customize data about the logged in user.

Following are some of the feature of the ASP.NET Identity system
  • One ASP.NET Identity system
    • ASP.NET Identity can be used with all of the ASP.NET frameworks such as ASP.NET MVC, Web Forms, Web Pages, Web API and SignalR
  • Ease of plugging in profile data about the user
    • When you create new users in your application, it is now easy to add extra information about the user. For eg.. if you wanted to add a Birthdate option for users when they Register an account in your application.
    • ASP.NET Identity uses Entity Framework Code First and it is possible to extend the POCO classes.
  • Persistence control
    • By default the ASP.NET Identity system will store all the user information in a database. ASP.NET Identity uses Entity Framework Code First to implement all of its persistence mechanism.
    • If your application requirements are that this information might be stored in a different storage mechanism such as SharePoint, Azure Table Service, No Sql databases etc. it is now possible to plug in different storage providers.
  • Unit testability
    • ASP.NET Identity makes the web application more unit testable. You can write Unit Tests for the parts of your application that use ASP.NET Identity
  • Simple Role provider
    • There is a Simple Role providers which lets you restrict access to parts of your application by Roles. You can easily create Roles such as “Admin” and add Users to Roles.
  • Claims Based
    • ASP.NET Identity supports claims-based authentication, where the user’s identity is represented as a set of claims. There is a Claims
  • External Logins 
    • You can easily add external logins such as Microsoft Account, Facebook, Twitter and Google to your application store the user specific data in your application using this system.
    • You can also add login functionality using Windows Azure Active Directory and store the user specific data in your application using this system.

Using Media-Type Formatters in ASP.NET Web API | Web API Tutorial

, ,
media-type formatter is an object that serializes your data when Web API writes the HTTP response body. The built-in formatters support JSON and XML output. By default, both of these formatters serialize all objects by value.


This guide shows how to support additional media formats in ASP.NET Web API.

Getting Started with One ASP.NET Project | Visual Studio 2013 | ASP.NET Tutorial

With One ASP.NET, now developer can add MVC and/or Web API controller in Web Form application or vice-versa. This newer version of ASP.NET also include an update to ASP.NET MVC 5, Razor 3, ASP.NET Web API 2, Entity Framework 6 and SignalR 2. Here in this quick post, we will see how to configure project and theme with One ASP.NET.

Basic Http Authorization for Web API in ASP.NET MVC 4 | Web API Tutorial

,
The below code snippet demonstrates the Custom Authentication Attribute for Web API. Let's create a custom attribute BasicHttpAuthorizeAttribute inheriting the AuthorizeAttribute.

This custom attribute can be used in Web API as below:


public class OrderController : ApiController
{
    // GET /api/orders/5
    [BasicHttpAuthorizeAttribute(RequireAuthentication = true)]
    public string Get(int id, string communicationLang)
    {
        //do your API Stuff
    }
}
The code for custom attribute used in Web API is given below:
public class BasicHttpAuthorizeAttribute : System.Web.Http.AuthorizeAttribute  
{
    bool requireSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["RequireSsl"]);
 
    public bool RequireSsl
    {
        get { return requireSsl; }
        set { requireSsl = value; }
    }
 
 
    bool requireAuthentication = true;
 
    public bool RequireAuthentication
    {
        get { return requireAuthentication; }
        set { requireAuthentication = value; }
    }
 
 
    /// <summary>
    /// For logging with Log4net.
    /// </summary>
    private static readonly ILog log = LogManager.GetLogger(typeof(BasicHttpAuthorizeAttribute));
 
 
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)        
    {
        //actionContext.Request
 
        if (Authenticate(actionContext) || !RequireAuthentication)
        {
            return;
        }
        else
        {
            HandleUnauthorizedRequest(actionContext);
        }
    }
 
    protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        var challengeMessage = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
        challengeMessage.Headers.Add("WWW-Authenticate", "Basic");
        throw new HttpResponseException(challengeMessage);
        //throw new HttpResponseException();
    }
 
 
    private bool Authenticate(System.Web.Http.Controllers.HttpActionContext actionContext) //HttpRequestMessage input)
    {
        if (RequireSsl && !HttpContext.Current.Request.IsSecureConnection && !HttpContext.Current.Request.IsLocal)
        {
            log.Error("Failed to login: SSL:" + HttpContext.Current.Request.IsSecureConnection);
            return false;
        }
 
        if (!HttpContext.Current.Request.Headers.AllKeys.Contains("Authorization")) return false;
 
        string authHeader = HttpContext.Current.Request.Headers["Authorization"];
 
        IPrincipal principal;
        if (TryGetPrincipal(authHeader, out principal))
        {
            HttpContext.Current.User = principal;
            return true;
        }
        return false;
    }
 
 
    private bool TryGetPrincipal(string authHeader, out IPrincipal principal)
    {
        var creds = ParseAuthHeader(authHeader);
        if (creds != null)
        {
            if (TryGetPrincipal(creds[0], creds[1], out principal)) return true;
        }
 
        principal = null;
        return false;
    }
 
 
    private string[] ParseAuthHeader(string authHeader)
    {
        // Check this is a Basic Auth header 
        if (authHeader == null || authHeader.Length == 0 || !authHeader.StartsWith("Basic")) return null;
 
        // Pull out the Credentials with are seperated by ':' and Base64 encoded 
        string base64Credentials = authHeader.Substring(6);
        string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(base64Credentials)).Split(new char[] { ':' });
 
        if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[0])) return null;
 
        // Okay this is the credentials 
        return credentials;
    }
 
 
    private bool TryGetPrincipal(string username, string password, out IPrincipal principal)
    {
        // this is the method that does the authentication 
 
        //users often add a copy/paste space at the end of the username
        username = username.Trim();
        password = password.Trim();
 
        //TODO
        //Replace this with your own Authentication Code
        Person person = AccountManagement.ApiLogin(username, password);
 
        if (person != null)
        {
            // once the user is verified, assign it to an IPrincipal with the identity name and applicable roles
            principal = new GenericPrincipal(new GenericIdentity(username), System.Web.Security.Roles.GetRolesForUser(username));
            return true;
        }
        else
        {
            if (!String.IsNullOrWhiteSpace(username))
            {
                log.Error("Failed to login: username=" + username + "; password=" + password);
            }
            principal = null;
            return false;
        }
    }
}
The private method TryGetPrincipal() should be altered as per your system requirement for authorizing a Web AP. Otherwise Plain ASP.NET provider Authentication may be sufficient.

Creating A SignalR Application Using Visual Studio 2013 | SignalR ASP.NET Application


The tutorial demonstrates the following SignalR development tasks:
  • Adding the SignalR library to an ASP.NET web application.
  • Creating a hub class to push content to clients.
  • Creating an OWIN startup class to configure the application.
  • Using the SignalR jQuery library in a web page to send messages and display updates from the hub.

Avoiding Fallback Loading Script From CDN

,
You can use jQuery scripts hosted on CDN in your Web application by adding the following script element to a page: 

    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>                        


To allow your page to fallback to loading jQuery from a local path on your own website if the CDN happens to be unavailable, add the following element immediately after the element referencing the CDN:

    <script>
        // Fallback to loading jQuery from a local path if the CDN is unavailable
        (window.jQuery || document.write('<script src="/scripts/jquery-1.9.0.min.js"><\/script>'));
    </script>

Step By Step ASP.NET Identity Implementation Guide


ASP.NET Identity is used in the Visual Studio 2013 project templates for ASP.NET MVC, Web Forms, Web API and SPA. In this walkthrough, we’ll illustrate how the project templates use ASP.NET Identity to add functionality to register, log in and log out a user.

ASP.NET Identity is implemented using the following procedure. The purpose of this article is to give you a high level overview of ASP.NET Identity; you can follow it step by step or just read the details. For more detailed instructions on creating apps using ASP.NET Identity, including using the new API to add users, roles and profile information, see the Next Steps section at the end of this article.
  1. Create an ASP.NET MVC application with Individual Accounts. You can use ASP.NET Identity in ASP.NET MVC, Web Forms, Web API, SignalR etc. In this article we will start with an ASP.NET MVC application.

  2. The created project contains the following three packages for ASP.NET Identity.
    • Microsoft.AspNet.Identity.EntityFramework
      This package has the Entity Framework implementation of ASP.NET Identity which will persist the ASP.NET Identity data and schema to SQL Server.
    • Microsoft.AspNet.Identity.Core 
      This package has the core interfaces for ASP.NET Identity. This package can be used to write an implementation for ASP.NET Identity that targets different persistence stores such as Azure Table Storage, NoSQL databases etc.
    • Microsoft.AspNet.Identity.OWIN
      This package contains functionality that is used to plug in OWIN authentication with ASP.NET Identity in ASP.NET applications. This is used when you add log in functionality to your application and call into OWIN Cookie Authentication middleware to generate a cookie.
  3. Creating a user.
    Launch the application and then click on the Register link to create a user. The following image shows the Register page which collects the user name and password.



    When the user clicks the Register button, the  Register action of the Account controller creates the user by calling the ASP.NET Identity API, as highlighted below:
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { UserName = model.UserName };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInAsync(user, isPersistent: false);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }
    
        // If we got this far, something failed, redisplay form
        return View(model);
    }
  4. Log in.
    If the user was successfully created, she is logged in by the SignInAsync method.
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { UserName = model.UserName };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInAsync(user, isPersistent: false);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }
    
        // If we got this far, something failed, redisplay form
        return View(model);
    } 
    private async Task SignInAsync(ApplicationUser user, bool isPersistent)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    
        var identity = await UserManager.CreateIdentityAsync(
           user, DefaultAuthenticationTypes.ApplicationCookie);
    
        AuthenticationManager.SignIn(
           new AuthenticationProperties() { 
              IsPersistent = isPersistent 
           }, identity);
    }
    The highlighted code above in the SignInAsync method  generates a ClaimsIdentity. Since ASP.NET Identity and OWIN Cookie Authentication are claims-based system, the framework requires the app to generate a ClaimsIdentity for the user. ClaimsIdentity has information about all the claims for the user, such as what roles the user belongs to. You can also add more claims for the user at this stage.

    The highlighted code below in the SignInAsync method signs in the user by using the AuthenticationManager from OWIN and calling SignIn and passing in the ClaimsIdentity.
    private async Task SignInAsync(ApplicationUser user, bool isPersistent)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    
        var identity = await UserManager.CreateIdentityAsync(
           user, DefaultAuthenticationTypes.ApplicationCookie);
    
        AuthenticationManager.SignIn(
           new AuthenticationProperties() { 
              IsPersistent = isPersistent 
           }, identity);
    }
  5. Log off.
    Clicking the Log off link calls the LogOff action in the account controller.
    // POST: /Account/LogOff
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff()
    {
        AuthenticationManager.SignOut();
        return RedirectToAction("Index", "Home");
    }
    The highlighted code above shows the OWIN AuthenticationManager.SignOut method. This is analogous to FormsAuthentication.SignOut method used by the FormsAuthentication module in Web Forms.

Components of ASP.NET Identity

The diagram below shows the components of the ASP.NET Identity system (click on this or on the diagram to enlarge it). The packages in green make up the ASP.NET Identity system. All the other packages are dependencies which are needed to use the ASP.NET Identity system in ASP.NET applications.