Saturday, 31 March 2012

JQuery Events

jQuery Event Methods



jQuery Event Methods

Event methods trigger, or bind a function to an event for all matching elements.
Trigger example:
$("button").click() - triggers the click event for a button element.
Binding example:
$("button").click(function(){$("img").hide()}) - binds a function to the click event.
The following table lists all the methods used to handle events.
Method Description
bind() Add one or more event handlers to matching elements
blur() Triggers, or binds a function to the blur event of selected elements
change() Triggers, or binds a function to the change event of selected elements
click() Triggers, or binds a function to the click event of selected elements
dblclick() Triggers, or binds a function to the dblclick event of selected elements
delegate() Add one or more event handlers to current, or future, specified child elements of the matching elements
die() Remove all event handlers added with the live() function
error() Triggers, or binds a function to the error event of selected elements
event.currentTarget The current DOM element within the event bubbling phase
event.data Contains the optional data passed to jQuery.fn.bind when the current executing handler was bound
event.isDefaultPrevented() Returns whether event.preventDefault() was called for the event object
event.isImmediatePropagationStopped() Returns whether event.stopImmediatePropagation() was called for the event object
event.isPropagationStopped() Returns whether event.stopPropagation() was called for the event object
event.pageX The mouse position relative to the left edge of the document
event.pageY The mouse position relative to the top edge of the document
event.preventDefault() Prevents the default action of the event
event.relatedTarget The other DOM element involved in the event, if any
event.result This attribute contains the last value returned by an event handler that was triggered by this event, unless the value was undefined
event.stopImmediatePropagation() Prevents other event handlers from being called
event.stopPropagation() Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event
event.target The DOM element that initiated the event
event.timeStamp This attribute returns the number of milliseconds since January 1, 1970, when the event is triggered
event.type Describes the nature of the event
event.which Which key or button was pressed for a key or button event
focus() Triggers, or binds a function to the focus event of selected elements
focusin() Binds a function to the focusin event of selected elements
focusout() Binds a function to the focusout event of selected elements
hover() Binds one or two functions to the hover event of selected elements
keydown() Triggers, or binds a function to the keydown event of selected elements
keypress() Triggers, or binds a function to the keypress event of selected elements
keyup() Triggers, or binds a function to the keyup event of selected elements
live() Add one or more event handlers to current, or future, matching elements
load() Triggers, or binds a function to the load event of selected elements
mousedown() Triggers, or binds a function to the mouse down event of selected elements
mouseenter() Triggers, or binds a function to the mouse enter event of selected elements
mouseleave() Triggers, or binds a function to the mouse leave event of selected elements
mousemove() Triggers, or binds a function to the mouse move event of selected elements
mouseout() Triggers, or binds a function to the mouse out event of selected elements
mouseover() Triggers, or binds a function to the mouse over event of selected elements
mouseup() Triggers, or binds a function to the mouse up event of selected elements
one() Add one or more event handlers to matching elements. This handler can only be triggered once per element
ready() Binds a function to the ready event of a document
(when an HTML document is ready to use)
resize() Triggers, or binds a function to the resize event of selected elements
scroll() Triggers, or binds a function to the scroll event of selected elements
select() Triggers, or binds a function to the select event of selected elements
submit() Triggers, or binds a function to the submit event of selected elements
toggle() Binds two or more functions to the toggle between for the click event for selected elements
trigger() Triggers all events bound to the selected elements
triggerHandler() Triggers all functions bound to a specified event for the selected elements
unbind() Remove an added event handler from selected elements
undelegate() Remove an event handler to selected elements, now or in the future
unload() Triggers, or binds a function to the unload event of selected elements

JQuery Selectors

jQuery Selectors

