Thursday, 14 August 2014

Asp.net Preventing SQL Injection Attacks using Parameterized Queries

 C# Code


SqlCommand cmd = new SqlCommand("select Name,Total=value from countrydetails where value =@value", con);
cmd.Parameters.AddWithValue("@value", txtSearch.Text);
VB.NET Code
Dim
cmd As New SqlCommand("select Name,Total=value from countrydetails where value =@value", con)
cmd.Parameters.AddWithValue("@value", txtSearch.Text)
To know more about how SQL injection occurs check this article SQL injection Attacks in Asp.net.
If you want to check example to prevent SQL injection attacks first design one table countrydetails in your database like as shown below Column Name

Data Type
Allow Nulls
ID   Int(set identity property=true)
name  Varchar(50)
value   Int



Once we create table we need to enter some dummy data for our application purpose
Now in your Default.aspx page write the following code

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Prevent SQL Injection Attacks in Asp.net Website</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter Count:<asp:TextBox ID="txtSearch" runat="server" />
<asp:Button ID="btnsearch" Text="Search" runat="server" onclick="btnsearch_Click" />
<br /><br />
<asp:GridView ID="gvDetails" CellPadding="5" runat="server">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>
After completion of aspx page write the following code in codebehind

C# Code
using System;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnsearch_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("select Name,Total=value from countrydetails where value =@value", con);
cmd.Parameters.AddWithValue("@value", txtSearch.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
}
}

VB.NET Code
Imports System.Data
Imports System.Data.SqlClient
Partial Class VBcode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub btnsearch_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim dt As New DataTable()
Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("select Name,Total=value from countrydetails where value =@value", con)
cmd.Parameters.AddWithValue("@value", txtSearch.Text)
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
con.Close()
gvDetails.DataSource = dt
gvDetails.DataBind()
End Using
End Sub
End Class
When we run above code we will get output like as shown below

Demo

No comments:

Post a Comment