JavaScript Object Notation (JSON)

JavaScript Object Notation (JSON) is a lightweight format for representing objects and their state. The asynchronous communication layer uses JSON as a serialization format instead of the SOAP format more typically used with Web services. Using JSON simplifies client-server interaction, because it eliminates the need for extensive client script to construct requests that use SOAP and XML

Difference between PHP Validating filters and PHP Sanitizing filters

Validating filters:

Are used to validate user input
Strict format rules (like URL or E-Mail validating)
Returns the expected type on success or FALSE on failure

Sanitizing filters:


Are used to allow or disallow specified characters in a string
No data format rules
Always return the string

PHP Filter

A PHP filter is used to validate and filter data coming from insecure sources.

To test, validate and filter user input or custom data is an important part of any web application.

The PHP filter extension is designed to make data filtering easier and quicker.

PHP code -Create a Custom Exception Class

<?php
class customException extends Exception
{
public function errorMessage()
 {
 //error message
 $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
 .': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
 return $errorMsg;
 }
}

$email = "someone@example...com";

try
{
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
 {
 //throw exception if email is not valid
 throw new customException($email);
 }
}

catch (customException $e)
{
//display custom message
echo $e->errorMessage();
}
?>

PHP Error Handling -Try, throw and catch

Proper exception code should include:

Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown"
Throw - This is how you trigger an exception. Each "throw" must have at least one "catch"
Catch - A "catch" block retrieves an exception and creates an object containing the exception information

Lets try to trigger an exception with valid code:

<?php
//create function with an exception
function checkNum($number)
{
if($number>1)
 {
 throw new Exception("Value must be 1 or below");
 }
return true;
}

//trigger exception in a "try" block
try
{
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}

//catch exception
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
?>

How to send mail in PHP

Code for send mail in PHP

<?php


$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";

?>

PHP mail() Function

The PHP mail() function is used to send emails from inside a script.

Syntax

mail(to,subject,message,headers,parameters)



to Required. Specifies the receiver / receivers of the email
subject Required. Specifies the subject of the email. Note: This parameter cannot contain any newline characters
message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
parameters Optional. Specifies an additional parameter to the sendmail program

How to destroy a Session in PHP

You can use the unset() or the session_destroy() function.

The unset() function is used to free the specified session variable:

<?php
unset($_SESSION['views']);
?>

You can also completely destroy the session by calling the session_destroy() function:

<?php
session_destroy();
?>

How to store a Session Variable in PHP

The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:

Code for store a session in pHP

<?php
session_start();
// store session data
$_SESSION['views']=1;
?>

<html>
<body>

<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>

</body>
</html>

Output:

Pageviews=1

How to start a PHP Session

Start a PHP Session

Before you can store user information in your PHP session, you must first start up the session.

Note: The session_start() function must appear BEFORE the <html> tag:

<?php session_start(); ?>

<html>
<body>

</body>
</html>

In PHP, How to Delete a Cookie?

Deleting a cookie you should assure that the expiration date is in the past.

example:

<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>

In PHP, How to get a Cookie Value?

PHP isset() function to find out if a cookie has been set:

<html>
<body>

<?php
if (isset($_COOKIE["user"]))
 echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
 echo "Welcome guest!<br />";
?>

</body>
</html>

In PHP, How to Retrieve a Cookie Value?

PHP $_COOKIE variable is used to retrieve a cookie value.

In the example below, we retrieve the value of the cookie named "user" and display it on a page:

<?php
// Print a cookie
echo $_COOKIE["user"];

// A way to view all cookies
print_r($_COOKIE);
?>

PHP setcookie() function

The setcookie() function is used to set a cookie.

Note: The setcookie() function must appear BEFORE the <html> tag.

Syntax
setcookie(name, value, expire, path, domain);


In PHP how to Create a Cookie?

The setcookie() function is used to set a cookie.

Note: The setcookie() function must appear BEFORE the <html> tag.
Syntax

setcookie(name, value, expire, path, domain);

Example


In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We also specify that the cookie should expire after one hour:

<?php
setcookie("user", "Alex Porter", time()+3600);
?>

<html>
<body>

</body>
</html>

PHP - Saving the Uploaded File

The examples above create a temporary copy of the uploaded files in
the PHP temp folder on the server.

The temporary copied files disappears when the script ends. To store
the uploaded file we need to copy it to a different location:

<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>

PHP Upload Script

<?php
  if ($_FILES["file"]["error"] > 0)
  {
     echo "Error: " . $_FILES["file"]["error"] . "<br />";
  }
  else
  {
     echo "Upload: " . $_FILES["file"]["name"] . "<br />";
     echo "Type: " . $_FILES["file"]["type"] . "<br />";
     echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
     echo "Stored in: " . $_FILES["file"]["tmp_name"];
 }
?>

By using the global PHP $_FILES array you can upload files from a client computer to the remote server.

The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this:

$_FILES["file"]["name"] - the name of the uploaded file
$_FILES["file"]["type"] - the type of the uploaded file
$_FILES["file"]["size"] - the size in bytes of the uploaded file
$_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
$_FILES["file"]["error"] - the error code resulting from the file upload

This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload.

PHP fgetc() function

fgetc() function : Reading a File Character by Character

The fgetc() function is used to read a single character from a file.