Use our excellent jQuery Selector Tester to experiment with the different selectors.
Selector Example Selects
* $("*") All elements
#id $("#lastname") The element with id=lastname
.class $(".intro") All elements with class="intro"
element $("p") All p elements
.class.class $(".intro.demo") All elements with the classes "intro" and "demo"
:first $("p:first") The first p element
:last $("p:last") The last p element
:even $("tr:even") All even tr elements
:odd $("tr:odd") All odd tr elements
:eq(index) $("ul li:eq(3)") The fourth element in a list (index starts at 0)
:gt(no) $("ul li:gt(3)") List elements with an index greater than 3
:lt(no) $("ul li:lt(3)") List elements with an index less than 3
:not(selector) $("input:not(:empty)") All input elements that are not empty
:header $(":header") All header elements h1, h2 ...
:animated $(":animated") All animated elements
:contains(text) $(":contains('W3Schools')") All elements which contains the text
:empty $(":empty") All elements with no child (elements) nodes
:hidden $("p:hidden") All hidden p elements
:visible $("table:visible") All visible tables
s1,s2,s3 $("th,td,.intro") All elements with matching selectors
[attribute] $("[href]") All elements with a href attribute
[attribute=value] $("[href='default.htm']") All elements with a href attribute value equal to "default.htm"
[attribute!=value] $("[href!='default.htm']") All elements with a href attribute value not equal to "default.htm"
[attribute$=value] $("[href$='.jpg']") All elements with a href attribute value ending with ".jpg"
[attribute^=value] $("[href^='jquery_']") All elements with a href attribute value starting with "jquery_"
:input $(":input") All input elements
:text $(":text") All input elements with type="text"
:password $(":password") All input elements with type="password"
:radio $(":radio") All input elements with type="radio"
:checkbox $(":checkbox") All input elements with type="checkbox"
:submit $(":submit") All input elements with type="submit"
:reset $(":reset") All input elements with type="reset"
:button $(":button") All input elements with type="button"
:image $(":image") All input elements with type="image"
:file $(":file") All input elements with type="file"
:enabled $(":enabled") All enabled input elements
:disabled $(":disabled") All disabled input elements
:selected $(":selected") All selected input elements
:checked $(":checked") All checked input elements



Select all elements inside <body>:
$("body *")

Definition and Usage

The * selector selects every single element in the document, including html, head and body.
If used together with another element (nested selectors, like in the example above), it selects all child elements within the specified element.

Syntax

$("*")


Tips and Notes

Tip: Depending on use, the * can be slow, and heavy for some browsers to process.

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("body *").css("background-color","red");
});
</script>
</head>
<body>
<h1>Welcome to My Homepage</h1>
<p class="intro">My name is Donald</p>
<p>I live in Duckburg</p>
<p>My best friend is Mickey</p>
Who is your favourite:
<ul id="choose">
<li>Goofy</li>
<li>Mickey</li>
<li>Pluto</li>
</ul>
</body>
</html>

JQuery

What is jQuery?

jQuery is a library of JavaScript Functions.
jQuery is a lightweight "write less, do more" JavaScript library.
The jQuery library contains the following features:
  • HTML element selections
  • HTML element manipulation
  • CSS manipulation
  • HTML event functions
  • JavaScript Effects and animations
  • HTML DOM traversal and modification
  • AJAX
  • Utilities

Adding the jQuery Library to Your Pages

The jQuery library is stored as a single JavaScript file, containing all the jQuery methods.
It can be added to a web page with the following mark-up:
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
Please note that the <script> tag should be inside the page's <head> section.

Basic jQuery Example

The following example demonstrates the jQuery hide() method, hiding all <p> elements in an HTML document.

Example

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("p").hide();
  });
});
</script>
</head>


<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html> 

Downloading jQuery

Two versions of jQuery are available for downloading: one minified and one uncompressed (for debugging or reading).
Both versions can be downloaded from jQuery.com.

Alternatives to Downloading

If you don't want to store the jQuery library on your own computer, you can use the hosted jQuery library from Google or Microsoft.

Google

<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>


jQuery Syntax Examples

$(this).hide()
Demonstrates the jQuery hide() method, hiding the current HTML element.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $(this).hide();
  });
});
</script>
</head>

<body>
<button>Click me</button>
</body>
</html>




$("#test").hide()
Demonstrates the jQuery hide() method, hiding the element with id="test".

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("#test").hide();
  });
});
</script>
</head>

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p id="test">This is another paragraph.</p>
<button>Click me</button>
</body>

</html>

 
$("p").hide()
Demonstrates the jQuery hide() method, hiding all <p> elements.

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("p").hide();
  });
});
</script>
</head>

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>

$(".test").hide()
Demonstrates the jQuery hide() method, hiding all elements with class="test".

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $(".test").hide();
  });
});
</script>
</head>
<body>

<h2 class="test">This is a heading</h2>
<p class="test">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>


jQuery Syntax

The jQuery syntax is tailor made for selecting HTML elements and perform some action on the element(s).
Basic syntax is: $(selector).action()
  • A dollar sign to define jQuery
  • A (selector) to "query (or find)" HTML elements
  • A jQuery action() to be performed on the element(s)
