Saturday, 25 January 2014

Comment in C#

                                                                                                                                Previous...
                                                                                                                                               Next.....





In this Tutorial, we will discuss
1. Single line comments
2. Multi line comments 
3. Introduction to XML documentation comments  



Single line Comments                       -   //
Multi line Comments                    -   /*  */
XML Documentation Comments      -   ///



Comments are used to document what the program does and what specific blocks or lines of code do. C# compiler ignores comments.

To Comment and Uncomment, there are 2 ways
1. Use the designer
2. Keyboard Shortcut: Ctrl+K, Ctrl+C and Ctrl+K, Ctrl+U

Note: Don't try to comment every line of code. Use comments only for blocks or lines of code that are difficult to understand 



                                                                                                                              Previous...
                                                                                                                                               Next.....

Friday, 24 January 2014

Arrays in C#

                                                                                                                                     Previous...
                                                                                                                                                    Next.....

In this Tutorial, we will discuss
1. Arrays
2. Advantages and dis-advantages of arrays 



An array is a collection of similar data types.
using System;
class Program
{
    public static void Main()
    {
        // Initialize and assign values in different lines
        int[] EvenNumbers = new int[3];
        EvenNumbers[0] = 0;
        EvenNumbers[1] = 2;
        EvenNumbers[2] = 4;
        // Initialize and assign values in the same line
        int[] OddNumbers = { 1, 3, 5};
        Console.WriteLine("Printing EVEN Numbers");
        // Retrieve and print even numbers from the array
        for (int i = 0; i < EvenNumbers.Length; i++)
        {
            Console.WriteLine(EvenNumbers[i]);
        }
        Console.WriteLine("Printing ODD Numbers");
        // Retrieve and print odd numbers from the array
        for (int i = 0; i < OddNumbers.Length; i++)
        {
            Console.WriteLine(OddNumbers[i]);
        }
    }
}

Advantages: Arrays are strongly typed.

Disadvantages: Arrays cannot grow in size once initialized. Have to rely on integral indices to store or retrieve items from the array. 


                                                                                                                                   Previous...
                                                                                                                                                    Next.....

Thursday, 23 January 2014

Datatype conversions in C#

                                                                                                                                         Previous.... 
                                                                                                                                                        Next...


In this Tutorial, we will discuss
1. Implicit conversions
2. Explicit Conversions
3. Difference between Parse() and TryParse() 



Implicit conversion is done by the compiler:
1. When there is no loss of information if the conversion is done
2. If there is no possibility of throwing exceptions during the conversion



Example: Converting an int to a float will not loose any data and no exception will be thrown, hence an implicit conversion can be done. 

Where as when converting a float to an int, we loose the fractional part and also a possibility of overflow exception. Hence, in this case an explicit conversion is required. For explicit conversion we can use cast operator or the convert class in c#.

Implicit Conversion Example
using System;
class Program
{
    public static void Main()
    {
        int i = 100;
        // float is bigger datatype than int. So, no loss of
        // data and exceptions. Hence implicit conversion
        float f = i;
        Console.WriteLine(f);
    }
}

Explicit Conversion Example


using System;
class Program
{
    public static void Main()
    {
        float f = 100.25F;

        // Cannot implicitly convert float to int.
        // Fractional part will be lost. Float is a
        // bigger datatype than int, so there is
        // also a possiblity of overflow exception
        // int i = f;

        // Use explicit conversion using cast () operator
        int i = (int)f;

        // OR use Convert class
        // int i = Convert.ToInt32(f);

        Console.WriteLine(i);
    }
}

Difference between Parse and TryParse
1. If the number is in a string format you have 2 options - Parse() and TryParse() 
2. Parse() method throws an exception if it cannot parse the value, whereas TryParse() returns a bool indicating whether it succeeded or failed.
3. Use Parse() if you are sure the value will be valid, otherwise use TryParse() 


                                                                                                                                         Previous.... 
                                                                                                                                                        Next...



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

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