Thursday, 22 November 2012

IE Css CSS3 Solutions for Internet Explorer Style Fixed to Developer

CSS3 is probably the hottest trend in web design right now, allowing developers the opportunity to implement a number of solutions into their projects with some very straightforward CSS while avoiding having to resort to nonsemantic markup, extra images, and complex JavaScript. Unfortunately, it’s not a surprise that Internet Explorer, even in its most recent version, still does not support the majority of the properties and features introduced in CSS3.
Experienced developers understand that CSS3 can be added to new projects with progressive enhancement in mind. This ensures that content is accessible while non-supportive browsers fall back to a less-enhanced experience for the user.
IE
But developers could face a situation where a client insists that the enhancements work cross-browser, demanding support even for IE6. In that case, I’ve collected together a number of options that developers can consider for those circumstances where support for a CSS3 feature is required for all versions of Internet Explorer (IE6, IE7, & IE8 — all of which are still currently in significant use).
(Smashing’s note: If you are looking for a good book on mobile, this is the one. Our brand new book on best design and coding practices for mobile, Responsive Web design and UX design for mobile. Pre-order now and save 20%!)

Opacity / Transparency

I think all developers are baffled at why Internet Explorer still fails to support this very popular (albeit troublesome) property. It’s been around so long, that we often forget that it’s actually a CSS3 property. Although IE doesn’t offer support for the opacity property, it does offer similar transparency settings via the proprietary filter property:

THE SYNTAX

1#myElement {
2    opacity: .4; /* other browsers  and IE9+ */
3    filter: alpha(opacity=40); /* IE6+ */
4    filter: progid:DXImageTransform.Microsoft.Alpha(opacity=40); /* IE6+ */
5    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(opacity=40)"; /* this works in IE8 only */
6}
You really only need the second line, which works in all versions of Internet Explorer. But if for some reason you needed the opacity setting to apply only to IE8, and not to IE6/7, then you can use the last line, which the older versions don’t recognize. The third line is just another way to do basically the same thing, but with a more convoluted syntax.
The opacity value at the end of each IE line works basically the same way that the opacityproperty does, taking a number from 0 to 100 (the opacity property takes a two-digit number from 0 to 1, so “44″ for IE would be “0.44″ for the others). Also, as many have experienced when using opacity (even when using the standard method), the opacity settings will be inherited by all child elements, for which there is no easy workaround.

THE DEMONSTRATION