Examples:
$(this).hide() - hides current element
$("p").hide() - hides all paragraphs
$("p.test").hide() - hides all paragraphs with class="test"
$("#test").hide() - hides the element with id="test"
lamp jQuery uses a combination of XPath and CSS selector syntax.
You will learn more about the selector syntax in the next chapter of this tutorial.


The Document Ready Function

You might have noticed that all jQuery methods, in our examples, are inside a document.ready() function:
$(document).ready(function(){

   // jQuery functions go here...

});
This is to prevent any jQuery code from running before the document is finished loading (is ready).
Here are some examples of actions that can fail if functions are run before the document is fully loaded:
  • Trying to hide an element that doesn't exist
  • Trying to get the size of an image that is not loaded



Java Script

The Navigator object contains information about the visitor's browser.

Browser Detection

Almost everything in this tutorial works on all JavaScript-enabled browsers. However, there are some things that just don't work on certain browsers - especially on older browsers.
Sometimes it can be useful to detect the visitor's browser, and then serve the appropriate information.
The Navigator object contains information about the visitor's browser name, version, and more.
Note Note: There is no public standard that applies to the navigator object, but all major browsers support it.

The Navigator Object

The Navigator object contains all information about the visitor's browser:

Example

<div id="example"></div>

<script type="text/javascript">

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";

document.getElementById("example").innerHTML=txt;

</script>
A cookie is often used to identify a user.

What is a Cookie?

A cookie is a variable that is stored on the visitor's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.
Examples of cookies:
  • Name cookie - The first time a visitor arrives to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like "Welcome John Doe!" The name is retrieved from the stored cookie
  • Date cookie - The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like "Your last visit was on Tuesday August 11, 2005!" The date is retrieved from the stored cookie

Create and Store a Cookie

In this example we will create a cookie that stores the name of a visitor. The first time a visitor arrives to the web page, he or she will be asked to  fill in her/his name. The name is then stored in a cookie. The next time the visitor arrives at the same page, he or she will get welcome message.
First, we create a function that stores the name of the visitor in a cookie variable:
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
The parameters of the function above hold the name of the cookie, the value of the cookie, and the number of days until the cookie expires.
In the function above we first convert the number of days to a valid date, then we add the number of days until the cookie should expire. After that we store the cookie name, cookie value and the expiration date in the document.cookie object.
Then, we create another function that returns a specified cookie:
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}
The function above makes an array to retrieve cookie names and values, then it checks if the specified cookie exists, and returns the cookie value.
Last, we create the function that displays a welcome message if the cookie is set, and if the cookie is not set it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the setCookie function:
function checkCookie()
{
var username=getCookie("username");
  if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}
All together now:

Example

<html>
<head>
<script type="text/javascript">
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
  {
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}
</script>
</head>

<body onload="checkCookie()">
</body>
</html>

Regex in JS

RegExp, is short for regular expression.

Complete RegExp Object Reference


The reference contains a brief description and examples of use for each property and method!

What is RegExp?

A regular expression is an object that describes a pattern of characters.
When you search in a text, you can use a pattern to describe what you are searching for.
A simple pattern can be one single character.
A more complicated pattern can consist of more characters, and can be used for parsing, format checking, substitution and more.
Regular expressions are used to perform powerful pattern-matching and "search-and-replace" functions on text.

Syntax

var patt=new RegExp(pattern,modifiers);

or more simply:

var patt=/pattern/modifiers;
  • pattern specifies the pattern of an expression
  • modifiers specify if a search should be global, case-sensitive, etc.

RegExp Modifiers

Modifiers are used to perform case-insensitive and global searches.
The i modifier is used to perform case-insensitive matching.
The g modifier is used to perform a global match (find all matches rather than stopping after the first match).

Example 1

Do a case-insensitive search for "w3schools" in a string:
var str="Visit W3Schools";
var patt1=/w3schools/i;
The marked text below shows where the expression gets a match:
Visit W3Schools


Example 2

Do a global search for "is":
var str="Is this all there is?";
var patt1=/is/g;
The marked text below shows where the expression gets a match:
Is this all there is?


Example 3

Do a global, case-insensitive search for "is":
var str="Is this all there is?";
var patt1=/is/gi;
The marked text below shows where the expression gets a match:
Is this all there is?



test()

The test() method searches a string for a specified value, and returns true or false, depending on the result.
The following example searches a string for the character "e":

