Finding a specific single quote and replacing with double quotes in C# - c#

I've a problem where I want to replace some specific single quotes with double quotes inside a SQL string but not all singles quotes in that string.
EXEC procedureName 'param'eter1', 'parameter2'
In above example I just want to replace the singles quotes inside the 'param'eter1' but the singles quotes in start and end of the parameter to remain same.
Using below command replace all singles quotes in the string and it looks like this ''param''eter1'' which is not correct.
sometext.Replace("'", "''")
I want it to look like this:
EXEC procedureName 'param''eter1', 'parameter2'
Also please note that I am already aware that using SqlParameter is a better solution to handle the single quotes in SQL parameters but due to the restrictions in the project environment I am unable to implement that.
Update:
Changing the individual parameters before using them to construct the full statement is not an option for me as I don't have access to that code. My project works like a data layer where it received SQL strings from other applications to process.

This is a very bad idea. The SQL syntax requires you to escape single quotes in literals exactly because it can otherwise not tell whether the single quote is meant to represent a single quote or meant to terminate the string literal.
Consider the following example:
EXEC procedureName 'param ', ' eter1', 'parameter2'
How would you know whether this is meant to have three parameters for the procedure call or only two? And even if you knew that this specific procedure takes two parameters, you couldn't decide whether the middle part belongs to the first or second parameter.
If the system constructs sql statements from user input without dealing with single quotes before the full statement is constructed, this can be used very easily to attack the system via an sql injection.

