Handling special character input for data selection [duplicate] - c#

This question already has answers here:
Escape a string in SQL Server so that it is safe to use in LIKE expression
(6 answers)
Closed 5 years ago.
UPDATE
Following four characters need to be escaped when '\' is the escape helper %[]_
http://msdn.microsoft.com/en-us/library/aa933232(v=sql.80).aspx - LIKE
Escape a string in SQL Server so that it is safe to use in LIKE expression
How do I escape _ in SQL Server?
QUESTION
Though I searched a lot, I could not find out a problem exactly matching the following, in stack overflow.
I have a database column called Log_Description. It has two records.
1) "Sample % value record"
2) "Sample free record"
I am using SQL Command and setting parameters as shown below
commandText = commandText + “Log_Description LIKE #Log_Description”;
command.Parameters.AddwithValue(“#Log_Description”, “%”+obj. LogDescription+”%”);
Suppose the user enters “%” as search param for txtLogDescription textbox, I need to show only first record. But currently it is showing both the records.
What are the possible ways to overcome this?
What are the other characters that may cause such issues with the above code?
Note: I cannot prevent user from entering “%” as input
Note: I am using SQL Server as database
EDIT:
Solution I am using now is Escaping the escape character does not work – SQL LIKE Operator
private static string CustomFormat(string input)
{
input = input.Replace(#"\", #"\\");
input = input.Replace(#"%", #"\%");
input = input.Replace(#"[", #"\[");
input = input.Replace(#"]", #"\]");
input = input.Replace(#"_", #"\_");
return input;
}
LINQ approach (with performance hit) is below
Collection<Log> resultLogs = null;
if (!String.IsNullOrEmpty(logSearch.LogDescription))
{
resultLogs = new Collection<Log>();
var results = from o in logs where o.LogDescription.Contains(logSearch.LogDescription) select o;
if (results != null)
{
foreach (var log in results)
{
resultLogs.Add((Log) log);
}
}
}
else
{
resultLogs = logs;
}

As far as escaping %, see Tommy Grovnes' comment on the question.
If you can use a List<T> instead of a Collection<T> (see here), this can be written more concisely:
var descr = logSearch.logDescription;
var results = (
from o in logs
where String.IsNullOrEmpty(descr) ||
o.LogDescription.Contains(descr)
select o
).ToList();
If you still need a Collection<T>, you can wrap the results of the LINQ query in a Collection constructor:
var results = new Collection<Log>((
from o in logs
where String.IsNullOrEmpty(descr) ||
o.LogDescription.Contains(descr)
select o
).ToList());

Related

Extract specific words from a string in C#

Although its easy in python but i am new to C# and i am having trouble extracting a particular word from a string . i have two txt file .
abc.txt
select * from schema1.table1
xyz.txt
select * from schema2.table2 where a=5
i need to extract "schema1" and "schema2" words only but i tried but i am having trouble with it as it is C#.
MY code
{
StreamReader sr = new StreamReader(file);
string data = sr.ReadLine();
while (data != null)
{
string[] values = data.Split('.');
foreach (string value in values)
{
Console.WriteLine(value.Split(' ').Last());
data = sr.ReadLine();
}
}
}
but the output gives whole lot of other words too . any kind of lead is appreciated .
You may try the following:
string sql = "select * from schema2.table2 where a=5";
var schema = Regex.Replace(sql, #"^select \* from ([^.]+)\.\S+.*$", "$1");
Console.WriteLine(schema); // schema2
This answer makes very large assumptions, including that every SQL query you would need to parse would always start with select * from some_schema.some_table. Obviously, for more complex/different queries, the above logic would fail.
In general, you might need to find a .NET library which can parse SQL queries.

Evaluating inline C# code from post content

I have been around in circles with this one and need some help. I have a method that evaluates code, so if I pass this Eval("DateTime.Now.Year - 1986") it returns 29, its working great and this means I can have inline code in my posts that dynamically evaluate at runtime (this might present some security concerns, but that for some other time), here's the example string I am trying to work with: string inStr = "this year is [EVAL]DateTime.Now.Year[/EVAL] and it has been [EVAL]DateTime.Now.Year - 1986[/EVAL] years since 1986"; I need a regex that will replace all [EVAL] instances and return the full text with the evaluated results. Anyone?
You want a Regex, you can have a regex...
string inStr = "this year is [EVAL]DateTime.Now.Year[/EVAL] and it has been [EVAL]DateTime.Now.Year - 1986[/EVAL] years since 1986";
var rx = new Regex(#"(\[EVAL\])(.*?)(\[/EVAL])");
string outStr = rx.Replace(inStr, RegexReplacer);
with
public static string RegexReplacer(Match match)
{
return Eval(match.Groups[2].Value);
}
or depending on the return type of Eval:
public static string RegexReplacer(Match match)
{
object obj = Eval(match.Groups[2].Value);
return obj != null ? obj.ToString() : string.Empty;
}
The capture group #2 is the (.*?). Note the use of the lazy quantifier .*?, because otherwise the capture would be [EVAL]DateTime.Now.Year[/EVAL] and it has been [EVAL]DateTime.Now.Year - 1986[/EVAL]

How to correct parse query string in C# if value contains ampersand? [duplicate]

This question already has answers here:
How to parse a query string into a NameValueCollection in .NET
(19 answers)
Closed 6 years ago.
I need parse query string: ?artist=singer1 & singer2&song=name song
Static method HttpUtility.ParseQueryString doesn't work the way I want if value contains ampersand like "singer1 & singer2".
For example:
string qs = "?artist=singer1 & singer2&song=name song";
NameValueCollection query = HttpUtility.ParseQueryString(qs);
Result is:
artist = singer1
null = singer2
song = name song
I would like result
artist = singer 1 & singer2
song = name song
Any idea?
The ampersand (&) in the middle of one of your values is throwing off the parser since it's a reserved symbol. Replace it with its numeric code instead:
string qs = "?artist=singer1+%26+singer2&song=name song";
NameValueCollection query = HttpUtility.ParseQueryString(qs);
Your problem is that & carries special meaning in a query string, namely to separate arguments. The & in the middle of your perceived artist parameter is actually being parsed as an argument separator. You need to URL encode the & when constructing the URL.
For example, one correct query string would be:
?artist=singer1+%26+singer2&song=name+song
(Spaces can usually be encoded either as + or %20, but that's a topic for another discussion.)
You can use HttpUtility.UrlEncode() when building the query string components to ensure that the result is correctly escaped. For example, you could build the query string like this:
static void Main()
{
var values = new NameValueCollection();
values["artist"] = "singer1 & singer2";
values["song"] = "name song";
Console.WriteLine(CreateQueryString(values));
}
static string CreateQueryString(NameValueCollection values)
{
if (values == null) { throw new ArgumentNullException("values"); }
return string.Join(
"&",
values.AllKeys.Select(key => HttpUtility.UrlEncode(key) + "=" +
HttpUtility.UrlEncode(values[key]))
.ToArray());
}
In other words, the issue is occuring at the time you build the query string, not when you are trying to parse it. When parsing it you already have a semantically incorrect query string; there's nothing you can do at this point.
If you want artist = singer1 & singer2 you need to escape or encode the & in your query string.
for example, if I ask Google about fred & blotts
the resulting query string contains &q=fred+%26+blotts rather than &q=fred+&+blotts
See https://www.rfc-editor.org/rfc/rfc3986#page-12

Using literal underscore character in a MySQL query from c#

From my ASP.NET application I want to issue this query to MySQL
SELECT * FROM responses WHERE field_id LIKE '3\_%'
In other words I am looking for records where the second character is the underscore literal character.
The code generated by the model designer looks like this:
public virtual RiskAnalysis.responsesDataTable GetResponseGroupForAnalysis(int raid, string fieldid) {
this.Adapter.SelectCommand = this.CommandCollection[2];
this.Adapter.SelectCommand.Parameters[0].Value = ((int)(raid));
if ((fieldid == null)) {
throw new global::System.ArgumentNullException("fieldid");
}
else {
this.Adapter.SelectCommand.Parameters[1].Value = ((string)(fieldid));
}
RiskAnalysis.responsesDataTable dataTable = new RiskAnalysis.responsesDataTable();
this.Adapter.Fill(dataTable);
return dataTable;
}
If I call this function like so:
string filter_string = #"3\_%";
ResponsesAdapter.GetResponseGroupForAnalysis(10, filter_string);
the MySQL log reports the query to look like this:
SELECT *
FROM responses
WHERE (ra_id = 10) AND (field_id LIKE '3\\_%')
In other words the I know I'm missing something blindingly obvious here, but how do I place MySQL's escape backslash in the query without C# (un)helpfully escaping it?
In the standard SQL, you can use the ESCAPE keyword to set an escaping character.
MySQL follows the standard SQL in this, as stated by the LIKE predicate documentation:
expr LIKE pat [ESCAPE 'escape_char']
Like so:
...
field_id LIKE '3\_%' ESCAPE '\'
This will make the wildcard _ be treated as a string literal.
Hope this what you were asking about.
OK, it seems (by experiment - happy to hear explanation or documentation link) that in MySQL (field_id LIKE '3\_%'); is equivalent to (field_id LIKE '3\\_%'); and both will find records where field_id starts with '3_'. Got myself well confused there - thanks Mahmoud and René for trying to understand what I was getting at!

Entitize arbitrary .NET string [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can I convert a C# string value to an escaped string literal
How can i entitize an arbitrary string to get exact human readable view similar to what the debugger does? I.e. i want all special characters entitized:
"Hello,\r\nworld"
"Hello,#D$#A$world"
"Hello,0x0D0x0Aworld"
any output like that will be fine. I'm only interested in standard function in BCL (maybe some escape routine in existing serializers or helper classes, whatever). Reverse function would be cool as well.
I do not think that there is out of the box solution for your needs.
Char.Isxxx can be used to find characters that needs special processing and custom code can replace them with info you want to see.
Code below works fine for sample but there is to many different characters in Unicode to be sure that it covers all the cases.
var s = #"Hello,
world";
var builder = new StringBuilder();
foreach (var c in s)
{
if (Char.IsLetterOrDigit(c) || Char.IsPunctuation(c))
builder.Append(c);
else
{
var newStr = string.Format("#{0}$", ((int)c).ToString("X"));
builder.Append(newStr);
}
}
Console.WriteLine(builder.ToString());
Result shown in console:
Hello,#D$#A$world
You can use a series of String.Replaces:
string Entitize(string input)
{
return input.Replace("\n", "\\n").Replace("\r", "\\r"), ... ;
}

Categories

Resources