Example

var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
Since there is an "e" in the string, the output of the code above will be:
true




exec()

The exec() method searches a string for a specified value, and returns the text of the found value. If no match is found, it returns null.
The following example searches a string for the character "e":

Example 1

var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));
Since there is an "e" in the string, the output of the code above will be:
e

Math Object In Javascript

Math Object

The Math object allows you to perform mathematical tasks.
Math is not a constructor. All properties/methods of Math can be called by using Math as an object, without creating it.

Syntax

var x = Math.PI; // Returns PI
var y = Math.sqrt(16); // Returns the square root of 16
For a tutorial about the Math object, read our JavaScript Math Object tutorial.

Math Object Properties

Property Description
E Returns Euler's number (approx. 2.718)
LN2 Returns the natural logarithm of 2 (approx. 0.693)
LN10 Returns the natural logarithm of 10 (approx. 2.302)
LOG2E Returns the base-2 logarithm of E (approx. 1.442)
LOG10E Returns the base-10 logarithm of E (approx. 0.434)
PI Returns PI (approx. 3.14)
SQRT1_2 Returns the square root of 1/2 (approx. 0.707)
SQRT2 Returns the square root of 2 (approx. 1.414)

Math Object Methods

Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y,x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle

Clock In Java Script

JavaScript Timing Events

With JavaScript, it is possible to execute some code after a specified time-interval. This is called timing events.
It's very easy to time events in JavaScript. The two key methods that are used are:
  • setTimeout() - executes a code some time in the future
  • clearTimeout() - cancels the setTimeout()
Note: The setTimeout() and clearTimeout() are both methods of the HTML DOM Window object.

The setTimeout() Method

Syntax

var t=setTimeout("javascript statement",milliseconds);
The setTimeout() method returns a value. In the syntax defined above, the value is stored in a variable called t. If you want to cancel the setTimeout() function, you can refer to it using the variable name.
The first parameter of setTimeout() can be a string of executable code, or a call to a function.
The second parameter indicates how many milliseconds from now you want to execute the first parameter.
Note: There are 1000 milliseconds in one second.

Example

When the button is clicked in the example below, an alert box will be displayed after 3 seconds.

Example

<html>
<head>
<script type="text/javascript">
function timeMsg()
{
var t=setTimeout("alertMsg()",3000);
}
function alertMsg()
{
alert("Hello");
}
</script>
</head>

<body>
<form>
<input type="button" value="Display alert box in 3 seconds"
onclick="timeMsg()" />
</form>
</body>
</html>

Try it yourself »

Example - Infinite Loop

To get a timer to work in an infinite loop, we must write a function that calls itself.
In the example below, when a button is clicked, the input field will start to count (for ever), starting at 0.
Notice that we also have a function that checks if the timer is already running, to avoid creating additional timers, if the button is pressed more than once:

Example

<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }
}
</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()">
<input type="text" id="txt" />
</form>
</body>
</html>

Try it yourself »


The clearTimeout() Method

Syntax

clearTimeout(setTimeout_variable)

Example

The example below is the same as the "Infinite Loop" example above. The only difference is that we have now added a "Stop Count!" button that stops the timer:

Example

<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }
}

function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()">
<input type="text" id="txt">
<input type="button" value="Stop count!" onclick="stopCount()">
</form>
</body>
</html>



<html>
<head>
<script type="text/javascript">
function timedText()
{
var t1=setTimeout("document.getElementById('txt').value='2 seconds!'",2000);
var t2=setTimeout("document.getElementById('txt').value='4 seconds!'",4000);
var t3=setTimeout("document.getElementById('txt').value='6 seconds!'",6000);
}
</script>
</head>

<body>
<form>
<input type="button" value="Display timed text!" onclick="timedText()" />
<input type="text" id="txt" />
</form>
<p>Click on the button above. The input field will tell you when two, four, and six seconds have passed.</p>
</body>

</html>


Friday, 30 March 2012

My Queries

To Count Tables in a Database :

SELECT COUNT(*) from information_schema.tables
WHERE table_type = 'base table' 


 FindTableNameInAllDatabase