Note: After a call to this function the file pointer moves to the next character.

Example

The example below reads a file character by character, until the end of file is reached:

<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
 {
 echo fgetc($file);
 }
fclose($file);
?>

PHP fgets() function

Reading a File Line by Line

The fgets() function is used to read a single line from a file.

Note: After a call to this function the file pointer has moved to the next line.

Example

The example below reads a file line by line, until the end of file is reached:

<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
 {
 echo fgets($file). "<br />";
 }
fclose($file);
?>

PHP feof() function

Check End-of-file
The feof() function checks if the "end-of-file" (EOF) has been reached.

The feof() function is useful for looping through data of unknown length.

if (feof($file)) echo "End of file";

PHP fclose() Function

The fclose() function is used to close an open file:

<?php
$file = fopen("test.txt","r");

//some code to be executed

fclose($file);
?>

PHP fopen() function

The fopen() function is used to open files in PHP.

The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened:

<html>
<body>

<?php
$file=fopen("welcome.txt","r");
?>

</body>
</html>

PHP require() Function

The require() function is identical to include(), except that it handles errors differently.

The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error).

Example with the require() function.


PHP code:

<html>
<body>

<?php
require("wrongFile.php");
echo "Hello World!";
?>

</body>
</html>

Error message:

Warning: require(wrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5

Fatal error: require() [function.require]:
Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5

PHP Date - Format the Date

The first parameter in the date() function specifies how to format the date/time. It uses letters to represent date and time formats. Here are some of the letters that can be used:

d - The day of the month (01-31)
m - The current month, as a number (01-12)
Y - The current year in four digits

An overview of all the letters that can be used in the format parameter, can be found in our PHP Date reference.

Other characters, like"/", ".", or "-" can also be inserted between the letters to add additional formatting:

<?php
echo date("Y/m/d");
echo "<br />";
echo date("Y.m.d");
echo "<br />";
echo date("Y-m-d");
?>

Output of the code:

2006/07/11
2006.07.11
2006-07-11

PHP Date - What is a Timestamp?

A timestamp is the number of seconds since January 1, 1970 at 00:00:00 GMT. This is also known as the Unix Timestamp.

What is PHP Date() Function

The PHP date() function formats a timestamp to a more readable date and time.

Syntax

date(format,timestamp)

Parameter Description

format Required. Specifies the format of the timestamp
timestamp Optional. Specifies a timestamp. Default is the current date and time (as a timestamp)

PHP $_POST Variable

$_POST variable is an array of variable names and values sent by the HTTP POST method.

$_POST variable is used to collect values from a form with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

Example


<form action="welcome.php" method="post">
Enter your name: <input type="text" name="name" />
Enter your age: <input type="text" name="age" />
<input type="submit" />
</form>

PHP $_REQUEST Variable

PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.

 PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.

Example


Welcome <?php echo $_REQUEST["name"]; ?>.<br />
You are <?php echo $_REQUEST["age"]; ?> years old!

PHP $_GET Variable

$_GET variable is an array of variable names and values sent by the HTTP GET method.

The $_GET variable is used to collect values from a form with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and it has limits on the amount of information to send (max. 100 characters).

Example

<form action="welcome.php" method="get">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

Explain PHP Form Validation

User input should be validated whenever possible. Client side validation is faster, and will reduce server load.

However, any site that gets enough traffic to worry about server resources, may also need to worry about site security. You should always use server side validation if the form accesses a database.

A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error

PHP Form Handling

The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.

Form example:

<html>
  <body>

            <form action="welcome.php" method="post">
                   Name: <input type="text" name="name" />
                   Age: <input type="text" name="age" />
                  <input type="submit" />
          </form>

  </body>
</html>

The example HTML page above contains two input fields and a submit button. When the user fills in this form and click on the submit button, the form data is sent to the "welcome.php" file.

The "welcome.php" file looks like this:

<html>
<body>

Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.

</body>
</html>

A sample output of the above script may be:

Welcome John.
You are 28 years old.



How to create a function in PHP

Creating PHP functions:

   * All functions start with the word "function()"
   * Name the function - It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number)
   * Add a "{"  - The function code starts after the opening curly brace
   * Insert the function code
   * Add a "}"  - The function is finished by a closing curly brace

Example

A simple function that writes my name when it is called:

<html>
<body>

<?php
         function writeMyName()
         {
               echo "Kai Jim Refsnes";
         }

        writeMyName();
?>

</body>
</html>

PHP Looping

Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to perform this.

In PHP we have the following looping statements:

  • while - loops through a block of code if and as long as a specified condition is true
  • do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true
  • for - loops through a block of code a specified number of times
  • foreach - loops through a block of code for each element in an array

In Terms PHP what is an array?

When working with PHP, sooner or later, you might want to create many similar variables.

Instead of having many similar variables, you can store the data as elements in an array.

Each element in the array has its own ID so that it can be easily accessed.

There are three different kind of arrays:

  • Numeric array - An array with a numeric ID key
  • Associative array - An array where each ID key is associated with a value
  • Multidimensional array - An array containing one or more arrays

PHP Switch Statement Syntax

If you want to select one of many blocks of code to be executed, use the Switch statement.

The switch statement is used to avoid long blocks of if..elseif..else code.

Syntax

