We have a legacy C# application where we have a lot of inline SQL queries that are being executed against the input that was passed by the user. So, obviously SQL injection came into the picture. Now we want to fix it but the thing is we want to go with minimalistic approach. Not touching to much code. So ORM and stored procedures are kind of out of the equation for us.
We have to update every inline statement to make use of SQL parameterization approach. However, what I am looking for is may be if there is a generic way of doing it. Like send the query to a method and generate the SqlParameter array dynamically.
By query I mean literally the query whenever I can without using the conventional @
Select *
From table
Where id = 1 and name = 'Sean' and
location like '%cali'
To something like this
List<Sqlparameters> params = new
List<Sqlparameters>()
var query = Select * from table where id = @v1 and name =@v2 and location like @v3
params.Add("v1", 1)
params.Add("v2", 'Sean')
params.Add("v3","%cali")
Update
Now, I have a method which does this for me. This will take the sql text like this
var sql = "select * from merchants where merchantID={" + Request["merchantid"] +"}"
Method
Public command Method(string query)
{
var cmd =new Command();
cmd.text="";
cmd.params=new List<SqlParameter>() ;
// code to trasform the query. Identify values based on the special char '{'. Dynamically adds placeholder variables and values into an array
cmd.text="select * from merchants where merchantID=@variable1
//Loops through variables and adds values
// to parameters
cmd.parameters.Add(new SqlParameter("variable1", value1);
return cmd;
}