CREATE PROCEDURE usp_FindTableNameInAllDatabase
@TableName VARCHAR(256)
AS
DECLARE @DBName VARCHAR(256)
DECLARE @varSQL VARCHAR(512)
DECLARE @getDBName CURSOR
SET @getDBName = CURSOR FOR
SELECT name
FROM sys.databases
CREATE TABLE #TmpTable (DBName VARCHAR(256),
SchemaName VARCHAR(256),
TableName VARCHAR(256))
OPEN @getDBName
FETCH NEXT
FROM @getDBName INTO @DBName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @varSQL = 'USE ' + @DBName + ';
INSERT INTO #TmpTable
SELECT '''+ @DBName + ''' AS DBName,
SCHEMA_NAME(schema_id) AS SchemaName,
name AS TableName
FROM sys.tables
WHERE name LIKE ''%' + @TableName + '%'''
EXEC (@varSQL)
FETCH NEXT
FROM @getDBName INTO @DBName
END
CLOSE @getDBName
DEALLOCATE @getDBName
SELECT *
FROM #TmpTable
DROP TABLE #TmpTable
GO
EXEC usp_FindTableNameInAllDatabase 'Address'
GO 


Sunday, 25 March 2012

SQL Injection


Security in software applications is an ever more important topic. In this article, I discuss various aspects of SQL Injection attacks, what to look for in your code, and how to secure it against SQL Injection attacks. Although the technologies used here are SQL Server 2000 and the .NET Framework, the general ideas presented apply to any modern data driven application framework, which makes attacks potentially possible on any type of application that depends on that framework.
What is a SQL Injection Attack?

A SQL Injection attack is a form of attack that comes from user input that has not been checked to see that it is valid. The objective is to fool the database system into running malicious code that will reveal sensitive information or otherwise compromise the server.

There are two main types of attacks. First-order attacks are when the attacker receives the desired result immediately, either by direct response from the application they are interacting with or some other response mechanism, such as email. Second-order attacks are when the attacker injects some data that will reside in the database, but the payload will not be immediately activated. I will discuss each in more detail later in this article.
An example of what an attacker might do

In the following example, assume that a web site is being used to mount an attack on the database. If you think about a typical SQL statement, you might think of something like:
Collapse

SELECT ProductName, QuantityPerUnit, UnitPrice
FROM Products
WHERE ProductName LIKE 'G%'

The objective of the attacker is to inject their own SQL into the statement that the application will use to query the database. If, for instance, the above query was generated from a search feature on a web site, then they user may have inserted the "G" as their query. If the server side code then inserts the user input directly into the SQL statement, it might look like this:
Collapse

string sql = "SELECT ProductName, QuantityPerUnit, UnitPrice "+
    "FROM Products " +
    "WHERE ProductName LIKE '"+this.search.Text+"%';
SqlDataAdapter da = new SqlDataAdapter(sql, DbCommand);
da.Fill(productDataSet);

This is all fine if the data is valid, but what if the user types something unexpected? What happens if the user types:
Collapse

' UNION SELECT name, type, id FROM sysobjects;--

Note the initial apostrophe; it closes the opening quote in the original SQL statement. Also, note the two dashes at the end; that starts a comment, which means that anything left in the original SQL statement is ignored.

Now, when the attacker views the page that was meant to list the products the user has searched for, they get a list of all the names of all the objects in the database and the type of object that they are. From this list, the attacker can see that there is a table called Users. If they take note of the id for the Users table, they could then inject the following:
Collapse

' UNION SELECT name, '', length FROM syscolumns
WHERE id = 1845581613;--

This would give them a list of the column names in the Users table. Now they have enough information to get access to a list of users, passwords, and if they have admin privileges on the web site.
Collapse

' UNION SELECT UserName, Password, IsAdmin FROM Users;--

Assume that there is a table called Users which has columns called UserName and Password, it is possible to union that with the original query and the results will be interpreted as if the UserName was the name of the product and the Password was the quantity per unit. Finally, because the attacker discovered that there is a IsAdmin column, they are likely to retrieve the information in that too.
Locking down

Security is something that needs to be tackled on many levels because a chain is only as strong as its weakest link. When a user interacts with a piece of software, there are many links in the chain; if the user is malicious, he could attempt to attack these links to find the weak point and attempt to break the system at that point. With this in mind, it is important that the developer does not become complacent about the security of the system because one security measure is put in place, or a set of security measures are in place on only one part of the system.

An intranet website that uses Windows authentication (it takes the user's existing credentials based on who they are logged in as) and is sitting inside the corporate network and unavailable to Internet users may give the impression that only authorised users can access the intranet web application. However, it is possible for an authenticated user to gain unauthorised access if the security is not taken much beyond that level. Some statistics support the suggestion that most security breaches are insider jobs rather than people attacking the system from outside.

With this in mind, it is important that even if the application permits only valid data through that has been carefully verified and cleaned up, other security measures are put in place. This is especially important between application layers where there may be an increased opportunity for spoofing of requests or results.

For example, if a web application were to request that the user choose a date, then it would be normal that the values for the date are checked in some JavaScript function on the web page before any data was posted back to the server. This improves the user experience by reducing the wait between lots of server requests. However, the value needs to be validated again on the server as it is possible to spoof the request with a deliberately crafted invalid date.
Encrypting data

Starting from the proposition that somehow an attacker has managed to break through all other defenses, what information is so sensitive that it needs to remain a secret? Candidates for encryption include user log in details or financial information such as credit card details.

For items such as passwords, the user's password can be stored as a "salted hash". What happens is that when a user creates a password, a randomly generated "salt" value is created by the application and appended to the password, and the password-and-salt are then passed through a one way encryption routine, such as found in the .NET Framework's helper class FormsAuthentication (HashPasswordForStoringInConfigFile method). The result is a salted hash which is stored in the database along with the clear text salt string.

The value of a salted hash is such that a dictionary attack is not going to work as each dictionary would have to be rebuilt appending the various salt values and recomputing the hash values for each item. While it is still possible to determine the password by brute force, the use of the salt (even though it is known) greatly slows down the process. The second advantage of the salt is that it masks any situations where two independent users happen to use the same password, as the salted hash value for each user would be different if given different salt values.
Least Privilege - Database account

Running an application that connects to the database using the database's administrator account has the potential for an attacker to perform almost limitless commands with the database. Anything an administrator can do, so can an attacker.

Using the example application above, an attacker could inject the following to discover the contents of the hard disk(s) on the server.

The first command is used to create a temporary store on the database and fill it with some data. The following injected code will create a table with the same structure as the result set of the extended stored procedure that will be called. It then populates the table with the results of the extended stored procedure.
Collapse

'; CREATE TABLE haxor(name varchar(255), mb_free int);
INSERT INTO haxor  EXEC master..xp_fixeddrives;--

A second injection attack has to take place in order to get the data out again.
Collapse

' UNION SELECT name, cast((mb_free) as varchar(10)), 1.0 FROM haxor;--

This returns the name of the disks with the available capacity in megabytes. Now that the drive letters of the disks are known, a new injection attack can take place in order to find out what is on those disks.
Collapse

'; DROP TABLE haxor;CREATE TABLE haxor(line varchar(255) null);
INSERT INTO haxor EXEC master..xp_cmdshell 'dir /s c:';--

And again, a second injection attack is used to get the data out again.
Collapse

' UNION SELECT line, '', 1.0 FROM haxor;--

xp_cmdshell, by default, is only executable by a user with the sysadmin privilege, such as sa, and CREATE TABLE is only available to sysadmin, db_dbowner or db_dlladmin users. It is therefore important to run the application with the least privileges that are necessary in order to perform the necessary functions of the application.
Least Privilege - Process account

When an instance of SQL Server is installed on a computer, it creates a service that runs in the background and processes the commands from applications that are connected to it. By default, this service is installed to use the Local System account. This is the most powerful account on a Windows machine, it is even more powerful than the Administrator account.

If an attacker has an opportunity to break out of the confines of SQL Server itself, such as through the extended procedure xp_cmdshell, then they could gain unrestricted access to the machine that the SQL Server is on.

Microsoft recommends that during the installation of SQL Server, the service is given a domain account which has the permissions set to only the necessary resources. That way, an attacker is confined by the permission set needed to run SQL Server.
Cleaning and Validating input

In many applications, the developer has side-stepped the potential use of the apostrophe as a way to get access to the system by performing a string replace on the input given by the user. This is useful for valid reasons, such as being able to enter surnames such as "O'Brian" or "D'Arcy", and so the developer may not even realise that they have partly defeated a SQL injection attack. For example:
Collapse

string surname = this.surnameTb.Text.Replace("'", "''");
string sql = "Update Users SET Surname='"+surname+"' "+
    "WHERE id="+userID;

All of the previous injection attack examples would cease to work given a scenario like this.

However, many applications need the user to enter numbers and these don't need to have the apostrophes escaped like a text string. If an application allows the user to review their orders by year, the application may execute some SQL like this:
Collapse

SELECT * FROM Orders WHERE DATEPART(YEAR, OrderDate) = 1996

And in order for the application to execute it, the C# code to build the SQL command might look like this:
Collapse

string sql = "SELECT * FROM Orders WHERE DATEPART(YEAR, OrderDate) = "+
    this.orderYearTb.Text);

It becomes easy to inject code into the database again. All the attackers need to do in this instance is start their attack with a number, then they inject the code they want to run. Like this:
Collapse

0; DELETE FROM Orders WHERE ID = 'competitor';--

It is therefore imperative that the input from the user is checked to determine that it really is a number, and in the valid range. For instance:
Collapse

string stringValue = orderYearTb.Text;
Regex re = new Regex(@"D");
Match m = re.Match(someTextBox.Text);
if (m.Success)
{
    // This is NOT a number, do error processing.

}
else
{
    int intValue = int.Parse(stringValue);
    if ((intValue < 1990) || (intValue > DateTime.Now.Year))
    {
        // This is out of range, do error processing.

    }
}

Second-Order Attacks

A second-order attack is one where the data lies dormant in the database until some future event occurs. It often happens because once data is in the database, it is often thought of as being clean and is not checked again. However, the data is frequently used in queries where it can still cause harm.

Consider an application that permits the users to set up some favourite search criteria. When the user defines the search parameters, the application escapes out all the apostrophes so that a first-order attack cannot occur when the data for the favourite is inserted into the database. However, when the user comes to perform the search, the data is taken from the database and used to form a second query which then performs the actual search. It is this second query which is the victim of the attack.

For example. If the user types the following as the search criteria:
Collapse

'; DELETE Orders;--

The application takes this input and escapes out apostrophe so that the final SQL statement might look like this:
Collapse

INSERT Favourites (UserID, FriendlyName, Criteria)
VALUES(123, 'My Attack', ''';DELETE Orders;--')

