17 May 2012

To display the list of stored procedure containing text in Sql Server


To display the list of  stored procedure containing text in Sql Server


DECLARE @Search varchar(255) SET @Search='CNC_EmailResults_Other'
SELECT DISTINCT o.name AS Object_Name,o.type_desc  FROM sys.sql_modules  m    INNER JOIN sys.objects
o ON m.object_id=o.object_id     WHERE m.definition Like '%'+@Search+'%'     ORDER BY 2,1



To find the text in the stored procedure in Sql server

To find the text in the stored procedure in Sql server



declare @newString varchar(205)
Set @newString = '%' + 'CNC_EmailResults_Other' + '%'
-- Insert statements for procedure here
select name from sysobjects where id in
(select id from syscomments where text like @newString)
order by name

Debug the Windows service in Setup

Debug the Windows service in Setup

1. Window service setup should be in debug mode.

2. Insert the code in the appropriate place System.Diagnostics.Debugger.Launch()

3. Now start debugging the windows service.



C# and VB.Net Connectivity using DataReader with Stored Procedure


C# and VB.Net Connectivity using  DataReader with Stored Procedure

static void GetSalesByCategory(string connectionString,
    string categoryName)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        // Create the command and set its properties.
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandText = "SalesByCategory";
        command.CommandType = CommandType.StoredProcedure;

        // Add the input parameter and set its properties.
        SqlParameter parameter = new SqlParameter();
        parameter.ParameterName = "@CategoryName";
        parameter.SqlDbType = SqlDbType.NVarChar;
        parameter.Direction = ParameterDirection.Input;
        parameter.Value = categoryName;

        // Add the parameter to the Parameters collection.
        command.Parameters.Add(parameter);

        // Open the connection and execute the reader.
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();

        if (reader.HasRows)
        {
            while (reader.Read())
            {
                Console.WriteLine("{0}: {1:C}", reader[0], reader[1]);
            }
        }
        else
        {
            Console.WriteLine("No rows found.");
        }
        reader.Close();
    }
}

VB.Net Connectivity for  DataReader

Shared Sub GetSalesByCategory(ByVal connectionString As String, _
    ByVal categoryName As String)

    Using connection As New SqlConnection(connectionString)

        ' Create the command and set its properties.
        Dim command As SqlCommand = New SqlCommand()
        command.Connection = connection
        command.CommandText = "SalesByCategory"
        command.CommandType = CommandType.StoredProcedure

        ' Add the input parameter and set its properties.
        Dim parameter As New SqlParameter()
        parameter.ParameterName = "@CategoryName"
        parameter.SqlDbType = SqlDbType.NVarChar
        parameter.Direction = ParameterDirection.Input
        parameter.Value = categoryName

        ' Add the parameter to the Parameters collection.
        command.Parameters.Add(parameter)

        ' Open the connection and execute the reader.
        connection.Open()
        Dim reader As SqlDataReader = command.ExecuteReader()

        If reader.HasRows Then
            Do While reader.Read()
                Console.WriteLine("{0}: {1:C}", _
                  reader(0), reader(1))
            Loop
        Else
            Console.WriteLine("No rows returned.")
        End If
    End Using
End Sub







2 May 2012

Generics in Dotnet

Generics  in Dotnet


·         In generic class, you can create a collection that is type-safe at compile-time.
   
      Generics are the most powerful feature of C# 2.0. Generics allow you to define type-safe data structures, without committing to actual data types. This results in a significant performance boost and higher quality code, because you get to reuse data processing algorithms without duplicating type-specific code. In concept, generics are similar to C++ templates, but are drastically different in implementation and capabilities. This article discusses the problem space generics address, how they are implemented, the benefits of the programming model, and unique innovations, such as constrains, generic methods and delegates, and generic inheritance. You will also see how generics are utilized in other areas of the .NET Framework such as reflection, arrays, collections, serialization, and remoting.


            If the items are value types, they must be boxed when they are added to the list, and unboxed when they are retrieved. 
·       
            Both the casting and the boxing and unboxing operations decrease performance; the effect of boxing and unboxing can be very significant in scenarios where you must iterate over large collections.
    
      The other limitation is lack of compile-time type checking; because an ArrayList casts everything to Object, there is no way at compile-time to prevent client code from doing something such as this:

    System.Collections.ArrayList list = new System.Collections.ArrayList();
    // Add an integer to the list.
    list.Add(3);
    // Add a string to the list. This will compile, but may cause an error later.
    list.Add("It is raining in Redmond.");
    int t = 0;

    // This causes an InvalidCastException to be returned.
    foreach (int x in list)
    {   t += x;
    }


Boxing and Unboxing in Dotnet

Boxing and Unboxing  in Dotnet


Boxing is the process of converting a value type to the type object
When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap.
Unboxing extracts the value type from the object. 