switch (expression)
{
             case label1:
                     code to be executed if expression = label1;
                     break;  
             case label2:
                     code to be executed if expression = label2;
                     break;
             default:
                    code to be executed if expression is different  from both label1 and label2;
}

Using the strpos() function

The strpos() function is used to search for a string or character within a string.

If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE.

Let's see if we can find the string "world" in our string:

<?php
echo strpos("Hello world!","world");
?>

Output of the code:

6

PHP strlen() function

The strlen() function is used to find the length of a string.

Let's find the length of our string "Hello world!":

<?php
echo strlen("Hello world!");
?>

output of the code

12

How to concatenate two variables / String

There is only one string operator in PHP.

The concatenation operator (.)  is used to put two string values together.

To concatenate two variables together, use the dot (.) operator:

<?php
$txt1="Hello World";
$txt2="1234";
echo $txt1 . " " . $txt2;
?>

output

Hello World 1234

PHP Variable Naming Rules

  • A variable name must start with a letter or an underscore "_"
  • A variable name can only contain alpha-numeric characters and underscores (a-Z, 0-9, and _ )
  • A variable name should not contain spaces. If a variable name is more than one word, it should be separated with underscore ($my_string), or with capitalization ($myString)

How to Declare Variables in PHP

Variables are used for storing a values, like text strings, numbers or arrays.

When a variable is set it can be used over and over again in your script

All variables in PHP start with a $ sign symbol.

The correct way of setting a variable in PHP:

$var_name = value;

New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will not work.

Let's try creating a variable with a string, and a variable with a number:

<?php
$txt = "Hello World!";
$number = 16;
?>

Comments in PHP language

In PHP language , we use // to make a single-line comment or /* and */ to make a large comment block.

<html>
<body>

<?php

//This is a comment

/*
This is
a comment
block
*/

?>

</body>
</html>

How to Install PHP

If your server supports PHP - you don't need to do anything! You do not need to compile anything or install any extra tools  - just create some .php files in your web directory - and the server will parse them for you. Most web hosts offer PHP support.

However, if your server does not support PHP, you must install PHP. Below is a link to a good tutorial from PHP.net on how to install PHP5:

http://www.php.net/manual/en/install.php

Download PHP

Download PHP for free here: http://www.php.net/downloads.php

Download MySQL Database

Download MySQL for free here: http://www.mysql.com/downloads/index.html

Download Apache Server

Download Apache for free here: http://httpd.apache.org/download.cgi

How to install and use the web service dispatcher?

Perquisites
 .NET framework
  Microsoft Soap Toolkit 3.0
(you can still use Microsoft Soap Toolkit 2.0 by modifying the web.config file).

Following steps for install web service dispatcher :-

Step 1. First, unzip the file WebServiceDispatcher.zip into a directory on the target machine, you need to preserve directory structure while unzipping.

Step 2. Create a virtual web directory WebServiceDispatcher pointing to the above directory.

Then we need to register existing web methods with the dispatcher.

Step 3.
Call the RegisterMethod method of the dispatcher.

The RegisterMethod method does not have to be called by the server instance that implements the web method, but typically a server calls RegisterMethod to register its web methods when starting up. The following VB script registers a web method named GetData .

Option Explicit

Const WSDL_URL = _
 "http://localhost/WebServiceDispatcher/ServiceDispatcher.asmx?wsdl"
Const INPUT_XML = _
   "<Root><MethodList><Method>_
   <MethodName>GetData</MethodName>_
   <ProviderName>Server11</ProviderName>_
   <ServiceURL>http://Server11.com/MyService/MyService.wsdl</ServiceURL>_
   </Method></MethodList></Root>"

Dim spclt
Set spclt = CreateObject("MSSOAP.SoapClient")
spclt.mssoapinit WSDL_URL

If spclt.RegisterMethod(INPUT_XML) Then
   WScript.Echo "Web method registered"
Else
   WScript.Echo "Failed to register web method"    
End If
set spclt = nothing

Here is an example of the input string to the RegisterMethod method. As you can see, it is possible to register multiple web methods with one call.


<Root>
  <MethodList>
      <Method>
           <MethodName>GetName</MethodName>
           <InternalMethodName>GetName1</InternalMethodName>
           <ProviderName>NameProvider1</ProviderName>
           <ServiceURL>http://NameProvider1.com/WebService/WebService.wsdl
           </ServiceURL>
           <ProxyServer>MyProxy.Com</ProxyServer>
           <ProxyPort>91</ProxyPort>
           <AuthUser>Tester</AuthUser>
           <AuthPassword>123456</AuthPassword>
      </Method>
      <Method>
           <MethodName>GetName</MethodName>
           <InternalMethodName>GetName2</InternalMethodName>
           <ProviderName>NameProvider2</ProviderName>
           <ServiceURL>http://NameProvider2.com/WebService/WebService.wsdl
           </ServiceURL>
           <ProxyServer>MyProxy.Com</ProxyServer>
           <ProxyPort>91</ProxyPort>
           <AuthUser>Tester</AuthUser>
           <AuthPassword>123456</AuthPassword>
       <Method>
       <Method>
           <MethodName>GetAge</MethodName>
           <ProviderName>AgeProvider</ProviderName>
           <ServiceURL>http://AgeProvider.com/WebService/WebService.wsdl
           </ServiceURL>
       </Method>
   </MethodList>