which is entered into the database without problems. However, when the user selects their favourite search, the data is retrieved to the application, which forms a new SQL command and executes that. For example, the C# code might look like:
Collapse

// Get the valid user name and friendly name of the favourite

int uid = this.GetUserID();
string friendlyName = this.GetFriendlyName();

// Create the SQL statement to retrieve the search criteria

string sql = string.Format("SELECT Criteria FROM Favourites "+
    "WHERE UserID={0} AND FriendlyName='{1}'",
    uid, friendlyName);
SqlCommand cmd = new SqlCommand(sql, this.Connection);
string criteria = cmd.ExecuteScalar();

// Do the search

sql = string.Format("SELECT * FROM Products WHERE ProductName = '{0}'",
    criteria);
SqlDataAdapter da = new SqlDataAdapter(sql, this.Connection);
da.Fill(this.productDataSet);

The second query to the database, when fully expanded, now looks like this:
Collapse

SELECT * FROM Products WHERE ProductName = ''; DELETE Orders;--

It will return no results for the expected query, but the company has just lost all of their orders.
Parameterised Queries

SQL Server, like many database systems, supports a concept called parameterised queries. This is where the SQL Command uses a parameter instead of injecting the values directly into the command. The particular second-order attack above would not have been possible if parameterised queries had been used.