This element has a solid blue background color (#0000FF), but is 60% transparent, making it appear light blue in all browsers
This is the same element without the opacity settings.

THE DRAWBACKS

  • The filter property is a Microsoft-only property, so your CSS won’t validate
  • As is the case for the opacity property, the IE filter causes all child elements to inherit the opacity
  • There could be performance issues with the IE filters

Rounded Corners (border-radius)

The border-radius property (more commonly referred to as CSS3 rounded corners) is another popular CSS3 enhancement. This property has allowed developers to avoid the headache of bloated JavaScript or extra positioned elements to achieve the same effect. But once again, Microsoft doesn’t want to cooperate, so IE doesn’t have any support for this property.
Fortunately, at least one person has come up with a very usable workaround that can be used in an IE-only stylesheet. Remiz Rahnas of HTML Remix has created an HTC file calledCSS Curved Corner that can be downloaded off Google Code.
The great thing about this piece of code is that it doesn’t require any extra maintenance if you adjust the amount of radius on your rounded corners. You just link to the file in your CSS, and the script will automatically parse your CSS to find the correct radius value from the standard border-radius property.

THE SYNTAX

Here’s what your code might look like:
1.box-radius {
2    border-radius: 15px;
3    behavior: url(border-radius.htc);
4}
The way it works is pretty straightforward, as shown above. Ideally, however, you would apply the behavior property in an IE-only stylesheet, using the same selector in your CSS, so the code knows where to get the radius value from.

THE DEMONSTRATION

Because this technique requires use of an external HTC file, you can view the demo at this location.

THE DRAWBACKS

  • The HTC file is 142 lines (minifying or GZipping would help, but it’s still extra bloat)
  • The behavior property will make your CSS invalid
  • Your server needs to be able to load HTC files for this technique to work
  • IE8 seems to have some trouble in some circumstances when the HTC file forces the curved element to have a negative z-index value

Box Shadow

The box-shadow property is another useful CSS3 feature that will even add a curved box shadow naturally to an element that uses the border-radius property. IE doesn’t supportbox-shadow, but a filter is available that offers a close replication.
It should be noted that the box-shadow property has been removed from the CSS3 Backgrounds and Borders Module, so its future in CSS3 seems to be a little uncertain right now.

THE SYNTAX

1.box-shadow {
2    -moz-box-shadow: 2px 2px 3px #969696; /* for Firefox 3.5+ */
3    -webkit-box-shadow: 2px 2px 3px #969696; /* for Safari and Chrome */
4    filter: progid:DXImageTransform.Microsoft.Shadow(color='#969696', Direction=145, Strength=3);
5}
As shown above, in addition to the proprietary WebKit and Mozilla properties, you can add a shadow filter that works in all versions of Internet Explorer.

THE DEMONSTRATION

This element has a drop shadow that works in Internet Explorer.

THE DRAWBACKS

  • The settings for the IE shadow filter do not match those of the other proprietary properties, so in order to make it look the same, you have to fiddle with the values until you get it right, which can cause maintenance headaches
  • The filter property doesn’t validate, but neither do the WebKit and Mozilla properties, so this is a drawback in all browsers

Text Shadow

Adding drop shadows to text elements has been practiced in both print and web design for years. On the web, this is normally done with images and occasionally with text duplication combined with positioning. CSS3 allows developers to easily add shadows to text using a simple and flexible text-shadow property.
Unfortunately, there doesn’t seem to be an easy way to add a text shadow in Internet Explorer — even with the use of proprietary filters. To deal with this problem, a Dutch front-end developer named Kilian Valkhof has written a jQuery plugin that implements text shadows in Internet Explorer.

THE SYNTAX

First, in your CSS, you would set the text-shadow property:
1.text-shadow {
2    text-shadow: #aaa 1px 1px 1px;
3}
The values specify the shadow color, position on the horizontal axis, position on the vertical axis, and the amount of blur.
After including the jQuery library and the plugin in your document, you can call the plugin with jQuery:
1// include jQuery library in your page
2// include link to plugin in your page
3
4$(document).ready(function(){
5    $(".text-shadow").textShadow();
6});
The plugin also allows the use of parameters to override the CSS. See the plugin author’s original web page for more details on the parameters.
Although there is a cross-browser jQuery plugin that applies drop shadows, the one I’m demonstrating above actually utilizes the CSS3 value that’s already set in your CSS, so it has the advantage of working along with the standard CSS setting for text shadows, whereas the other plugin needs to be set independently.

THE DEMONSTRATION

Because this technique requires use of the jQuery library and an external plugin file, you can view the demo at this location.

THE DRAWBACKS

There are some significant drawbacks to this method that make it very unlikely to ever be practical. You’re probably better off creating an image to replace the text for IE instead.
  • In order to make the shadow look almost the same in IE, you need to use different settings in an IE-only stylesheet, adding to development and maintenance time
  • Requires that you add the jQuery library, in addition to a 61-line plugin file (GZipping or minifying would help)
  • The IE version of the shadow never looks exactly the same as the other browsers
  • When using the overriding parameters, the plugin seems to be rendered somewhat useless, displaying a big ugly shadow that won’t change with new values
  • Unlike the CSS3 version, the plugin doesn’t support multiple shadows
  • For some reason, in order to get it to work in IE8, you need to give the element a z-index value

Gradients

Another practical and time-saving technique introduced in CSS3 is the ability to create custom gradients as backgrounds. Although Internet Explorer doesn’t support gradients of the CSS3 variety, it’s pretty easy to implement them for the IE family using proprietary syntax.

THE SYNTAX

To declare a gradient that looks the same in all browsers, including all versions of Internet Explorer, use the CSS shown below (the last two lines are for IE):
1#gradient {
2    background-image: -moz-linear-gradient(top, #81a8cb, #4477a1); /* Firefox 3.6 */
3    background-image: -webkit-gradient(linear,left bottom,left top,color-stop(0,#4477a1),color-stop(1, #81a8cb)); /* Safari & Chrome */
4    filter:  progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#81a8cb', endColorstr='#4477a1'); /* IE6 & IE7 */
5    -ms-filter:"progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#81a8cb', endColorstr='#4477a1')"; /* IE8 */
6}
For the IE filters, the GradientType can be set to “1″ (horizontal) or “0″ (vertical).

THE DEMONSTRATION

This element has a linear gradient that works in Internet Explorer.

THE DRAWBACKS

Some of the usual drawbacks apply to gradients created with the IE-only filter, along with some other problems.
  • Your CSS won’t validate, although that’s also true for the WebKit and Mozilla values
  • Different code is needed for IE8, adding to maintenance time
  • The WebKit and Mozilla gradients allow for “stops” to be declared; this doesn’t seem to be possible with the IE gradient, limiting its flexibility
  • IE’s filter doesn’t seem to have a way to declare “radial” gradients, which WebKit and Mozilla support
  • For a gradient to be visible in IE, the element with the gradient must have layout

Transparent Background Colors (RGBA)

CSS3 offers another method to implement transparency, doing so through an alpha channel that’s specified on a background color. Internet Explorer offers no support for this, but this can be worked around.

THE SYNTAX

For the CSS3-compliant browsers, here’s the syntax to set an alpha channel on the background of an element:
1#rgba p {
2    background: rgba(98, 135, 167, .4);
3}
With the above CSS, the background color will be set to the RGB values shown, plus the optional “alpha” value of “.4″. To mimic this in Internet Explorer, you can use the proprietary filter property to create a gradient with the same start and end color, along with an alpha transparency value. This would be included in an IE-only stylesheet, which would override the previous setting.
1#rgba p {
2    filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#886287a7', endColorstr='#886287a7');
3}
The “gradient” will look exactly the same in IE as in other browsers, duplicating the RGBA transparency effect.

THE DEMONSTRATION

This first example below will work in browsers that support RGBA colors. The second example will only work in Internet Explorer.
This paragraph has a background color with a 40% opacity setting declared using RGBA (doesn’t work in IE).
This paragraph has an IE-only filter applied to mimic RGBA transparency (only works in IE).

THE DRAWBACKS

  • The filter property is not valid CSS
  • Requires an extra line of CSS in an IE-only stylesheet
  • The element needs to have layout
Note: Initially, I had used a PNG image method to achieve this effect, but apparently it was working only partially in IE7 and IE8, and required a PNG-hack for IE6, so I tried the method given by Liam and Matias in the comments and this seems to work better. The PNG method is another option, but seems to be more troublesome, and has more drawbacks.

Multiple Backgrounds

This is another CSS3 technique that, when widely supported, could prove to be a very practical addition to CSS development. Currently, IE and Opera are the only browsers that don’t support this feature. But interestingly, IE as far back as version 5.5 has allowed the ability to implement multiple backgrounds on the same element using a filter.

THE SYNTAX

You might recall trying to hack a PNG in IE6 and noticing the image you were trying to hack appearing twice, which you had to remove by adding background: none, then applying the filter. Well, using the same principle, IE allows two background images to be declared on the same element.
To use multiple backgrounds in Firefox, Safari, and Chrome, here’s the CSS:
1#multi-bg {
2    background: url(images/bg-image-1.gif) center center no-repeat, url(images/bg-image-2.gif) top left repeat;
3}
To apply two backgrounds to the same element in IE, use the following in an IE-only stylesheet:
1#multi-bg {
2    background: transparent url(images/bg-image-1.gif) top left repeat;
3    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader (src='images/bg-image-2.gif', sizingMethod='crop'); /* IE6-8 */
4    -ms-filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/bg-image-2.gif', sizingMethod='crop')"; /* IE8 only */
5}