</Root>

The <MethodName> string identifies the web method registered on the dispatcher. The <ProviderName> string identifies a server instance that implements this web method. The <InternalMethodName> string is the name of the web method on the server instance that implements it, you can register the same web method from two different server instances (two different providers) as demonstrated in the above XML. It is assumed that <MethodName> and <InternalMethodName> are the same in case <InternalMethodName> is not provided. When a request to invoke a web method comes to the dispatcher, the dispatcher will randomly pick a provider if there is more than one. The <ServiceURL> string is used by the dispatcher to access the provider of a web method on behalf of the clients. The <ProxyServer> and the <ProxyPort> strings are optional, they are needed only if there is a firewall between the dispatcher and the provider of the web method. The <AuthUser> and the <AuthPassword> strings are also optional, they are needed only if access to the web method provider are restricted by the given user name and password.

It is ok to register a web method for the same provider more than once, the last registeration will override the previous ones. For example, if the <ServiceURL> string was wrong when it was first registered, you can correct the information by registering it again.

A server providing a web method through the dispatcher should call the UnRegisterMethod method before shutting down itself. The format of the input string for UnRegisterMethod is the same as that of the RegisterMethod except that you need only to specify <MethodName> and <ProviderName> . If you don't specify <ProviderName> , then the web method identified by <MethodName> will be unregistered for all providers!

Step 4.
Other programs access the registered web methods by calling InvokeMethodX methods of the web service dispatcher.

Here is a VB script that calls the GetData web method registered in the above script, assuming it takes only one input argument.

Option Explicit

Const WSDL_URL = _
 "http://localhost/WebServiceDispatcher/ServiceDispatcher.asmx?wsdl"

Dim spclt
Set spclt = CreateObject("MSSOAP.SoapClient")
spclt.mssoapinit WSDL_URL

Dim output
output = spclt.InvokeMethod1("GetData", "This is an input string")

If output <> "" Then
   WScript.Echo "Output: " & output
Else
   WScript.Echo "Failed to invoke web meothod"
End If

set spclt = nothing

When writing real code, you should know what to send as the input arguments and how to process the output. I have included code for a sample web service called MathService which provides four web methods, Add, Subtract, Multiply, and Divide . To install MathService , you need to unzip the MathService.zip file into a directory on the target machine and create a virtual web directory named MathService for it. Run the script RegisterMathService.vbs to register methods of MathService on the dispatcher (assuming you already installed the dispatcher). Run the script InvokeMathService.vbs to invoke the methods of MathService through the dispatcher.

LINQ to SQL Statements Select with a Where Clause

public void SimpleQuery3()
{
DataClasses1DataContext dc = new DataClasses1DataContext();

var q =
from a in dc.GetTable<Order>()
where a.CustomerID == "VINET"
select a;

dataGridView1.DataSource = q;
}

simple LINQ to SQL statement

public void SimpleQuery()
{
DataClasses1DataContext dc = new DataClasses1DataContext();

var q =
from a in dc.GetTable<Order>()
select a;

dataGridView1.DataSource = q;
}

SQL Server Performance Tips and Guidelines

• As a common practice, every table should have a clustered index. Generally, but not always, the clustered index should be on a column that monotonically increases, such as an identity column or some other column where the value is unique. In many cases, the primary key is the ideal column for a clustered index.

• Indexes should be measured on all columns that are frequently used in WHERE, ORDER BY, GROUP BY, TOP and DISTINCT clauses.

• Do not automatically add indexes on a table because it seems like the right thing to do. Only add indexes if you know that they will be used by the queries run against the table.

• For historical (static) tables, create the indexes with a FILLFACTOR and a PAD_INDEX of 100 to ensure there is no wasted space. This reduces disk I/O, helping to boost overall performance.

• Queries that return a single row are just as fast using a non-clustered index as a clustered index.

• Queries that return a range of rows are just as fast using a clustered index as a non-clustered index.

• Do not add more indexes on your OLTP tables to minimize the overhead that occurs with indexes during data modifications.

• Do not add the same index more than once on a table with different names.

• Drop all those indexes that are not used by the Query Optimizer, generally. You probably won't want to add an index to a table under the following conditions:

If the index is not used by the query optimizer. Use the Query Analyzer's "Show Execution Plan" option to see if your queries against a particular table use an index or not.
If the table is small, most likely indexes will not be used.
If the column(s) to be indexed are very wide.
If the column(s) are defined as TEXT, NTEXT or IMAGE data types.
If the table is rarely queried but insertion, updating is frequent.

• To provide up-to-date statistics, the query optimizer needs to make smart query optimization decisions. You will generally want to leave the "Auto Update Statistics" database option on. This helps to ensure that the optimizer statistics are valid, ensuring that queries are properly optimized when they are run.

• Keep the "width" of your indexes as narrow as possible. This reduces the size of the index and reduces the number of disk I/O reads required to read the index.

• If possible, try to create indexes on columns that have integer values instead of characters. Integer values use less overhead than character values.

• If you have two or more tables that are frequently joined together, then the columns used for the joins should have an appropriate index. If the columns used for the joins are not naturally compact, then consider adding surrogate keys to the tables that are compact in order to reduce the size of the keys. This will decrease I/O during the join process, which increases overall performance.

