HI WELCOME TO Sirees

asp.net interview questions part1

Leave a Comment
What are the different environments in your development process or development life cycle at your company?
This is a general interview question and not very specific to ASP.NET. Usually, the interviewer asks this question to measure your understanding of the different environments and their role in software development. Some interviewers, may also ask this question, to check if you really have the work experience you are claiming or just faking it.
 



1. Development
2. QA
3. Staging
4. UAT (User Acceptance Testing)
5. Production

1. Development Environment - All the developers check in their current work into development environment.

2. QA (Quality Assurance) Environment - This is the environment, where testers (QA) test the application. QA cannot test on development environment, because developers are continuously checking in new code. So, if there is a bug, we don't know, if it's caused by the old or new code. In short,  if development is going on in the same environment it would be difficult to keep up with the current state. There will be lot of confusion, if the developer is trying to fix in the same area as the tester is testing. Without development and QA environment being seperate their is no way to do proper testing.

3. Staging Environment - Many organisations, try to keep their staging environment as identical as possible to the actual production environment. The primary reason for this environment is to identify any deployment related issues. Also, if you are developing a B2B (Business to Business) application, you may be interfacing with other service provider systems. Many organisations, usually setup their staging environment to interface with the service providers as well, for complete end to end testing.

4. Production Environment - The actual live environment, that we use for day to day business. 

Note: In general, the code flows from Development => QA => Staging => Production


Difference between EnableViewState and ViewStateMode properties



1. Using EnableViewState property we only have 2 options
     We can turn off view state altogether,
                              or
     Enable viewstate for the entire page and then turn it off on a control-by-control basis.

2. If you want to turn of ViewState for the entire page and only enable it for specific controls on the page, then we have to use ViewStateModeproperty in conjunction with EnableViewState.

3. EnableViewState property only accepts true or false values and the default value is true, where as ViewStateMode property can have a value of - Enabled, Disabled and inherit. Inherit is the default value for ViewStateMode property.

4. ViewStateMode property is introduced in ASP.NET 4, where as EnableViewState exists from a long time.

5. If EnableViewState is to True, only then the ViewStateMode settings are applied, where as, if EnableViewState is set to False then the control will not save its view state, regardless of the ViewStateMode setting. In short if EnableViewState is set to False, ViewStateMode setting is not respected.

6. To disable view state for a page and to enable it for a specific control on the page, set the EnableViewState property of the page and the control to true, set the ViewStateMode property of the page to Disabled, and set the ViewStateMode property of the control to Enabled.

ASP.NET Page is very slow. What will you do to make it fast


This is a very common asp.net interview question asked in many interviews. There are several reasons for the page being slow. We need to identify the cause. 

1. Find out which is slow, is it the application or the database : If the page is executing SQL queries or stored procedures, run those on the database and check how long do they take to run. If the queries are taking most of the time, then you know you have to tune the queries for better performance. To tune the queries, there are several ways and I have listed some of them below.
   a) Check if there are indexes to help the query
   b) Select only the required columns, avoid Select *.
   c) Check if there is a possiblity to reduce the number of joins
   d) If possible use NO LOCK on your select statements
   e) Check if there are cursors and if you can replace them with joins

2. If the queries are running fast, then we know it is the application code that is causing the slowness. Isolate the page event that is causing the issue by turning tracing on. To turn tracing on, set Trace="true" in the page directive. Once you have tracing turned on you should see trace information at the bottom of the page as shown in the image below. In this case Page Load event is taking the maximum time. So we know, the code in Page_Load event is causing the issue. Once you look at the code, you should be able to nail down the issue.




When I create a new ASP.NET 4 web application, the web.config file is almost empty. What happened to all the configuration elements that were there prior to ASP.NET 4?



All the major configuration settings are moved into machine.config file, and all the applications will inherit the setting from this file. If an application needs to override the default settings, we can do so using the application specific configuration (web.config) file. ASP.NET 4 applications have clean web.config files.

If you create a new asp.net 4 empty web application, the only entry that you will find is shown below.


Note: If you create a new ASP.NET Web Application, instead of a new ASP.NET Empty Web Application, you will find a lot more confiuration entries in the web.config file. This is because, the template for ASP.NET web application overrides some of the default settings inherited from machine.config.

