Wednesday, October 9, 2013

Difference between Abstract Class VS Interaces

Abstract Class

  •    with keyword Abstract in the class Contain both abstract and non abstract methods. Abstract  methods does not contain implementaion in base classs only contains  method name with parameters with keyword abstract in the methods. Non Abstract methods contain implementation in the base Class itself.
  • Abstract method should be override in the derived class by defining it. 
  • A class can be inherited from only one abstract class.
  • Abstract class can't able to instantiate. It can be accessed through derived class objects.
  • Abstract class have access specifiers for Function/Properties/Methods
Interface
   
  • Interface is not a class it is a Entity defined by interfaces. Methods defined inside interface does not contain implementation only method  name with parameter. Classes which inherited interfaces all methods defined will get Implemented in the base class.
  • A class can have more than One Interfaces . It supports multiple inheritance.(C# does not support multiple inheritance.) 
  • Interface does not contain Access Specifier for Function/Properties/Methods default as Public.
  


LINQ IN SQL

LINQ - Language Integrated Query

  • Feature Introduced in Visual Studio 2008 
  • Supported from Visual Studio 2008 & later versions of visual Studio.
  • Used or Query the result set from  Objects/XML/ADO.Net (Object collection/Data Set /SQL Server/Entities/XML).
  • Using Linq 
For Querying result in our front end C# language support LINQ.

Sample Query for Linq


var q=(from item in TAA_Parcels
where item.IsDeleted==false
 select new{
                item.ParcelID,
                 item.ParcelNumber,
           }).ToList(); 
  
q.Dump();

Result Set



































INNER JOIN uisng  LINQ Query

from item in Metadatas 
 join item1 in BusinessRules on item.DatabaseID equals item1.DatabaseID
where item.DatabaseID == 1 orderby item.ReportTypeID 
select new
{
item.MetadataID,
item1.RuleName,
item.ReportTypeID,
item1.FormulaExpression

}



CROSS JOIN using LINQ

from meta in Metadatas
from type in  MetadataTypes
where meta.DatabaseID == 1 && meta.MetadataTypeID==1
select new
{
       meta.MetadataID,
       meta.MetadataTypeID,
       meta.DatabaseID,
       type.CreatedBy,
       type.MetadataTypeName
}












































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.

C# - Unvalidated Redirects and Forward Access

Definition by OWASP:
          Web applications frequently redirect and forward users to other pages and websites, and use untrusted data to determine the destination pages. Without proper validation, attackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages.

·     The users are trick by the attackers making users to submitting request to attackers’ website unknowingly.
·        Attackers link the unvalidated redirect and trick user into clicking it.
·         Unsafe forward to bypass security checks by the attackers.
·         Target page is specified in an unvalidated parameter, allowing attacker to choose destination page.
·         Redirect will attempt to install malware and identify the sensitive information.
·         Unsafe forward may allow access control bypass.
·         Reputation of business can lost and business value of your users trust get affected 

How attackers achieve it

Unvalidated Redirects
Attackers find a page with a redirect on it:








     
    Through phishing or some mechanism attackers get modify the above the URL link make the user to click the link              

 

http:/ / www.mytrustedsite.com/Redirect.aspx?Url=http://myuntrustedsite.com


Clicked on a URL which clearly had the host name of mytrustedsite.com, we’re now on myuntrustedsite.com. What’s more, there’s a logon form asking for credentials which you’d naturally expect would be handled properly under the circumstances.

The code behind the page simply takes the URL parameter from the query string, performs some arbitrary logging then performs a redirect which sends an HTTP 302 response to the browser:

var url = Request.QueryString["Url"];
 LogRedirect(url);
 Response.Redirect(url);

The above mytrustedsite.com is authorised domain so the user will click the URL this will lead to unvalidated redirects.


Redirect can be achieved by JavaScript:
  • location
  • location.href
  • location.pathname
  • location.search
  • location.protocol
  • location.hostname
  • location.assign
  • location.replace


/<![CDATA[
(function(g){
  var a=location.href.split("#!")[1];
  if(a){g.location=g.HBR=a;}
})(window);
//]]>

Unvalidated Forwards
               
                An application having login page and after successful login a protected page which is not accessible normally. Using Forward bypassing login page go directly access protected page


Avoid unvalidated redirects and forwards

·      To identify the vulnerability one should review the redirects and forwards of their site and verify the target URL in any redirection is an allowable destination.
 For eg:
Response.Redirect(“DestinationPage”);
Server.Transfer(“DestinationPage”);

·      Whitelist more important. All input must be validated against a whitelist of acceptable value ranges.
  var url = Request.QueryString["Url"];
 if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
              // Gracefully exit with a warning message
          }    

This validation will make the  untrusted data conforms to expected pattern of URL.
·         In the case of unvalidated redirects, we don’t need to have the URL in the query string, let’s try it like this:

http://mytrustedsite.com/Redirect.aspx?Id=AD420440-DB7E-4F16-8A61-72C9CEA5D58D
     
The entire code would then look something like this:

var id = Request.QueryString["Id"];
 Guid idGuid;
if (!Guid.TryParse(id, out idGuid))
{ // Gracefully exit with a warning message }
 var db = new MyTrustedSiteEntities();
var allowableUrl = db.AllowableUrls.SingleOrDefault(u => u.Id == idGuid);
if (allowableUrl == null)
{
// Gracefully exit with a warning message
 }
 LogRedirect(allowableUrl.Url);
 Response.Redirect(allowableUrl.Url);

We are still validate against the data type  and checking it against whitelist this code will provide extra protection and ensure against manipulation.

·      Create / use spider crawl your own website(Look at the Log statuses)
300 – Serious Statuses
302 – Old page moved from location
307 – Proper validation.

Prevent unvalidated redirects and forwards
               
·         Avoid using redirects and forwards.
·         If implemented, don’t use user parameter for identify the destination page. This can be usually done while developing.
·          If the destination parameter is unavoidable, ensure the parameter supplied is valid and verified by the user.
·          It is recommended that any such destination parameters be a mapping value, rather than the actual URL or portion of the URL, and that server side code translate this mapping to the target URL.
·         Applications can use ESAPI to override the sendRedirect() method to make sure all redirect destinations are safe.
Avoiding such flaws is extremely important as they are target of phishers trying to gain the user’s trust.

References:


Example Attack Scenarios
Scenario #1: The application has a page called “redirect.jsp” which takes a single parameter named “url”. The attacker crafts a malicious URL that redirects users to a malicious site that performs phishing and installs malware.
http://www.example.com/redirect.jsp?url=evil.com
Scenario #2: The application uses forwards to route requests between different parts of the site. To facilitate this, some pages use a parameter to indicate where the user should be sent if a transaction is successful. In this case, the attacker crafts a URL that will pass the application’s access control check and then forwards the attacker to administrative functionality for which the attacker isn’t authorized.
http://www.example.com/boring.jsp?fwd=admin.jsp