• When creating indexes, try to make them unique indexes if at all possible. SQL Server can often search through a unique index faster than a non-unique index. This is because, in a unique index, each row is unique and once the needed record is found, SQL Server doesn't have to look any further.

• If a particular query against a table is run infrequently and the addition of an index greatly speeds the performance of the query, but the performance of INSERTS, UPDATES and DELETES is negatively affected by the addition of the index, consider creating the index for the table for the duration of when the query is run and then dropping the index. An example of this is when monthly reports are run at the end of the month on an OLTP application.

• Avoid using FLOAT or REAL data types as primary keys, as they add unnecessary overhead that can hurt performance.

• If you want to boost the performance of a query that includes an AND operator in the WHERE clause, consider the following:

Of the search criteria in the WHERE clause, at least one of them should be based on a highly selective column that has an index.
If at least one of the search criteria in the WHERE clause is not highly selective, consider adding indexes to all of the columns referenced in the WHERE clause.
If none of the columns in the WHERE clause are selective enough to use an index on their own, consider creating a covering index for this query.

• The Query Optimizer will always perform a table scan or a clustered index scan on a table if the WHERE clause in the query contains an OR operator and if any of the referenced columns in the OR clause are not indexed (or do not have a useful index). Because of this, if you use many queries with OR clauses, you will want to ensure that each referenced column in the WHERE clause has an index.

• If you have a query that uses ORs and it is not making the best use of indexes, consider rewriting it as a UNION and then testing performance. Only through testing can you be sure that one version of your query will be faster than another.

• If you use the SOUNDEX function against a table column in a WHERE clause, the Query Optimizer will ignore any available indexes and perform a table scan.

• Queries that include either the DISTINCT or the GROUP BY clauses can be optimized by including appropriate indexes. Any of the following indexing strategies can be used:

Include a covering, non-clustered index (covering the appropriate columns) of the DISTINCT or the GROUP BY clauses.
Include a clustered index on the columns in the GROUP BY clause.
Include a clustered index on the columns found in the SELECT clause.
Adding appropriate indexes to queries that include DISTINCT or GROUP BY is most important for those queries that run often.

• Avoid clustered indexes on columns that are already "covered" by non-clustered indexes. A clustered index on a column that is already "covered" is redundant. Use the clustered index for columns that can better make use of it.

• Ideally a clustered index should be based on a single column (not multiple columns) that are as narrow as possible. This not only reduces the clustered index's physical size, it also reduces the physical size of non-clustered indexes and boosts SQL Server's overall performance.

• When you create a clustered index, try to create it as a unique clustered index, not a non-unique clustered index.

• SET NOCOUNT ON at the beginning of each stored procedure you write. This statement should be included in every stored procedure, trigger, etc. that you write.

• Keep Transact-SQL transactions as short as possible within a stored procedure. This helps to reduce the number of locks, helping to speed up the overall performance of your SQL Server application.

• If you are creating a stored procedure to run in a database other than the Master database, don't use the prefix sp_ in its name. This special prefix is reserved for system stored procedures. Although using this prefix will not prevent a user defined stored procedure from working, what it can do is to slow down its execution ever so slightly.

• Before you are done with your stored procedure code, review it for any unused code, parameters or variables that you may have forgotten to remove while you were making changes and remove them. Unused code just adds unnecessary bloat to your stored procedures, although it will not necessarily negatively affect performance of the stored procedure.

• For best performance, all objects that are called within the same stored procedure should be owned by the same object owner or schema, preferably dbo, and should also be referred to in the format of object_owner.object_name or schema_owner.object_name.

• When you need to execute a string of Transact-SQL, you should use the sp_executesql stored procedure instead of the EXECUTE statement.

• If you use input parameters in your stored procedures, you should validate all of them at the beginning of your stored procedure. This way, if there is a validation problem and the client application needs to be notified of the problem, it happens before any stored procedure processing takes place, preventing wasted effort and boosting performance.

• When calling a stored procedure from your application, it is important that you call it using its qualified name, for example:

exec dbo.myProc

...instead of:

exec myProc

• If you think a stored procedure will return only a single value and not a record set, consider returning the single value as an output parameter.

• Use stored procedures instead of views. They offer better performance.

• Don't include code, variable or parameters that don't do anything.

• Don't be afraid to make broad-minded use of in-line and block comments in your Transact-SQL code. They will not affect the performance of your application and they will enhance your productivity when you have to come back to the code and try to modify it.

• If possible, avoid using SQL Server cursors. They generally use a lot of SQL Server resources and reduce the performance and scalability of your applications.

• If you have the choice of using a join or a sub-query to perform the same task within a query, generally the join is faster. This is not always the case, however, and you may want to test the query using both methods to determine which is faster for your particular application.

• If your application requires you to create temporary tables for use on a global or per connection use, consider the possibility of creating indexes for these temporary tables. While most temporary tables probably won't need -- or even use -- an index, some larger temporary tables can benefit from them. A properly designed index on a temporary table can be as great a benefit as a properly designed index on a standard database table.

• Instead of using temporary tables, consider using a derived table instead. A derived table is the result of using a SELECT statement in the FROM clause of an existing SELECT statement. By using derived tables instead of temporary tables, you can reduce I/O and often boost your application's performance.