Where the application developer would have constructed a SqlCommand object like this:
Collapse

string cmdText=string.Format("SELECT * FROM Customers "+
    "WHERE Country='{0}'", countryName);
SqlCommand cmd = new SqlCommand(cmdText, conn);

A parameterised query would look like this:
Collapse

string commandText = "SELECT * FROM Customers "+
    "WHERE Country=@CountryName";
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.Parameters.Add("@CountryName",countryName);

The value is replaced by a placeholder, the parameter, and then the parameter's value is added to the Parameters collection on the command.

While many second-order attacks can be prevented by using parameters, they can only be used in places were a parameter is permitted in the SQL statement. The application may return a variable sized result set based on user preference. The SQL statement would include the TOP keyword in order to limit the result set, however, in SQL Server 2000, TOP can only accept literal values so the application would have to inject that value into the SQL command to obtain that functionality. For example:
Collapse

string sql = string.Format("SELECT TOP {0} * FROM Products", numResults);

Using Stored Procedures

Stored Procedures add an extra layer of abstraction in to the design of a software system. This means that, so long as the interface on the stored procedure stays the same, the underlying table structure can change with no noticeable consequence to the application that is using the database. This layer of abstraction also helps put up an extra barrier to potential attackers. If access to the data in SQL Server is only ever permitted via stored procedures, then permission does not need to be explicitly set on any of the tables. Therefore, none of the tables should ever need to be exposed directly to outside applications. For an outside application to read or modify the database, it must go through stored procedures. Even though some stored procedures, if used incorrectly, could potentially damage the database, anything that can reduce the attack surface is beneficial.

