1

I think the main point of my question is: what is best practise or is Visual Studio 2019 giving me wrong hints about reviewing the query string?

I have checked this example from Microsoft where the warning-code is sent me, but the following warning keeps popping up. The example gives obsolete code so I might look in the wrong place..

Review if the query string passed to 'string SqlCommand.CommandText' in 'GetTrumpfCadCamDocuments', accepts any user input.

The code was different, but when I do it the way the docs suggest the code looks like this:


/// The sqlfilepath is a content file which looks like this:
/// SELECT * FROM [R_DOCUMENT] WHERE [TYPE] = @type
/// Writing out the file content as a string is also used sometimes
/// which gives the same error.

string query = File.ReadAllText(sqlfilepath);

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    using (SqlCommand command = new SqlCommand())
    {
        command.Connection = connection;
        command.Parameters.AddWithValue("@type", type);
        command.CommandText = query; //warning gets triggered here
        
        .....
    }
}
  • 2
    What is the actual value of `query`? – Olivier Jacot-Descombes Feb 15 '22 at 13:58
  • 1
    Where is `query` coming from? If it is a constant then you shouldn't get this error. If it's coming from an input parameter or concatenation then you should question why that is. The warning is there for a reason: beware of SQL injection. Side point: a shorter syntax is: `using (SqlCommand command = new SqlCommand(query, connection))` also you don't need to `Close` as the `using` sorts that out – Charlieface Feb 15 '22 at 14:41
  • 1
    Aside... [AddWithValue is Evil](https://www.dbdelta.com/addwithvalue-is-evil/). – AlwaysLearning Feb 15 '22 at 21:20
  • Yes Charlie normally I use the shorter syntax which is not used by msdn. I've added where query comes from. – Clinton Portis Feb 16 '22 at 11:02

0 Answers0