• For better performance, if you need a temporary table in your Transact-SQL code, consider using a table variable instead of creating a conventional temporary table.

• Don't repeatedly reuse the same function to calculate the same result over and over within your Transact-SQL code.

• If you use BULK INSERT to import data into SQL Server, then use the TABLOCK hint along with it. This will prevent SQL Server from running out of locks during very large imports and will also boost performance due to the reduction of lock contention.

• Always specify the narrowest columns you can. The narrower the column, the less amount of data SQL Server has to store and the faster SQL Server is able to read and write data. In addition, if any sorts need to be performed on the column, the narrower the column, the faster the sort will be.

• If you need to store large strings of data and they are less than 8000 characters, use a VARCHAR data type instead of a TEXT data type. TEXT data types have extra overhead that drag down performance.

• Don't use the NVARCHAR or NCHAR data types unless you need to store 16-bit character (Unicode) data. They take up twice as much space as VARCHAR or CHAR data types, increasing server I/O and wasting unnecessary space in your buffer cache.

• If the text data in a column varies greatly in length, use a VARCHAR data type instead of a CHAR data type. The amount of space saved by using VARCHAR over CHAR on variable length columns can greatly reduce the I/O reads that the cache memory uses to hold data, improving overall SQL Server performance.

• If a column's data does not vary widely in length, consider using a fixed-length CHAR field instead of a VARCHAR. While it may take up a little more space to store the data, processing fixed-length columns is faster in SQL Server than processing variable-length columns.

• If you have a column that is designed to hold only numbers, use a numeric data type such as INTEGER instead of a VARCHAR or CHAR data type. Numeric data types generally require less space to hold the same numeric value than does a character data type. This helps to reduce the size of the columns and can boost performance when the columns are searched (WHERE clause), joined to another column or sorted.

• If you use the CONVERT function to convert a value to a variable length data type such as VARCHAR, always specify the length of the variable data type. If you do not, SQL Server assumes a default length of 30. Ideally, you should specify the shortest length to accomplish the required task. This helps to reduce memory use and SQL Server resources.

• Avoid using the new BIGINT data type unless you really need its additional storage capacity. The BIGINT data type uses 8 bytes of memory, versus 4 bytes for the INT data type.

• Don't use the DATETIME data type as a primary key. From a performance perspective, it is more efficient to use a data type that uses less space. For example, the DATETIME data type uses 8 bytes of space, while the INT data type only takes up 4 bytes. The less space used, the smaller the table and index, and the less I/O overhead that is required to access the primary key.

• If you are creating a column that you know will be subject to many sorts, consider making the column integer-based and not character-based. This is because SQL Server can sort integer data much faster than character data.

• Carefully evaluate whether your SELECT query needs the DISTINCT clause or not. Some developers automatically add this clause to every one of their SELECT statements, even when it is not necessary. This is a bad habit that should be stopped.

• When you need to use SELECT INTO option, keep in mind that it can lock system tables, preventing other users from accessing the data they need while the data is being inserted. In order to prevent or minimize the problems caused by locked tables, try to schedule the use of SELECT INTO when your SQL Server is less busy. In addition, try to keep the amount of data inserted to a minimum. In some cases, it may be better to perform several smaller SELECT INTOs instead of performing one large SELECT INTO.

• If you need to verify the existence of a record in a table, don't use SELECT COUNT (*) in your Transact-SQL code to identify it. This is very inefficient and wastes server resources. Instead, use the Transact-SQL IF EXISTS to determine if the record in question exists, which is much more efficient.

• By default, some developers -- especially those who have not worked with SQL Server before -- routinely include code similar to this in their WHERE clauses when they make string comparisons:

SELECT column_name FROM table_name
WHERE LOWER (column_name) = 'name'

In other words, these developers are making the assumption that the data in SQL Server is case-sensitive, which it generally is not. If your SQL Server database is not configured to be case sensitive, you don't need to use LOWER or UPPER to force the case of text to be equal for a comparison to be performed. Just leave these functions out of your code. This will speed up the performance of your query, as any use of text functions in a WHERE clause hurts performance.

However, what if your database has been configured to be case-sensitive? Should you then use the LOWER and UPPER functions to ensure that comparisons are properly compared? No. The above example is still poor coding. If you have to deal with ensuring case is consistent for proper comparisons, use the technique described below, along with appropriate indexes on the column in question:

SELECT column_name FROM table_name
WHERE column_name = 'NAME' or column_name = 'name'

This code will run much faster than the first example.

• If you currently have a query that uses NOT IN, which offers poor performance because the SQL Server optimizer has to use a nested table scan to perform this activity, instead try to use one of the following options, all of which offer better performance:

Use EXISTS or NOT EXISTS
Use IN
Perform a LEFT OUTER JOIN and check for a NULL condition

• When you have a choice of using the IN or the EXISTS clause in your Transact-SQL, you will generally want to use the EXISTS clause, as it is usually more efficient and performs faster.

• If you find that SQL Server uses a TABLE SCAN instead of an INDEX SEEK when you use an IN/OR clause as part of your WHERE clause, even when those columns are covered by an index, consider using an index hint to force the Query Optimizer to use the index.

• If you use LIKE in your WHERE clause, try to use one or more leading characters in the clause, if possible. For example, use:

LIKE 'm%' instead of LIKE '%m'