Stored procedures can be written to validate any input that is sent to them to ensure the integrity of the data beyond the simple constraints otherwise available on the tables. Parameters can be checked for valid ranges. Information can be cross checked with data in other tables.

For example, consider a database that has the user details for a website, this includes the user name and password. It is important that an attacker is unable to get a list of passwords or even one password. The stored procedures are designed so that a password can be passed in, but it will never put a password in any result set. The stored procedures for registering and authenticating a user for the website might be:

    * RegisterUser
    * VerifyCredentials
    * ChangePassword

RegisterUser takes the user name and password as parameters (possibly along with other information that is necessary for registering on the website) and returns the UserID.

VerifyCredentials would be used for logging into the site by accepting the user name and the password. If there is a match the UserID is returned, if not then a NULL value.

ChangePassword would take the UserID, the old password and the new password. If the UserID and the password match, the password can be changed. A value that indicates success or failure is returned.

The above example shows that the password is always contained in the database and is never exposed.
Stored Procedure Caveat

While stored procedures seem to be a wonderful panacea against injection attacks, this is not necessarily the case. As mentioned above, it is important to validate data to check that it is correct and it is a definite benefit of stored procedures that they can do this; however, it is doubly important to validate data if the stored procedure is going to use EXEC(some_string) where some_string is built up from data and string literals to form a new command.

For instance, if the stored procedure is to modify the data model of the database, such as creating a table, the code may be written as follows:
Collapse

CREATE PROCEDURE dbo.CreateUserTable
    @userName sysname
AS
    EXEC('CREATE TABLE '+@userName+
        ' (column1 varchar(100), column2 varchar(100))');
GO

It is obvious that whatever @userName contains will be appended to the CREATE statement. An attacker could inject into the application some code that sets the user name to be:
Collapse

a(c1 int); SHUTDOWN WITH NOWAIT;--

which will immediately stop the SQL Server without waiting for other requests to complete.

It is important to validate the input to ensure that no illegal characters are present. The application could be set to ensure that spaces are not permitted as part of the user name and this could be rejected before it ever got as far as constructing the CREATE statement.

If the stored procedure is going to construct a SQL command based on an existing object, such as a table or view, then it should check that such an object exists. For instance:
Collapse

CREATE PROCEDURE dbo.AlterUserTable
    @userName sysname
AS
    IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_SCHEMA = 'dbo'
        AND TABLE_TYPE = 'BASE TABLE'
        AND TABLE_NAME = @userName)
    BEGIN
        // The table is known to exist
        // construct the appropriate command here
    END
GO

Error Messages

Error messages are useful to an attacker because they give additional information about the database that might not otherwise be available. It is often thought of as being helpful for the application to return an error message to the user if something goes wrong so that if the problem persists they have some useful information to tell the technical support team. Applications will often have some code that looks like this:
Collapse

try
{
    // Attempt some database operation

}
catch(Exception e)
{
    errorLabel.Text = string.Concat("Sorry, your request failed. ",
        "If the problem persists please report the following message ",
        "to technical support", Environment.Newline, e.Message);
}

A better solution that does not compromise security would be to display a generic error message that simply states an error has occurred with a unique ID. The unique ID means nothing to the user, but it will be logged along with the actual error diagnostics on the server which the technical support team has access to. The code above would change to something like this instead:
Collapse

try
{
    // Attempt some database operation

}
catch(Exception e)
{
    int id = ErrorLogger.LogException(e);
    errorLabel.Text = string.Format("Sorry, your request Failed. "+
        "If the problem persists please report error code {0} "
        "to the technical support team.", id);
}

Summary

    * Encrypt sensitive data.
    * Access the database using an account with the least privileges necessary.
    * Install the database using an account with the least privileges necessary.
    * Ensure that data is valid.
    * Do a code review to check for the possibility of second-order attacks.
    * Use parameterised queries.
    * Use stored procedures.
    * Re-validate data in stored procedures.
    * Ensure that error messages give nothing away about the internal architecture of the application or the database.

What should you required to learn machine learning

  To learn machine learning, you will need to acquire a combination of technical skills and domain knowledge. Here are some of the things yo...