Sunday, September 8, 2013

Generics in C#

GENERICS IN C# 2.0

                           Generics features was introduced in the .net framework 2.0. Generic refer to the technique for writing a class without specifying data type that the class works with. This generic classes allowing to work with many different data type  without needing to be rewritten it


Generic Parameter
  Genereic parameter in the generic class can be identified by  "<" and " >" brackets in class. 

public class Stack<T>
{
   T[] m_Items; 
   public void Push(T item)
   {...}
   public T Pop()
   {...}
}
Stack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);






Friday, August 23, 2013

About Interfaces-properties methods in OOPS Concept

INTERFACES OOPS Concept

All the classes will Inherit interfaces methods. Abstract classes serve some similar operation  of interfaces. Inside the interface methods does not implemented. Interface will be define methods, properties and events

Interface is not a class it will represent with the key word 'interface'
Interface name contain with I prefix in the interface name.
Interface contain public as its modifiers.
Interface methods will be implemented in the class file which inherited interfaces.

A class can be Inherit more interfaces. Interfaces will support multiple inheritance.

code: 

//Interface contain methods without implementation inside the interface
public interface Ivalue
{
    string Name();
}

//Interface method declare in the inherited classes of the intefaces
Public class Operation : Ivalue
{
   public string Name()
  {
     return "MANOJ KUMAR";
   }
}

SAMPLE PROJECT 

//Interface
    public interface Isample
    {
        string fname
        {
            get;
            set;
        }

        string lname
        {
            get;
            set;
        }

        string Name();
    }

//Class inherited with interfaces

    public class Operation : Isample
    {

       protected string _fname;
       protected string _lname;

        public string fname
        {
            get
            {
                return _fname;
            }
            set
            {
                _fname = value;
            }
        }

        public string lname
        {
            get
            {
                return _lname;
            }
            set
            {
                _lname = value;
            }
        }

        public string Name()
        {
            return "First Name is " + fname + " & Last Name is " + lname;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Isample sam = new Operation();
            sam.fname = "Manoj";
            sam.lname = "Kumar";
            Console.WriteLine(sam.Name());
            Console.ReadLine();
        }
    }
}

Result Set






Thursday, August 22, 2013

About Abstract class - properties, methods and implementation

Abstract OOPS Concept


              Abstract class contain both Abstract method and Non Abstract Method.Abstract class can not be instantiated. Abstract class identified using keyword "abstract" in the class prefix. Abstract class can  also be defined with non abstract methods without containing Abstract methods .

code:abstract class
abstract class Operation
{
 //Abstract Method    
    public abstract int add(int num1,int num2);

    //Non Abstract Method
    public int sub(int num1, int num2)
     {
        return  num1-num2;
     }
}

 Abstract method inside abstract class does not have implementation.
 Abstract method can be identified using Keyword "abstract" in the method inside the abstract class.
Derived class of the abstract class contain the implementation of abstract methods.

Non Abstract method have implementation inside the abstract class.


Sample Abstract class Code

using System;
using System.Collections.Generic;
using System.Text;

namespace AbstractClass
{
    abstract class  Operation
    {
    //Abstract Method    
    public abstract int add(int num1,int num2);

    //Non Abstract Method
    public int sub(int num1, int num2)
     {
        return  num1-num2;
     }


    };
    class Program : Operation
    {
        //Abstract method Override Operation in Derived Class
        public override int add(int num1, int num2)
        {

            return num1 + num2;
        }
        static void Main(string[] args)
        {
           //Object of Derived class Instance created to access Methods
            Program prog = new Program();
            Console.WriteLine("addition:{0} Subtraction:{1}",prog.add(10, 5),prog.sub(50, 25));
            Console.ReadLine();
        }
    }
}

Result Screen








Properties of Abstract class & methods:
  • Abstract class can not be instantiated.
  • Abstract method can not be declared as 'Private'
  • Abstract class cant use sealed keyword.
  • Abstract  method cant use Virtual keyword.
  • If the abstract method declares as Protected inside the abstract class In the derived class also abstract method with protected modifier.


FRESHERS INTERVIEW QUESTIONS IN SQL SERVER JOINS CONCEPT


Most of the database Interview part  contains JOINS