• If your application needs to retrieve summary data often, but you don't want to have the overhead of calculating it on the fly every time it is needed, consider using a trigger that updates summary values after each transaction into a summary table.

• When you have a choice of using the IN or the BETWEEN clauses in your Transact-SQL, you will generally want to use the BETWEEN clause, as it is much more efficient. For example...

SELECT task_id, task_name
FROM tasks
WHERE task_id in (1000, 1001, 1002, 1003, 1004)

...is much less efficient than this:

SELECT task_id, task_name
FROM tasks
WHERE task_id BETWEEN 1000 and 1004

• If possible, try to avoid using the SUBSTRING function in your WHERE clauses. Depending on how it is constructed, using the SUBSTRING function can force a table scan instead of allowing the optimizer to use an index (assuming there is one). If the substring you are searching for does not include the first character of the column you are searching for, then a table scan is performed.

• If possible, you should avoid using the SUBSTRING function and use the LIKE condition instead for better performance. Instead of doing this:

WHERE SUBSTRING(task_name,1,1) = 'b'

Try using this instead:

WHERE task_name LIKE 'b%'

• Avoid using optimizer hints in your WHERE clauses. This is because it is generally very hard to out-guess the Query Optimizer. Optimizer hints are special keywords that you include with your query to force how the Query Optimizer runs. If you decide to include a hint in a query, this forces the Query Optimizer to become static, preventing the Query Optimizer from dynamically adapting to the current environment for the given query. More often than not, this hurts -- not helps -- performance.

• If you have a WHERE clause that includes expressions connected by two or more AND operators, SQL Server will evaluate them from left to right in the order they are written. This assumes that no parentheses have been used to change the order of execution. Because of this, you may want to consider one of the following when using AND:

Locate the least likely true AND expression first.
If both parts of an AND expression are equally likely of being false, put the least complex AND expression first.
You may want to consider using Query Analyzer or Management Studio to look at the execution plans of your queries to see which is best for your situation

• Don't use ORDER BY in your SELECT statements unless you really need to, as it adds a lot of extra overhead. For example, perhaps it may be more efficient to sort the data at the client than at the server.

• Whenever SQL Server has to perform a sorting operation, additional resources have to be used to perform this task. Sorting often occurs when any of the following Transact-SQL statements are executed:

ORDER BY
GROUP BY
SELECT DISTINCT
UNION

• If you have to sort by a particular column often, consider making that column a clustered index. This is because the data is already presorted for you and SQL Server is smart enough not to resort the data.

• If your WHERE clause includes an IN operator along with a list of values to be tested in the query, order the list of values so that the most frequently found ones are placed at the start of the list and the less frequently found ones are placed at the end of the list. This can speed up performance because the IN option returns true as soon as any of the values in the list produce a match. The sooner the match is made, the faster the query completes.

• If your application performs many wildcard (LIKE %) text searches on CHAR or VARCHAR columns, consider using SQL Server's full-text search option. The Search Service can significantly speed up wildcard searches of text stored in a database.

• The GROUP BY clause can be used with or without an aggregate function. However, if you want optimum performance, don't use the GROUP BY clause without an aggregate function. This is because you can accomplish the same end result by using the DISTINCT option instead, and it is faster. For example, you could write your query two different ways:

SELECT task_id
FROM tasks
WHERE task_id BETWEEN 10 AND 20
GROUP BY OrderID

...or:

SELECT DISTINCT task_id
FROM tasks
WHERE task_id BETWEEN 10 AND 20

• It is important to design applications that keep transactions as short as possible. This reduces locking and increases application concurrently, which helps to boost performance.

• In order to reduce network traffic between the client or middle-tier and SQL Server -- and also to boost your SQL Server-based application's performance -- only the data needed by the client or middle-tier should be returned by SQL Server. In other words, don't return more data (both rows and columns) from SQL Server than you need to the client or middle-tier and then further reduce the data to the data you really need at the client or middle-tier. This wastes SQL Server resources and network bandwidth.

• To make complex queries easier to analyze, consider breaking them down into their smaller constituent parts. One way to do this is to simply create lists of the key components of the query, such as:

List all of the columns that are to be returned
List all of the columns that are used in the WHERE clause
List all of the columns used in the JOINs (if applicable)
List all the tables used in JOINs (if applicable)
Once you have the above information organized into this easy-to-comprehend form, it is much easier to identify those columns that could potentially make use of indexes when executed.

C# Sample code :shows a threading Trap

using System;
using System.Threading;

namespace ThreadTrap1
{
/// <summary>
/// This example shows a threading Trap, you simply can't
/// rely on threads executing in the order in which they
/// are started.
/// </summary>
class Program
{
static void Main(string[] args)
{

Thread T1 = new Thread(new ThreadStart(Increment));
Thread T2 = new Thread(new ThreadStart(Increment));
T1.Name = "T1";
T2.Name = "T2";
T1.Start();
T2.Start();
Console.ReadLine();
}


private static void Increment()
{
for (int i = 0; i < 100000;i++ )
if (i % 10000 == 0)
Console.WriteLine("Thread Name {0}",
Thread.CurrentThread.Name);
WriteDone(Thread.CurrentThread.Name);
}


private static void WriteDone(string threadName)
{
switch (threadName)
{
case "T1" :
Console.WriteLine("T1 Finished");
break;
case "T2":
Console.WriteLine("T2 Finished");
break;
}
}
}
}

