Take the 2-minute tour ×

I am designing a web part where users can enter a search phrase the MOSS Search index is sought for that. I use FullTextSqlQuery class for searching.

When I create my select statement, I apparently have to use concatenation to include the user's input in it. The final statment should be something like this:

 SELECT title, author from portal..scope() 
 WHERE ("SCOPE" = 'TheDocuments') 
 AND CONTAINS(MYPROPERTY, 'TheValueThatuserSpecified')

So, the question is, how do I avoid SQL(?) injections from user input? Is there some specific utility function for that? In php/mysql projects I'd use mysql_real_escape_string. Anything similar in SharePoint namespaces?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

I haven't found any function to encode user input so I created my own method:

protected override string EncodeUrlParameter(string paramValue)
   StringBuilder sb = new StringBuilder();
   for (int i = 0; i < paramValue.Length; i++)
       char c = paramValue[i];
       if (c == '*' || c == '%' || c == '[' || c == ']' || c == '_')
       else if (c == '\'')
   return sb.ToString();

This is mainly used for parameters filtered using the LIKE keyword (the documentation page has a note about this). The biggest thing I stumbled upon was when people tried to include apostrophes in their queries.

share|improve this answer

The FullTextSQLQuery class takes a "full text sql" query which is not true sql. The "full text sql" is parsed and converted to regular sql to query against table in the sql server database and to query against an external index file. There is no way to do sql injection via "full text sql", it will not pass validation. The "column names" you use in the "full text sql" must be valid "managed properties" that are set up in Search Administration, they do not point to actual column names on a table.


share|improve this answer
True, but this way the user could anyway enter search phrase like ') AND CONTAINS (ANOTHERPROPERTY, 'Anothervalue) OR (SCOPE='AnotherScope. This renders a valid search query, but in quite a different way. Another point is - you have to take care of escaping apostrophes, quotes etc. –  naivists Jan 11 '11 at 15:02
CONTAINS predicate will only work against managed properties that have been enabled as FullTextQueriable. Also, Retrievable flag. This flag prevents a Managed Property’s value from being returned if specified as a column in the SELECT statement. –  Madhur Ahuja Jan 11 '11 at 15:07
Also, search results are security trimmed, so even if you manage to get your injected query to run you will only get results that you normally have access to anyway. –  Tom Clarkson Jan 12 '11 at 23:04

Your Answer