TYPES OF JOINS IN SQL SERVER  & ITS Examples
  • LEFT OUTER JOIN  
  • RIGHT OUTER JOIN
  • FULL OUTER JOIN
  • CROSS JOIN
  • INNER JOIN



/*Create two tables*/
CREATE TABLE RightTable( ID [Int], Name Varchar(50));
GO
CREATE TABLE LeftTable(ID [INT], Amount[int]);
GO

/*Insert datas to the tables*/
INSERT INTO RightTable Values
(1,'man'),(2, 'sam'),(3,'jon'),(5,'joe'),(7,'kan')
GO
INSERT INTO LeftTable Values
(1,250),(2,550),(4,390),(6,874)
GO

/*LEFT JOIN*/
It returns all the rows in the Left side table and unmatched rows in the right side table will be "NULL"

SELECT *
FROM LeftTable
LEFT JOIN RightTable
ON LeftTable.ID=RightTable.ID

Result Set




/*RIGHT JOIN*/

It returns all the rows in the Right side table and unmatched rows in the Left side table will be "NULL"

SELECT *
FROM LeftTable
RIGHT JOIN RightTable
ON LeftTable.ID=RightTable.ID

Result Set




/*INNER JOIN*/
It returns only  common rows in the both the tables.
SELECT *
FROM  LeftTable
INNER JOIN RightTable
ON LeftTable.ID = RightTable.ID

Result Set



/*FULL JOIN*/
It returns all the rows from  both the tables.
SELECT *
FROM LeftTable
FULL OUTER JOIN RightTable
ON  LeftTable.ID = RightTable.ID

Result Set





/*CROSS JOIN*/

SELECT *
FROM LeftTable
CROSS JOIN RightTable

Result Set






Wednesday, August 21, 2013

SPARSE COLUMN IN SQL SERVER 2008

SPARSE COLUMN IN SQL SERVER 2008

     Optimized Storing of Null value can be done  using SPARSE COLUMN.
     Storing a null in a sparse column takes up no space at all. . In other words, a SPARSE column is better at managing NULL and ZERO values in SQL Server. It does not occupy any space in the database.

Sample for Identifying the size using Sparse column

/*CREATE BOTH SPARSED TABLE and UNPARSED TABLE*/

CREATE TABLE UNPARSEDmark1 (
testNAME VARCHAR(100),
TESTDate smallDateTime)
GO

CREATE TABLE mark1(
testNAME VARCHAR(100) SPARSE,
TESTDate smallDateTime SPARSE)
GO

/*INSERT 45000 NULL ROWS IN BOTH TABLES*/

DECLARE @IDx INT=1
WHILE @IDx<50000
BEGIN
INSERT INTO UNPARSEDmark1 VALUES(NULL,NULL)
INSERT INTO mark1 VALUES(NULL,NULL)
SET @idx+=1
END
GO
/*CHECK THE SPACE USED BY BOTH TABLES*/
sp_spaceUsed 'UNPARSEDmark1'
GO
sp_spaceUsed 'mark1'
GO
















Advantages of SPARSE Column
  • A SPARSE column saves database space when there is zero or null values in the database.
  • INSERT, UPDATE, and DELETE statements can reference the SPARSE columns by name.
  • We can get more benefit of Filtered indexes on a SPARSE column.
Limitation of SPARSE Column
  •  SPARSE column must be nullable and cannot have the ROWGUIDCOL or IDENTITY properties.
  • A SPARSE column cannot be data types like text, ntext, image, timestamp, user-defined data type, geometry, or geography.
  • Merge replication does not support SPARSE columns.
  • The SPARSE property of a column is not preserved when the table is copied.

Friday, July 26, 2013

NORMALIZATION

What is normalization?
Database Design Technique used for avoiding redundant data and dependency data.


Before going to view the rules lets understand some basics,

Primary Key – unique identify for the database records without duplication.
        Following Characteristics of Primary Key,
·         Primary key does not allow null value
·         Primary key must be unique
·         Primary values cannot be changed
·         Primary key created when new records inserted.

Composite Key – Combination of multicolumn values for identity a record unique.

Foreign Key –
Foreign Key - insert record in foreign key table will throw error if foreign Key doesn’t have entry in Primary Key.


Transitive Functional Dependencies
A transitive functional dependency is when changing a non-key column , might cause any of the other non-key columns to change




1NF - (no duplication of data/ single value for each column)
    1NF Rules:
·         Each column contain single value
·         Each rows inserted must be unique
  
2NF – (Use of Referential integrity, Primary Key and Foreign Key)
 2NF Rules

·         Follow  1NF
·         Single column Primary Key
3NF Rules
·         Follow 2NF
·         Has no transitive Functional Dependencies


Boyce-Codd Normal Form (BCNF)

Even when a database is in 3rd Normal Form, still there would be anomalies resulted if it has more than one Candidate Key.  
Sometimes is BCNF is also referred as 3.5 Normal Form.


4th Normal Form
If no database table instance contains two or more, independent and multivalued data describing the relevant entity , then it is in 4th Normal Form.

5th Normal Form
A table is in 5th Normal Form only if it is in 4NF and it cannot be decomposed in to any number of smaller tables without loss of data.











Wednesday, July 3, 2013

C# - Broken Authentication and Session Management

Definition by OWASP:
                   Application functions related to authentication and session management are often not implemented correctly, allowing attackers to compromise passwords, keys, session tokens, or exploit other implementation flaws to assume other users’ identities.

·         The attackers may be external attackers or the users who are using the application can steal account information of other.
·         Attackers will make use the flaws or leaks found in the application authentication and session management function will lead to loss of sensitive information, passwords to impersonate users. 
·         Developers of the application use custom authentication and session management deploy correctly is very hard.
·         Such flaw may allow some or even all user account information to be hacked successfully.
·         The above risk is not clearly defined just like injection and XSS. Broken is a bit of all different vulnerabilities, some may explicitly looked up such as insecure cryptographic storage and insufficient transport layer authentication.

           Hackers will intercept session from cookie or requested URL.

ASP.Net Session State

           Programmatically, session state is nothing more than memory in the shape of a dictionary or hash table, e.g. key-value pairs, which can be set and read for the duration of a user's session.

Session Management

ASP maintains session state by providing the client with a unique key assigned to the user when the session begins. This key is stored in an HTTP cookie that the client sends to the server on each request. The server can then read the key from the cookie and re-inflate the server session state.

With cookie

      Enter user name and password for login page. Cookie information stored properly in this page and used further use.

 

// assume successful authentication against an account source...
Session ["Username"] = username;
                lblUsername.Text = username == null? "Unknown”: username.ToString ();



Cookie information stored can be viewed and obtained easily.

Cookieless State Information

Use cookieless state in asp.net session management. Store session information in particular position in the URL .
   <sessionState cookieless="true" />

          http://yourserver/folder/(session ID here)/default.aspx



Page contain Cookieless state hold session information will have identical information for both cookie and cookieless state.

Use Asp.net Membership provider and Role provider

        Practice use of asp.net member ship provider and role provider will help in reducing the attacks




<asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false">
<AnonymousTemplate>
 [ <a href="~/Account/Login.aspx" id="HeadLoginStatus" runat="server">Log In</a> ]
 </AnonymousTemplate>
 <LoggedInTemplate>
Welcome
<span class="bold">
<asp:LoginName ID="HeadLoginName" runat="server" />
</span>
! [ <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" LogoutPageUrl="~/" /> ]
 </LoggedInTemplate>
 </asp:LoginView>


Use asp.net membership provider control provided in .net control toolbox and customizable role provider done using this control. Avoid using your own or custom authentication and session management for the application don’t attempt to rewrite code without proper need of it.



Implement Proper Password Strength Controls
                Password Length
·         Set minimum length of 10 and make it as strong.
·         Weak password strength will lead to crack the password.
·         Make sure maximum password length to be 20-30 Characters.

Password Complexity
§     at least 1 uppercase character (A-Z)
§     at least 1 lowercase character (a-z)
§     at least 1 digit (0-9)
§     at least 1 special character (punctuation) — do not forget to treat space as special characters too.

 

Implement Secure Password Recovery Mechanism

Instead of sending password via mail reset the password

 

Use SSL with Session

 Using SSL all communication are encrypted (the cookies content been encrypted). Make it nearly impossible to directly access the data cookies.

Get the session expiration automatically or manually
Make the session clear either automatically or manually to avoid maintain for prolong period of time.

<system.web>
 <sessionState timeout="10" />
</system.web>

Summary

 We can protect ourselves by make cookie encrypted using SSL, expire cookie information periodically, Double Checking Password and avoid cookieless information.