Resume Threads

There used to be a way to pause threads using the Resume() method. But this is now deprecated, so you must use alternative methods, such as WaitHandles. To demonstrate this there is a combined application that covers Pause/Resume and Abort of background threads

Pause threads

There used to be a way to pause threads using the Pause() method. But this is now deprecated, so you must use alternative methods, such as WaitHandles. To demonstrate this there is a combined application that covers Pause/Resume and Abort of background threads

C# Sample Code : ThreadInterrupt

using System;
using System.Threading;

namespace ThreadInterrupt
{
   class Program
   {

       public static Thread sleeper;
       public static Thread waker;

       public static void Main(string[] args)
       {
           Console.WriteLine("Enter Main method");
           sleeper = new Thread(new ThreadStart(PutThreadToSleep));
           waker = new Thread(new ThreadStart(WakeThread));
           sleeper.Start();
           waker.Start();
           Console.WriteLine("Exiting Main method");
           Console.ReadLine();

       }

       //thread sleeper threadStart
       private static void PutThreadToSleep()
       {
           for (int i = 0; i < 50; i++)
           {
               Console.Write(i + " ");
               if (i == 10 || i == 20 || i == 30)
               {
                   try
                   {
                       Console.WriteLine("Sleep, Going to sleep at {0}",
                           i.ToString());
                       Thread.Sleep(20);
                   }
                   catch (ThreadInterruptedException e)
                   {
                       Console.WriteLine("Forcibly ");
                   }
                   Console.WriteLine("woken");
               }
           }
       }

       //thread waker threadStart
       private static void WakeThread()
       {

           for (int i = 51; i < 100; i++)
           {
               Console.Write(i + " ");

               if (sleeper.ThreadState == ThreadState.WaitSleepJoin)
               {
                   Console.WriteLine("Interrupting sleeper");
                   sleeper.Interrupt();
               }
           }

       }
   }
}

What is Thread Interrupt?

When a thread is put to sleep, the thread goes into the WaitSleepJoin state. If the thread is in this state it may be placed back in the scheduling queue by the use of the Interrupt method. Calling Interrupt when a thread is in the WaitSleepJoin state will cause a ThreadInterruptedException to be thrown, so any code that is written needs to catch this.

C# Sample code : for Thread.Sleep

using System;
using System.Threading;

namespace ThreadSleep
{
   class Program
   {

       public static Thread T1;
       public static Thread T2;

       public static void Main(string[] args)
       {
           Console.WriteLine("Enter Main method");

           T1 = new Thread(new ThreadStart(Count1));
           T2 = new Thread(new ThreadStart(Count2));
           T1.Start();
           T2.Start();
           Console.WriteLine("Exit Main method");
           Console.ReadLine();

       }

       //thread T1 threadStart
       private static void Count1()
       {
           Console.WriteLine("Enter T1 counter");
           for (int i = 0; i < 50; i++)
           {
               Console.Write(i + " ");
               if (i == 10)
                   Thread.Sleep(1000);
           }
           Console.WriteLine("Exit T1 counter");
       }

       //thread T2 threadStart
       private static void Count2()
       {
           Console.WriteLine("Enter T2 counter");
           for (int i = 51; i < 100; i++)
           {
               Console.Write(i + " ");
               if (i == 70)
                   Thread.Sleep(5000);
           }
           Console.WriteLine("Exit T2 counter");
       }
   }
}

C# Sample code : for Join 2 Threads

using System.Threading;

namespace ThreadJoin
{
   class Program
   {

       public static Thread T1;
       public static Thread T2;

       public static void Main(string[] args)
       {
           T1 = new Thread(new ThreadStart(First));
           T2 = new Thread(new ThreadStart(Second));
           T1.Name = "T1";
           T2.Name = "T2";
           T1.Start();
           T2.Start();
           Console.ReadLine();

       }

       //thread T1 threadStart
       private static void First()
       {
           for (int i = 0; i < 5; i++)
           {
               Console.WriteLine(
                   "T1 state [{0}], T1 showing {1}",
                   T1.ThreadState,  i.ToString());
           }
       }

       //thread T2 threadStart
       private static void Second()
       {
           //what the state of both threads
           Console.WriteLine(
               "T2 state [{0}] just about to Join, T1 state [{1}], CurrentThreadName={2}",
               T2.ThreadState, T1.ThreadState,
               Thread.CurrentThread.Name);

           //join T1
           T1.Join();

           Console.WriteLine(
               "T2 state [{0}] T2 just joined T1, T1 state [{1}], CurrentThreadName={2}",
               T2.ThreadState, T1.ThreadState,
               Thread.CurrentThread.Name);

           for (int i = 5; i < 10; i++)
           {
               Console.WriteLine(
                   "T2 state [{0}], T1 state [{1}], CurrentThreadName={2} showing {3}",
                   T2.ThreadState, T1.ThreadState,
                   Thread.CurrentThread.Name, i.ToString());
           }

           Console.WriteLine(
               "T2 state [{0}], T1 state [{1}], CurrentThreadName={2}",
               T2.ThreadState, T1.ThreadState,
               Thread.CurrentThread.Name);
       }
   }
}