How to get rid of single quotes in {0} string parameter? - c#

I made a service and it retrieve sql command from physical xml file.
It looks like:
<Sql>
<![CDATA[
SELECT
MAX(COMM_HIST_NO) AS COMM_HIST_NO
, MAX(COMMUTER_NO) AS COMMUTER_NO
, MAX(ARRIVED_AT_WORK) AS ARRIVED_AT_WORK
, MAX(LEFT_WORK) AS LEFT_WORK
FROM COMMUTE_HISTORY
WHERE COMMUTER_NO = {0}
AND DATEDIFF(DAY, {1}, GETDATE()) = 0
]]>
</Sql>
And here's what returns sql command as a string:
// arParams is an Array.
string.Format(xmlDoc.SelectSingleNode("/SVC/Sql").InnerText,arParms)
{1} is going to be a column name and I want my {1} parameter to be written as column name, which has no single quotes.
To be specific, Mybatis in Java provides ${param} and #{param} and the latter one gets rid of single quotes from the string param.
.NET must have developed this feature!

Sorry, that was a simple mistake.
It worked at the first place. If single quotes are not given around the parameter, '' will not be there.

Related

Console WriteLine(var, var); not displaying second variable?

I'm writing a little text-based adventure in the console as one of my first projects in C#.
At a certain point, I want to do the following:
Console.WriteLine(intro);
var name = Console.ReadLine();
Console.Clear();
Console.WriteLine(replyOne, name, replyTwo);
However, on that last line, only the first variable (replyOne) is displayed. How can I display all the values?
Depends on what's on replyOne, but you are using a Console.WriteLine overload that takes a format string as the first argument and a number of objects for substitution of that format string (this one). That's what's called Composite Formatting in .NET
If what you want to do is concatenate the strings, you can do it in several ways:
Pass only one string to Console.WriteLine:
Console.WriteLine(replyOne + name + replyTwo);
Use a format string... this would use the same overload you are using now, but passing a formatting string for substitution on the first argument:
Console.WriteLine("{0}{1}{2}", replyOne, name, replyTwo);
Use an interpolated string (C# 6 and up only)
Console.WriteLine($"{replyOne}{name}{replyTwo}");
In the multi-argument overloads of the Console.WriteLine the first parameter is supposed to be a format string, and everything else as a substitution values.
See Console.WriteLine Method (String, Object) for details.
If you want Console.WriteLine to output a formatted string the first argument has to be the string that contains the placeholders that define the formatting. So assuming you just want to output the three strings consecutively, you'll need something like this:
Console.WriteLine("{0} {1} {2}", replyOne, name, replyTwo);
which will output the three strings separated by spaces.
You can replace the spaces by commas, newlines (\n) or tabs (\t) to get the formatting you need.
Try this instead:
Console.WriteLine(replyOne + name + replyTwo);
Or something similar.
As you're calling the method right now, it's treating the replyOne value as the format for the output, not an individual output item. And of course, your format doesn't have a {0} or {1} for the format arguments in the call, name and replyTwo, so they are omitted.
You can just concatenate the output text yourself, as above, as use that as the entire format (without any format arguments at all).
There are, of course, lots of other options for formatting the output. The above fits what you've posted so far.
Console.WriteLine("{0},{1},{2}",replyOne,name,replyTwo);

Finding a specific single quote and replacing with double quotes in 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();

Format a Resource string into another one?

What would be the best way to accomplish something like this?
Suppose I have the following pair of Resource strings.
BadRequestParameter: Potential bad request aborted before execution.
RequiredParameterConstraint: {0} parameter requires a value. {1}
And suppose I want to set {1} on the second one, to the value of BadRequestParameter. I could easily do that using string.Format. But now suppose I have lots of Resource strings like the second one, all of which include some other Resource string in them.
What would be the best way to code this? Is using string.Format repeateadly in each case really all that I can do?
Update
I'll try to explain myself better. These are the resource strings I actually have:
BadRequestParameter Potential bad request aborted before execution.
EmptyVector Vectorized requests require at least one element. {0}
OverflownVector Vectorized requests can take at most one hundred elements. {0}
RequiredParamConstraint {0} parameter requires a value. {1}
SortMinMaxConstraint {0} parameter value '{1}' does not allow Min or Max parameters in this query. {2}
SortRangeTypeConstraint Expected {0} parameter Type '{1}'. Actual: '{2}'. {3}
SortValueConstraint {0} parameter does not allow '{1}' as a value in this query. {2}
I'd like to avoid writing the string in BadRequestParameter at the end of each of those lines. Therefore, I added a format at the end of those strings. The issue now is that I'd like to somehow auto-reference {x} to BadRequestParameter, in order to avoid having to make calls like
string.Format(Error.EmptyVector, Error.BadRequestParameter);
I have lots of Resource strings like the second one, all of which include some other Resource string in them.
Instead of storing pre-made format strings ready for use, you could store raw material for building real format strings, and add code to expand them pro grammatically before use. For example, you could store strings like this:
BadRequestParameter: Potential bad request aborted before execution.
SupportNumber: (123)456-7890
CallTechSupport: You need to call technical support at {SupportNumber}.
RequiredParameterConstraint: {{0}} parameter requires a value. {BadRequestParameter} {CallTechSupport}
Of course passing these strings to string.Format as-is is not going to work. You need to parse these strings, for example with RegExps, and find all instances where you have a word between curly braces, instead of a number. You could then replace each word with its sequence number, and produce an array of parameters based on the names that you find between curly braces. In this case, you will get these two values (pseudocode):
formatString = "{{0}} parameter requires a value. {0} {1}";
// You replaced {BadRequestParameter} with {0} and {CallTechSupport} with {1}
parameters = {
"Potential bad request aborted before execution."
, "You need to call technical support at (123)456-7890."
};
Note: Of course, producing this array of parameters required recursion.
At this point, you can invoke string.Format to produce your final string:
var res = string.Format(formatString, parameters);
This returns the string that has resource strings pre-replaced for your callers:
"{0} parameter requires a value. Potential bad request aborted before execution. You need to call technical support at (123)456-7890."
The callers can now use this string for formatting, without bothering with other resource values.
Yes :-) unless you want to make a helper method that is shorter, but that would really just be for convenience sake
public static string f(string format, params object[] p)
{
return string.Format(format, p);
}
IF you treat the argument indicators {#} as wild cards then why would it make sense for you to pre-fill them inside of your resource.
I see absolutely nothing wrong with
String.Format(RequiredParamterConstraint, "something", BadRequestParameter);

C# how to Parse stored procedure String

I have a Query string from client application. It comes with all parameters like
string query="PROCS.DBO.APP_2370_ANALYST_S 'ABC' , 'TESTDATA' , 100";
In Server, I made a function(Util.getParametersFromString) to parse string from client application to make parameter object Array using string.Split function.
I used ',' and ' ' as separator to make object array.
And I execute db procedure by using below code
object[] parameters = Util.getParametersFromString(query);
DbCommand cmd = dbconnection.GetStoredProcCommand("PROCS.DBO.APP_2370_ANALYST_S", parameters);
I works well if parameter string doesn't contain comma or single quotation mark.
If one of parameter string have one or more comma or single quotaion mark.
Like below
string query="PROCS.DBO.APP_2370_ANALYST_S 'A,B,C' , 'Hi, Sam 'The Legend' Brown was here ' , 100";
parameter array didn't come correctly. I didn't know how to parse string correctly in this
situation. Please give me advice to solve this problem
I am not good at english. So I am so sorry If I didn't write my question correctly
Regards,
Park
You can escape the single quotes - ' becomes '':
string query="PROCS.DBO.APP_2370_ANALYST_S 'A,B,C' , 'Hi, Sam ''The Legend'' Brown was here ' , 100";
As for the problem with a comma - it depends on how your function is written. You will have to escape the comma and make sure your function is aware of this escape sequence.
If both parameters of your query string are as flexible as your example, and you cannot change the way this string is generated as suggested in Oded's answer, you have a problem.
The query "PROCS.DBO.APP_2370_ANALYST_S 'ABC' , 'ABC' , 'ABC' , 100" for example, could be interpreted as having the first parameter "'ABC' , 'ABC'" and second parameter "ABC" or vice versa.
If, on the other hand, your first parameter may not contain 's, then you could identify the first parameter by looking between the first two 's, and the second parameter by falling between the third and the last '.

Possible to pass name/value as parameter into Windows Console Application?

Building one of my first console apps.
This console app will run some stored procedures I'm defining. I would like to be able to pass in parameter values via the command line.
Is there any way to pass in a name value pair? For example:
myConsoleApp.exe sproc_GetLastActives, #LastActiveDate - 11/20/2009
I know how to retreive the parameter values, but I'm noticing that the args[] are split if I put in a / or a ,. How can I pass in name value pair?
Thanks!
Do you want that in a single string? Try this:
myConsoleApp.exe "sproc_GetLastActives, #LastActiveDate - 11/20/2009"
(i.e. just add quotes)
Slashes and commas shouldn't affect things, but the command line parser splits on spaces unless you've quoted it.
There are several solutions to this problem the most common is to use '/' or '-' to prefix parameters and = to delimit them from their arguments for example
consoleapp.exe /spname=sproc_GetLastActives /LastActiveDate="11/20/2009"
in your code your code you can use String.Split(arg[i], new char[] {'='}) to bust up the individual parameters.
consoleapp.exe key1 val1 key2 val2
args[] gives your 4 items, pair them up in your code. :P
Similar to mykhaylo's response, why not pass in the values at one string:
consoleapp.exe sproc_name key1=value1 "key2=Value With Spaces" key3=value3
Then just test for the presence of the = sign and parse it to get your key/value pair.

Categories