int i = 123;
object o = (object)i;  // boxing
The object can then be unboxed and assigned to integer variable i: 
o = 123;
i = (int)o;  // unboxing
Disadvantages of Boxing
Performance
Boxing and unboxing are computationally expensive processes. When a value type is boxed, an entirely new      object must be created. This can take up to 20 times longer than an assignment. When unboxing, the casting     process can take four times as long as an assignment.

16 April 2012

Sql Injection in Sql Server

Sql Injection in Sql Server


SQL injection is an attack in which malicious code is inserted into strings that are later passed to an instance of SQL Server for parsing and execution.


Any procedure that constructs SQL statements should be reviewed for injection vulnerabilities because SQL Server will execute all syntactically valid queries that it receives.


The primary form of SQL injection consists of direct insertion of code into user-input variables that are concatenated with SQL commands and executed.


The injection process works by prematurely terminating a text string and appending a new command. 

The following script shows a simple SQL injection. The script builds an SQL query by concatenating hard-coded strings together with a string entered by the user:

var Shipcity;
ShipCity = Request.form ("ShipCity");
var sql = "select * from OrdersTable where ShipCity = '" + ShipCity + "'";

The user is prompted to enter the name of a city. If she enters Redmond, the query assembled by the script looks similar to the following:
SELECT * FROM OrdersTable WHERE ShipCity = 'Redmond'
However, assume that the user enters the following:
Redmond'; drop table OrdersTable--
In this case, the following query is assembled by the script:
SELECT * FROM OrdersTable WHERE ShipCity = 'Redmond';drop table OrdersTable--'
The semicolon (;) denotes the end of one query and the start of another. The double hyphen (--) indicates that the rest of the current line is a comment and should be ignored. If the modified code is syntactically correct, it will be executed by the server. When SQL Server processes this statement, SQL Server will first select all records in OrdersTablewhere ShipCity is Redmond. Then, SQL Server will drop OrdersTable.
As long as injected SQL code is syntactically correct, tampering cannot be detected programmatically. Therefore, you must validate all user input and carefully review code that executes constructed SQL commands in     the server that you are using.

Always validate user input by testing type, length, format, and range. When you are implementing precautions against malicious input, consider the architecture and deployment scenarios of your application. 
  • Test the size and data type of input and enforce appropriate limits. This can help prevent deliberate buffer overruns.
  • Test the content of string variables and accept only expected values.

    • Never build Transact-SQL statements directly from user input.
    • Use stored procedures to validate user input.
            Never concatenate user input that is not validated. String concatenation is the primary point of entry for script injection.
When you can, reject input that contains the following characters.
Input characterMeaning in Transact-SQL
;
Query delimiter.
'
Character data string delimiter.
--
Comment delimiter.
/* ... */
Comment delimiters. Text between /* and */ is not evaluated by the server.
xp_
Used at the start of the name of catalog-extended stored procedures, such as xp_cmdshell.

Use Type-Safe SQL Parameters

The Parameters collection in SQL Server provides type checking and length validation. 
SqlDataAdapter myCommand = new SqlDataAdapter("AuthorLogin", conn);
myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter parm = myCommand.SelectCommand.Parameters.Add("@au_id",
     SqlDbType.VarChar, 11);
parm.Value = Login.Text;

Use Parameterized Input with Stored Procedures

Stored procedures may be susceptible to SQL injection if they use unfiltered input. For example, the following code is vulnerable:
SqlDataAdapter myCommand = 
new SqlDataAdapter("LoginStoredProcedure '" + 
                               Login.Text + "'", conn);
If you use stored procedures, you should use parameters as their input.

Use the Parameters Collection with Dynamic SQL

If you cannot use stored procedures, you can still use parameters, as shown in the following code example:
SqlDataAdapter myCommand = new SqlDataAdapter(
"SELECT au_lname, au_fname FROM Authors WHERE au_id = @au_id", conn);
SQLParameter parm = myCommand.SelectCommand.Parameters.Add("@au_id", 
                        SqlDbType.VarChar, 11);
Parm.Value = Login.Text;

Filtering Input

Filtering input may also be helpful in protecting against SQL injection by removing escape characters. However, because of the large number of characters that may pose problems, this is not a reliable defense. The following example searches for the character string delimiter.
private string SafeSqlLiteral(string inputSQL)
{
  return inputSQL.Replace("'", "''");
}

LIKE Clauses

Note that if you are using a LIKE clause, wildcard characters still must be escaped:
s = s.Replace("[", "[[]");
s = s.Replace("%", "[%]");
s = s.Replace("_", "[_]");
http://msdn.microsoft.com/en-us/library/ms161953(v=sql.100).aspx

Implementing OAuth validation in a Web API

 I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...