Tuesday, 21 January 2014

What is SQL Injection Attack


                                                                                                                                         Previous.....
                                                                                                                                                      Next.....

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


Here is a youtube video that I have recorded on SQL Injection. Hope, you will find it useful.





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

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.

You can also see this link for SQL injection.. http://venkataspinterview.blogspot.in/2011/07/what-is-sql-injection-attack.html

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?

                                                                                                                                        Previous....
                                                                                                                                                     Next.....



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.



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


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.


These are the different types of extensions in Dot Net Files 
.
» .aspx- Web Form 
» .master - Master Page 
» .ascx - WebUserControl 
» .edmx - Ado Entity data Model
» .cs - Class file
» .rpt - CrystalReport
» .xsd - DataSet1
» .ascx - DynamicDataField
» .htm - HTMLPage
» .csproj - SilverlightApplication
» .mdf - Sql Server Database
» .config - web configuration file
» .asmx -web services
» .xml - XML file
                                                                                                                                       Previous....
                                                                                                                                                     Next.....





Software development environments in asp.net

                                                                                                                                        Previous...




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 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

Nullable Types in C#

                                                                                                                                       Precious......
                                                                                                                                                    Next......

Nullable-: We can directly assign NULL value to the reference Type But can't assign null value to Value type so we use Nullable keyword to assign NULL value to value type variable.
1. Nullable types in C#
2. Null Coalescing Operator ??  



In C# types  are divided into 2 broad categories.
Value Types  - int, float, double, structs, enums etc
Reference Types – Interface, Class, delegates, arrays etc


By default value types are non nullable. To make them nullable use ?
int i = 0 (i is non nullable, so "i" cannot be set to null, i = null will generate compiler error)
int? j = 0 (j is nullable int, so j=null is legal)

Nullable types bridge the differences between C# types and Database types

Program without using NULL coalescing operator
using System;
class Program
{
    static void Main()
    {
        int AvailableTickets;
        int? TicketsOnSale = null;
        if (TicketsOnSale == null)
        {
            AvailableTickets = 0;
        }
        else
        {
            AvailableTickets = (int)TicketsOnSale;
        }
        Console.WriteLine("Available Tickets={0}", AvailableTickets);
    }
}


The above program is re-written using NULL coalescing operator
using System;
class Program
{
    static void Main()
    {
        int AvailableTickets;
        int? TicketsOnSale = null;
        //Using null coalesce operator ??
        AvailableTickets = TicketsOnSale ?? 0;
        Console.WriteLine("Available Tickets={0}", AvailableTickets);
    }
} 



                                                                                                                                       Precious......
                                                                                                                                                    Next......

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...