08.01.2015 Views

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

90<br />

CHAPTER 4 ■ DATA BINDING WITH <strong>ASP</strong>.<strong>NET</strong><br />

Using Parameters in Comm<strong>and</strong>s<br />

Now, this is all very well for a fixed SQL statement like the one we had hard-coded to<br />

query for postal code 98011. But what happens if you want the user to specify the postal<br />

code that they are searching for You achieve this using parameters. Thus, you can provide<br />

an application where the user specifies (using text input, request parameters, or<br />

other input mechanisms) what they want, <strong>and</strong> your application responds accordingly.<br />

Be careful when using parameters in SQL statements that are derived from user<br />

input, as this is a common source of SQL injection attacks. This type of hacker attack<br />

involves a cleverly crafted parameter value on the user’s part <strong>and</strong> an insecure application<br />

that doesn’t validate user input. This attack can allow a malicious user to access private<br />

data or even destroy your database.<br />

To use a parameter in SQL, you specify a placeholder for the parameter by prefixing<br />

it with the @ character. So, for example, our hard-coded query from earlier could be<br />

changed to this:<br />

sqlComm.Comm<strong>and</strong>Text =<br />

"SELECT AddressLine1 FROM Person.Address WHERE (PostalCode = @strZIP)";<br />

Then, before executing, you add the value of the parameter to the comm<strong>and</strong>,<br />

like this:<br />

sqlComm.Parameters.Add("@strZIP", strParamZIP);<br />

The value you’ll assign to the parameterized postal code is contained in the variable<br />

strParamZIP. The value can be the result of text input, or, if you prefer, taken directly off<br />

the query string. The code to access it from the query string will look like this:<br />

string strParamZIP = "98011";<br />

if (Request.Params["ZIP"] != null)<br />

strParamZIP = Request.Params["ZIP"];<br />

But if you use code like this, don’t forget to sanitize strParamZIP before passing it to<br />

the database to avoid injection attacks. By sanitize, I mean that you should evaluate the<br />

value contained within strParamZIP <strong>and</strong> make sure it’s a valid postal code, not some other<br />

(invalid) text.<br />

Now if you run your application, your query string can contain a postal code, <strong>and</strong> the<br />

query results for that postal code will be displayed. Figure 4-18 shows an example of this<br />

where I used a postal code of 14111.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!