THE DEMONSTRATION

The box below shows multiple backgrounds in Chrome, Firefox, and Safari (you won’t see anything in IE):
The next box shows multiple backgrounds in Internet Explorer 6-8 (you’ll only see a single background in other browsers):

THE DRAWBACKS

  • Your CSS will be invalid
  • The second background image applied using the filter property will always be in the top left, and cannot repeat, so this method is extremely inflexible and can probably only be used in a limited number of circumstances
  • In order to get the element to center (as in other browsers), you have to create an image with the exact amount of whitespace around it, to mimic the centering, as I’ve done in the demonstration above
  • The AlphaImageLoader filter causes performance issues, as outlined here

Element Rotation (CSS Tranformations)

CSS3 has introduced a number of transformation and animation capabilities, which some have suggested are out of place in CSS. Nonetheless, there is a way to mimic element rotation in Internet Explorer, albeit in a limited fashion.

THE SYNTAX

To rotate an element 180 degrees (that is, to flip it vertically), here is the CSS3 syntax:
1#rotate {
2    -webkit-transform: rotate(180deg);
3    -moz-transform: rotate(180deg);
4}
To create the exact same rotation in Internet Explorer, you use a proprietary filter:
1#rotate {
2    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2);
3}
The value for the rotation can be either 1, 2, 3, or 4. Those numbers represent 90, 180, 270, or 360 degrees of rotation respectively.