you can do like this
var aStringBuilder = new StringBuilder(theString);
aStringBuilder.Remove(3, 2); // just find a position of single quotes
aStringBuilder.Insert(3, "/""); // replace that position with " quotes using loop
theString = aStringBuilder.ToString();

Related

Replacing single quotes in full sql queries with C#

In our C# desktop-application we generate a lot of dynamic sql-queries. Now we have some troubles with single quotes in strings. Here's a sample:
INSERT INTO Addresses (CompanyName) VALUES ('Thomas' Imbiss')
My question is: How can I find and replace all single quotes between 2 other single quotes in a string? Unfortunately I can't replace the single quotes when creating the different queries. I can only do that after the full query is created and right before the query gets executed.
I tried this pattern (Regular Expressions): "\w\'\w"
But this pattern doesn't work, because after "s'" there's a space instead of a char.
I am sorry to say, there is no solution in approach you expect.
For example, have these columns and values:
column A, value ,A',
column B, value ,B',
If they are together in column list, you have ',A',',',B','.
Now, where is the boundary between first and second value? It is ambiguous.
You must take action when creating text fields for SQL. Either use SQL parameters or properly escape qoutes and other problematic characters there.
Consider showing the above ambiguous example to managers, pushing the whole problem back as algorithmically unsolvable at your end. Or offer implementing a guess-work and ask them whether they will be happy if content of several text fields can get mixed in some cases like above one.
At time of SQL query creation, if they do not want to start using SQL parameters, the solution for enquoting any input string is as simple as replacing:
string Enquote(string input)
{
return input.All(c => Strings.AscW(c) < 128) ? "'" : "N'"
+ input.Replace("'", "''")
+ "'"
}
Of course, it can have problem with deliberately malformed Unicode strings (surrogate pairs to hide ') but it is not normally possible to produce these strings through the user interface. Generally this can be still faster than converting all queries to versions with SQL parameters.

Running complex command line from C#

I'm trying to run the following command line from C#:
Process.Start("C:\\Program Files\\GoToTags\\GoToTags Encoder\\GoToTags.Encoder.exe --records "{'Url':'http://petshop.intato.com/index.php?id='" + TxtBoxIDCode.Text + "'','RecordType':'Website'}"");
Obviously it is not working.
The problem is that I need to keep the proper signs such as the : in order to make it work properly.
The original command is:
C:\Program Files\GoToTags\GoToTags Encoder\GoToTags.Encoder.exe --records "{'Url':'http://petshop.intato.com/index.php?id=29','RecordType':'Website'}"
I have to run that command and at the same time, replace that 29 with the content of a textbox
Would anyone be able to help me with that?
The string.Format command is your friend...
string path = #"C:\Program Files\GoToTags\GoToTags Encoder\GoToTags.Encoder.exe";
string args = string.Format("--records \"{'Url':'http://petshop.intato.com/index.php?id={0}','RecordType':'Website'}\"", TxtBoxIDCode.Text);
Process.Start(path, args);
You have several pitfalls awaiting you.
Firstly, as you've already discovered, the backslashes in path names cause problems in the strings, as they could also indicate C# escape sequences. It's usually good practice to use C#'s #"..." syntax for file names, partly to avoid needing to double up the backslashes and make it easier to read, and partly because you could inadvertently leave a \t in there and it'd go unnoticed for ages.
Secondly, the single-parameter call to Process.Start only takes a command - it cannot accept command arguments - so you have to call the two-parameter overload.
Thirdly, the quotes around of the value of the records argument need handling so that the C# syntax knows what you want with them - i.e. to pass them to the command. I've separated out the command arguments into two parts to make that clearer. I have elected to use backslashes to escape them, though using the alternative #"...""..." would be just as good, and the choice is largely down to personal preference unless the context points you strongly one way rather than the other.
string cmd = #"C:\Program Files\GoToTags\GoToTags Encoder\GoToTags.Encoder.exe";
string url = "http://petshop.intato.com/index.php?id=" + TxtBoxIDCode.Text;
string cmdArgs = "--records \"{'Url':'" + url + "','RecordType':'Website'}\"";
Process.Start(cmd, cmdArgs);
[edited to add:]
If for some reason you find you either want or need to use string.Format to help build your cmdArgs, there's a fourth gotcha waiting in the wings for you, in that string.Format looks for the brace ({ and }) characters to delimit insertion parameter specifications, but your records command-line argument wants braces characters in the string. The way to achieve that would be to double up the braces that you want, like this:
string cmdArgs =
string.Format("--records \"{{'Url':'{0}','RecordType':'Website'}}\", url)";
In addition to the other answers, you should use the two-argument overload of Process.Start. The first argument is the executable, and the second argument is the command line arguments.
Normally, if you insist on using a single argument call, you should enclose your executable in double quotes, as such:
"\"C:\\Program Files\\GoToTags\\GoToTags Encoder\\GoToTags.Encoder.exe\" ...arguments here..."
However, this form does not work for Process.Start(string) because it specifically disallows it.

Replace all single quotes with two single quotes in a string

I am trying to read value from DB using c#.
The query string contains multiple single quotes - such as: Esca'pes' (the query strings are being read from a text file)
So, I wanted to replace all the single quotes with two single quotes before forming the SQL query. My code is as below:
if (name.Contains('\''))
{
name = name.Replace('\'','\''');
}
How to fix this?
Use strings, not char literals.
name = name.Replace("'", "''");
However it sounds like you're concatenating SQL strings together. This is a huge "DO NOT" rule in modern application design because of the risk of SQL injection. Please use SQL parameters instead. Every modern DBMS platform supports them, including ADO.NET with SQL Server and MySQL, even Access supports them.
name = name.Replace("'","''");
On an unrelated note, you're concatenating strings for use in SQL? Try parameters instead, that's what they're meant for. You're probably making it harder than it needs to be.
Since you want to replace a single character with two characters, you need to use the String overload of Replace
if (name.Contains('\''))
{
name = name.Replace("'","''");
}
(Note: single quotes don't require escaping in Strings like they do in character notation.)

How to avoid double quote escape in C# strings?

In Ruby it's possible to use the strings without the need to escape the double quote in the string, like Q/Some my string with "double quotes"/
Is it possible with C# to use a string without a need to escape double quotes?
For a good reason I need to write inline SQL and it's very annoying to escape double quotes every time I put SQL query from DB console to C# code.
I know it's possible to use \" or "" as one double quote. But is it possible to avoid the need to escape the double quotes?
No, basically. You have the choice of "foo \" bar" or #"foo "" bar", both of which you have mentioned. However, frankly I rarely find " necessary in SQL; you have ' for literal strings and [ / ] for object/column names - of course, this might just be because I usually use SQL Server.
The only alternative that doesn't involve any escaping is to move the SQL to an external resource file, maybe a text file. That, though, is probably more painful than just using "".
No, this is not possible in C#. You could write your SQL in a separate file and then read it from there.
For a good reason I need to write inline SQL and it's very annoying to
escape double quotes every time I put SQL query from DB console to C#
code.
If you are writing a Inline Sql Query you don't need to worry about quotes if you passed the values via SqlParameters. This way you won't see the annoying double quotes every where and even your query will safe from Sql Injection

c#: what is the proper way to perform sql LIKE searches using any characters

I'm building (c#) sql select commands strings on the fly using LIKE %somestring% conditions. In my search strings I want to be able to handle any character found on a standard PC (US) keyboard (including ~ ! # # % etc., alt-special chars not required but would be nice to have). I know that single quotes need to be doubled up and perhaps double quotes as well. What other string fixes might be required to ensure correct syntax?
No fixes required:
SqlCommand cmd = new SqlCommand("select * from Foo where Bar like #p", connection);
SqlParameter p = new SqlParameter();
param.ParameterName = "#p";
param.Value = pattern;
cmd.Parameters.Add(param);
Apart from doubling up single quotes (or using a parametrised query), will the user know that "_" and "%" are wildcards (any-character and zero-or-more-any-characters respectively), and that "[...]" creates a closure?
To escape those characters there are two routes
WHERE Foo LIKE '%xxx\%yyy%' ESCAPE '\'
or
WHERE Foo LIKE '%xxx[%]yyy%'
the second uses the side effect of creating a closure, and avoids having to use the ESCAPE (which in itself needs some thought to choose a character that does not conflict with the rest of the string, or is itself escaped where it occurs)
Note that using 'LIKE %somestring%' will usually require a table scan, and may therefore lead to performance problems - e.g. if you have millions of rows to be checked.
In SQL Server you can use sp_ExecuteSQL if you are generating WHERE clauses by string-concatenation - so that only fields that the user specifies criteria for are included. sp_ExecuteSQL will cache the query and, most times, improve performance. (please ask if that it relevant and you need help)

Categories