Explain Dependency Injection with an example

One of the very common interview questions, asked these days. This is the most common approach used today to solve dependencies between objects. In many of the enterprise class ASP.NET application, Dependency Injection is a common standard to follow. Let us understand Dependency Injection with an example.


In the example above, Employee class depends on EmployeeDAL class to get the data from the database. In GetAllEmployees() method of theEmployee class, we create an instance of the EmployeeDAL (Employee Data Access Layer) class and then invoke SelectAllEmployees() method. This is tight coupling, EmployeeDAL is tightly copuled with the Employee class. Everytime the EmployeeDAL class changes, the Employee class also needs to change. EmployeeDAL cannot be mocked and hence unit testing becomes cumbersome and time consuming. 

The same example can be re-written using dependency injection as shown below. First thing to notice is that, we are using interface types instead of concrete types. Using interfaces help us to plugin any implemenation of the interface, with less or no code modification at all. We are not creating the instance of the EmployeeDAL in the Employee class, instead we are passing it as a parameter to the constructor of the Employee class. As, we are injecting an instance of a class into a class that depends on it, we can call this process as Dependency Injection.


Dependency Injection is of 2 types.
1. Constructor Injection
2. Setter Injection.

We have already seen how to use Constructor Injection in the example above. An, example for Setter Injection is shown below. We are injecting an object instance through the Setter property, instead of a constructor. Hence, we call Setter Injection. It is very important to use the propertyEmployeeDataObject to access the instance of IEmployeeDAL, rather than the private variable employeeDAL. The property checks to see ifemployeeDAL is null, and throws the exception accordingly.



What is SQL Injection Attack

Let us understand SQL injection attack, with an example. I have an Employee Search Page as shown in the image below. This webform has a very simple functionality. You enter the ID of the employee, you want to search and click the Search Employee button. If a match is found in the database, we show the employee record in the GridView.

Employee Search Page
The HTML for the Employee Serach Page is shown below. As you can see from the HTML, the Employee Serach Page contains TextBox, Button and a GridView control.

Employee Search Page HTML


The codebehind page for the EmployeeSearchPage is shown below. 

Employee Search Page Code Behind

The Button1_Click event handler has the required ADO.NET code to get data from the database. This code is highly susceptible to sql injection attack and I will never ever have code like this in production environment. The second line in Button1_Click event handler, dynamically builds the sql query by concatenating the Employee ID that we typed into the TextBox


So, for example, if we had typed 2 into the Employee ID textbox, we will have a SQL query as shown below.
Select * from Employees where Id=2

If a malicious user, types something like 2; Delete from Employees into the TextBox, then we will have a SQL query as shown below.
Select * from Employees where Id=2; Delete from Employees

When this query is executed, we loose all the data in the Employees table. This is SQL Injection Attack, as the user of the application is able to inject SQL and get it executed against the database. It is very easy to avoid SQL Injection attacks by using either parameterized queries or usingstored procedures.

You may be thinking, how will the user of the application know the name of the table. Well, one way is to simply guess or inject a sql syntax error. The injected SQL syntax error causes the page to crash and can possibly reveal the name of the table as shown below. However, proper exception handling and custom error pages can be used to prevent the end user from seeing the yello screen of death. The screen shot below shows the table name Employees.

Page crash revealing Employees table name

To solve SQL injection attack, create a Stored Procedure as shown below. 

Create Procedure spGetEmployees
@Id int
as
Begin
Select * from Employees where Id=@Id
End

Modify the codebehind page for the EmployeeSearchPage, to use the stored procedure as shown below


using System;
using System.Data;
using System.Data.SqlClient;

namespace TestWeb
{
    public partial class EmployeeSearch : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            // Create the SQL Connection object. 
            SqlConnection con = new SqlConnection
            ("server=localhost; database=TestDB; integrated security=SSPI");

            // Create the SQL command object. Pass the stored procedure name 
            // as a parameter to the constructor of the SQL command class
            SqlCommand cmd = new SqlCommand("spGetEmployees", con);
            // Create the SQL parameter object, specifying the name and the value 
            // we want to pass to the SP.
            SqlParameter paramId = new SqlParameter("@Id", txtEmployeeId.Text);
            // Associate the Id parameter object with the command object, using
            // parameters collection property 
of the SQL Command object. 