THE DEMONSTRATION

The element below should appear upside down in Internet Explorer, having a rotation of 180 degrees set via the filter property. To demonstrate this more emphatically, I’ve applied a 3px solid gray “bottom” border, which should appear at the top of the element.
This element is rotated 180 degrees in Internet Explorer.

THE DRAWBACKS

  • Your CSS won’t validate, although that’s also true for the WebKit and Mozilla code
  • While the Mozilla and WebKit code allows for rotation changes to increment by a single degree, the IE filter only permits 4 stages of rotation, minimizing its flexibility
Update: As pointed out in the comments, IE does allow the ability to rotate objects with the same flexibility as the CSS3 methods. To explain the method here is too complex, but the CSS3, please project by Paul Irish has implemented this method into its code generator, so you can use that to create the IE-compatible code for CSS3 rotations.

Friday, 16 November 2012

Preventing SQL Injection in ASP.NET

Preventing SQL Injection in ASP.NET


I, and many other contributors to the forums at www.asp.net find examples of code posted on a daily basis that are vulnerable to SQL Injection attacks. We continue to exhort beginners (and some more experienced programmers) to code against them. This article examines just how serious a flaw vulnerable coding can be, and what you should do about it.

What is SQL Injection?
To answer this, let's look at a typical piece of code used in millions of web sites which attempts to validate a user who has tried to log in to a protected area of a web site:
  
protected void Button1_Click(object sender, EventArgs e)
{
  string connect = "MyConnString";
  string query = "Select Count(*) From Users Where Username = '" + UserName.Text + "' And Password = '" + Password.Text + "'";
  int result = 0;
  using (var conn = new SqlConnection(connect))
  {
    using (var cmd = new SqlCommand(query, conn))
    {
      conn.Open();
      result = (int)cmd.ExecuteScalar();
    }
  }
  if (result > 0)
  {
    Response.Redirect("LoggedIn.aspx");
  }
  else
  {
    Literal1.Text = "Invalid credentials";
}
  

This is a commonly found piece of code that runs as the result of a ButtonClick event. It connects to the database and executes some SQL against a SQL Server database that returns the number of rows where the username and password combination supplied by the user matches a row in the database. If the result is at least one matching row, the user is logged in. At runtime, the values entered by the user are merged dynamically with the SQL string, to create a valid SQL command which is then executed against the database:
The values supplied above were "Admin" for the user name, and "Let_Me_In" for the password. The image illustrates that the merging of those values with the core SQL has worked rather nicely. You will only get logged in if there is a matching row in the database. Simples. Now look at this:
This was achieved simply by entering ' or '1' = '1 into both the username textbox and the password textbox. If you study the SQL that has resulted from concatenating those user values with the core SQL, you will probably be able to see that it will always match at least one row. In fact, it will match all rows, so the variable result will be > 0. Sometimes, coders don't return a count. They return user's details so they can use them for allowing further permissions or similar. This SQL will return the first row that matches, which will be the first row in the table generally. Often, this is the admin account that you set up when developing the site, and has all privileges.
This is SQL Injection. Basically, additional SQL syntax has been injected into the statement to change its behaviour. The single quotes are string delimiters as far as T-SQL is concerned, and if you simply allow users to enter these without managing them, you are asking for potential trouble. Quite often, I see well meaning people advise beginners to "escape" the quotes, using a string.Replace() method such as this:
var username = UserName.Text.Replace("'", "''");
var password = Password.Text.Replace("'", "''");
string query = "Select * From Users Where Username = '" + username + "' And Password = '" + password + "'";


And indeed that will have the desired effect:
The first OR clause will never be true. Job done. However, it does not protect against all avenues of attack. Consider the very common scenario where you are querying the database for an article, product or similar by ID. Typically, the ID is stored as a number - most of them are autogenerated by the database. The code will usually look like this:
string connect = "MyConnString";
string query = "Select * From Products Where ProductID = " + Request["ID"];

using (var conn = new SqlConnection(connect))
{
  using (var cmd = new SqlCommand(query, conn))
  {
    conn.Open();
    //Process results
  }
}

Now, in this case, the value for Request["ID"] could come from a posted form, or a querystring value - perhaps from a hyperlink on a previous page. It's easy for a malicious user to amend a querystring value. In the example caught by the VS debugger below, I just put ;Drop Table Admin-- on the end of the querystring before requesting the page:
The result, again is a legitimate SQL statement that will be run against the database. And the result will be that my Admin table will be deleted. You might be wondering how a hacker will know the names of your tables. Chances are they don't. But think about how you name your database objects. They are bound to be commonsense names that reflect their purpose. It doesn't take long to guess. And of course, if you are using ASP.NET Membership out-of-the-box, the aspnetdb.mdf schema is available to anyone. But before you start changing all your database table names to something really obscure, that is not the answer. Dictionary attacks (where random strings are generated) are common. Finally, it takes just one disgruntled person (a former colleague?) who knows the obscure names you have used to undo all your effort.
So far, the examples have shown attacks that will only really cause an inconvenience. Someone might break into your Content Management System and start defacing your site, or they might make parts of the database disappear. No big deal - a database restore from a backup will put things right (you DO backup your database, don't you?). Or they might help themselves to some free shipments, or discover secret information that your client would prefer their competitors didn't know. Or it could be a lot worse. Have a look at this document, which describes a certain type of penetration test.
Penetration tests are tests designed to identify security loopholes in applications, systems and networks. This particular test makes use of the SQL Server xp_cmdshell system stored procedure. xp_cmdshell is extraordinarily powerful, and assuming that the user has the right privileges, effectively gives them total control over the machine that the SQL Server is on, as well as potentially others in the network. Now, imagine being responsible for creating the loophole through which someone was able to create an FTP site on your web server's network, and use it to store material they would not like the police to know about. Or wiped the entire server. Some people think they don't need to worry about this type of thing because their application is intended only to run on a private Intranet. I have however seen servers hosting this type of applciation being affected.
The Prevention
OK. I'm sure that by now, you can see that the only sensible thing to do is to prevent any possibility of your application being subject to successful SQL Injection attacks. So now we will turn to preventing them. I have seen plenty of advice like this: http://forums.asp.net/t/1254125.aspx, where the suggestion is to create a Black List if all T-SQL keywords and punctuation, and screen user input for the presence of it. If it exists, throw an error, or similar. It's not a good approach in my view. There are two potential problems with this that I can see. The first is that there may be legitimate reasons why users need to post values included in the blacklist. How many users will become frustrated in their attempt to post a comment that includes "At the end of the day..."? Most T-SQL keywords are also in use in every day language. What if they aren't alowed to submit an @ symbol? Or a semi-colon? The second problem is what happens if Microsoft makes changes to the syntax of T-SQL? Do you go round all the applications you have built over the years and rebuild your black list functions? You might think that the chances of Microsoft making changes are so slim that you shouldn't worry about this. However, until the middle of last year, neither "var" nor "=>" would have done anything in C# except generate a compiler error. You certainly won't get any guarantees from Microsoft against making changes to T-SQL. The real way to prevent SQL Injection attacks is the use of Parameter Queries.
Parameter Queries
Parameters in queries are placeholders for values that are supplied to a SQL query at runtime, in very much the same way as parameters act as placeholders for values supplied to a C# method at runtime. And, just as C# parameters ensure type safety, SQL parameters do a similar thing. If you attempt to pass in a value that cannot be implicitly converted to a numeric where the database field expects one, exceptions are thrown. In a previous example where the ProductID value was tampered with to append a SQL command to DROP a table, this will now cause an error rather than get executed because the semicolon and text cannot be converted to a number.
The SqlCommand class represents a SQL query or stored procedure to be executed against the database. It has a Parameters property which is a collection of SqlParameter objects. For each parameter that appears in the SQL statement, you need to add a Parameter object to the collection. This is probably simpler to explain through code, so taking the ProductID example as a starting point, here's how to rewrite the code:
protected void Page_Load(object sender, EventArgs e)
{
  var connect = ConfigurationManager.ConnectionStrings["NorthWind"].ToString();
  var query = "Select * From Products Where ProductID = @ProductID";
  using (var conn = new SqlConnection(connect))
  {
    using (var cmd = new SqlCommand(query, conn))
    {
      cmd.Parameters.Add("@ProductID", SqlDbType.Int);
      cmd.Parameters["@ProductID"].Value = Convert.ToInt32(Request["ProductID"]);
      conn.Open();
      //Process results
    }
  }
}


The connection string has been defined in the web.config file, and is obtained using the System.Configuration.ConfigurationManager class which provides acces to items in the web.config file. In this case, it retrieves the value of the item in the connectionstrings area with the name "NorthWind". The SQL query is declared with a parameter: @ProductID. All parameters are prefixed with the @ sign. The connection object is declared next, with the connection string passed into the constructor. It's in a using block, which ensures that the connection is closed and disposed of without have to explicitly type code to manage that. The same is true of the SqlCommand object.
Adding the parameter to the SqlCommand.Parameters collection is relatively straightforward. there are two methods - the Add() method and the AddWithValue() method. The first of these has a number of overloads. I've used the Add(String, SqlDbType) option and then applied the value separately. It could be written all on one line like this:
cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = Convert.ToInt32(Request["ProductID"]);

Alternatively, I could use the AddWithValue(string, object) option like this:
protected void Page_Load(object sender, EventArgs e)
{
  var connect = ConfigurationManager.ConnectionStrings["NorthWind"].ToString();
  var query = "Select * From Products Where ProductID = @ProductID";
  using (var conn = new SqlConnection(connect))
  {
    using (var cmd = new SqlCommand(query, conn))
    {
      cmd.Parameters.AddWithValue("@ProductID", Convert.ToInt32(Request["ProductID"]);

      conn.Open();
      //Process results
    }
  }
}


The choice is up to you, but most professionals prefer to use one of the Add() methods where the SQL data type (and length, where appropriate) is specified. This reduces the chance of sub-optimal conversion causing performance issues on the server. It also ensures that the value being passed is of the right type in the application, rather than getting SQL Server to have to deal with it and report back errors. Having said all that, most samples on this site use the AddWithValue() option for readability.
When ADO.NET parameterised queries are sent to SQL Server, they are executed via the system stored procedure sp_executesql:
exec sp_executesql N'Select * From Products Where ProductID = @ProductID',N'@ProductID int',@ProductID=13

This passes in the SQL statement, followed (in this case) by the data type, and finally with the value that the parameter in the SQL statement must use. If the value is a string, any SQL syntax it might contain is treated as part of the literal string, and not as part of the SQL statement, and this is how SQL injection is prevented.
If a string is provided where a numeric is expected, the application will throw an error. For this reason, you should be validating all input for type and range before even attempting to pass it to a parameter.
There is one other benefit to be had by using parameters, and that is one of performance. When SQL Server is presented with a SQL statement, it first checks its cache for an identical statement. If it finds one, it retrieves an optimised execution plan which will ensure that the statement is executed as efficiently as possible. If it cannot find an exact match, it goes through the process of creating a plan to cache prior to using that plan to execute the statement. You can see that the first part of the sp_executesql call contains the statement, and that it will always be the same. All subsequent uses of it will use the cached optimised plan. If this statement was dynamically generated using string concatenation, and the ProductID varied each time, an execution plan would need to be created and stored for every value of ProductID. "...WHERE ProductID = 13" is not the same as "...WHERE ProductID = 96".
Stored Procedures
It always interests me that whenever the subject of preventing SQL injection comes up in the www.asp.net forums, at least one person contributes the assertion that you must use stored procedures to make use of parameters. As I have demonstrated above, this is not true. However, if you do use stored procedures the code above can be used with just two amendments: you need to pass the name of the stored procedure instead of the SQL statement, and you must set the CommandType to CommandType.StoredProcedure. It's omitted at the moment because the default is CommandType.Text. Here's the revised code for a stored procedure which I shall call GetProductByID:
var connect = ConfigurationManager.ConnectionStrings["NorthWind"].ToString();
var query = "GetProductByID";

using (var conn = new SqlConnection(connect))
{
  using (var cmd = new SqlCommand(query, conn))
  {
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = Convert.ToInt32(Request["ProductID"]);
    conn.Open();
    //Process results
  }
}


LINQ to SQL, Entity Framework, OleDb and ODBC
Both LINQ to SQL and the Entity Framework generate parameterised SQL commands out-of-the-box, providing protection against SQL Injection with no additional effort. This is indeed true of many other Object Relational Mappers (nHibernate etc). If you are using MS Access, SQL injection is not such a problem, as Access is very limited in what it allows. For example, you cannot batch statements so the DROP Table example will not work. Nevertheless, the login hack will work, so you should still use parameters. A much fuller description of how OleDb parameters work with Access is given here:http://www.mikesdotnetting.com/Article/26/Parameter-Queries-in-ASP.NET-with-MS-Access. It should be noted that both OleDb an ODBC parameters work based on position, whereas the examples in this article that use SqlClient all work on matching the name of the parameters, and position is not important.
How other database systems are affected varies, but it is always best to check their documentation. Nevertheless, using parameterised queries where they are supported by the database system is a sure-fire way to make your application SQL Injection proof. You really have no excuse.

Toturial for Software Developer

http://www.udemy.com/courses/popular


This an Tutorial for software develop and Intrestet learning people. try this. Use this to your career..