            cmd.Parameters.Add(paramId);
            // Specify the command type as stored procedure. This tells the command
            // object, that the command 
is a SQL stored procedure and not an adhoc sql query
            cmd.CommandType = CommandType.StoredProcedure;
            // Open the connection
            con.Open();
            // Execute the command and assign the returned results as the data source for 
            // the employyes girdview
            gvEmployees.DataSource = cmd.ExecuteReader();
            // Call the DataBind() method, to bind the results to the employees grid view control
            gvEmployees.DataBind();
            // Finally close the sql server connection object
            con.Close();
        }
    }
}

Difference between EnableViewState and ViewStateMode properties



1. Using EnableViewState property we only have 2 options
     We can turn off view state altogether,
                              or
     Enable viewstate for the entire page and then turn it off on a control-by-control basis.

2. If you want to turn of ViewState for the entire page and only enable it for specific controls on the page, then we have to use ViewStateModeproperty in conjunction with EnableViewState.

3. EnableViewState property only accepts true or false values and the default value is true, where as ViewStateMode property can have a value of - Enabled, Disabled and inherit. Inherit is the default value for ViewStateMode property.

4. ViewStateMode property is introduced in ASP.NET 4, where as EnableViewState exists from a long time.

5. If EnableViewState is to True, only then the ViewStateMode settings are applied, where as, if EnableViewState is set to False then the control will not save its view state, regardless of the ViewStateMode setting. In short if EnableViewState is set to False, ViewStateMode setting is not respected.

6. To disable view state for a page and to enable it for a specific control on the page, set the EnableViewState property of the page and the control to true, set the ViewStateMode property of the page to Disabled, and set the ViewStateMode property of the control to Enabled.

ASP.NET Page is very slow. What will you do to make it fast


This is a very common asp.net interview question asked in many interviews. There are several reasons for the page being slow. We need to identify the cause. 

1. Find out which is slow, is it the application or the database : If the page is executing SQL queries or stored procedures, run those on the database and check how long do they take to run. If the queries are taking most of the time, then you know you have to tune the queries for better performance. To tune the queries, there are several ways and I have listed some of them below.
   a) Check if there are indexes to help the query
   b) Select only the required columns, avoid Select *.
   c) Check if there is a possiblity to reduce the number of joins
   d) If possible use NO LOCK on your select statements
   e) Check if there are cursors and if you can replace them with joins

2. If the queries are running fast, then we know it is the application code that is causing the slowness. Isolate the page event that is causing the issue by turning tracing on. To turn tracing on, set Trace="true" in the page directive. Once you have tracing turned on you should see trace information at the bottom of the page as shown in the image below. In this case Page Load event is taking the maximum time. So we know, the code in Page_Load event is causing the issue. Once you look at the code, you should be able to nail down the issue.




Interview Questions related to Dependency Injection


When do you use Setter Injection over Constructor Injection and vice versa ?
Constructor Injection is normally the standard for dependency injection. Constructor Injection, ensures that all the dependency objects are initialized before we attempt to invoke any methods or peroperties, thus avoiding null reference exceptions. 

Setter Injection is used rarely in exceptional cases. For example, if I have a class that has several methods which does not depend on any other objects, and now I need to introduce a new method with in this class, which depends on another object. We can use, constructor injection here, but we need to change the exisitng constructor calls at all the other places. This can become cumbersome, especially if the project is a huge one. Hence, Setter Injection could be a choice when we want to change the legacy code. 

Setter Injection, enables you to inject the object, just before you need it. So, if the object is an expensive object to create, and you want to create it as late as possible, then setter injection is your choice.

What are the advantages of using Dependency Injection?
1. Dependency Injection allows us to develop very loosely coupled systems.

2. Easy to swap in a different implementation of a component, as long as the component implements the interface type.

3. Dependency Injection, allows objects to be mocked with in the Unit Tests. This is the greatest advantage of Dependency Injection.

What Dependency Injection Container have you used in your project?
There are lot of Dependency Injection Containers available in the market. I have included, the very commonly used list of Dependency Injection Containers for your quick refernce.
1. Unity
2. Castle Windsor 
3. StructureMap 
4. Spring.NET 

I have used Unity in most of my projects.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.