Incorrect syntax near '​' - c#

First I was getting this error:
Invalid object name "product_images​_temporary"
and after I have added the [] brackets, everything worked fine. But then when I removed them again, I got this error:
Incorrect syntax near '​'
Why does this work:
[product_images​_temporary]
but this throws an exception ("Incorrect syntax near '​'"):
product_images​_temporary
More code:
try
{
using (var sqlConnection = new DapperHelper().DatabaseConnection())
{
var sqlStatement = "SELECT * FROM product_images​_temporary";
sqlConnection.Execute(sqlStatement);
}
}
catch (Exception e)
{
}
Is product_images​_temporary a reserved word in SQL Server? Like datetime etc.? I can't explain this.

Between the s and the _ is the Unicode zero-width-space character \u200B. This is invisible so makes the string not what it appears to be.
This character is not legal in an SQL object identifier name and is the cause of the error you see, using [] escapes make it legal.
Simply retype the name manually or double-delete between the two characters.
As your code does work with [] it means the actual table name contains \u200B so should also be renamed.

Just rename the table, you have an invisible character in your table's name

Related

C#: Unassigned local variable with succeeded property pattern match

I have the following code using pattern matching with a property pattern that always succeeds:
var result = new { Message = "Hello!" } is { Message: string message };
Console.WriteLine(message);
The above match succeeds(result is true). However, when I try to print message, I get a:
CS0165: Use of unassigned local variable.
However, the following works:
var result = "Hello!" is { Length: int len };
Console.WriteLine(len);
Also, when I use it with an if, it just works fine:
if (new { Message = "Hello!"} is { Message: string message })
{
Console.WriteLine(message);
}
Why the discrepancies?
Why the discrepancies?
Well, it's a compile-time error, and at compile-time, it doesn't know that it would match. As far as the compiler is concerned, it's absolutely valid for result to be false, and message to be unassigned - therefore it's a compile-time error to try to use it.
In your second example, the compiler knows that it will always match because every string has a length, and in the third example you're only trying to use the pattern variable if it's matched.
The only oddity/discrepancy here is that the compiler doesn't know that new { Message = "Hello!" } will always match { Message: string message }. I can understand that, in that Message could be null for the same anonymous type... slightly more oddly, it looks like it doesn't know that it will always match { Message: var message } either (which should match any non-null reference to an instance of the anonymous type, even if Message is null).
I suspect that for your string example, the compiler is "more aware" that a string literal can't be null, therefore the pattern really, really will always match - whereas for some reason it doesn't do that for the anonymous type.
I note that if you extract the string literal to a separate variable, the compiler doesn't know it will always match:
string text = "hello";
var result = text is { Length: int length };
// Use of unassigned local variable
Console.WriteLine(length);
I suspect this is because a string literal is a constant expression, and that the compiler effectively has more confidence about what it can predict for constant expressions.
I agree that it does look a bit odd, but I'd be surprised if this actually affected much real code - because you don't tend to pattern match against string literals, and I'd say it's the string literal match that is the unexpected part here.

Invalid expression term 'long'

I get an error "Invalid expression term 'long'" in the code below:
if (Int64.TryParse(Response.ToString(), out long time) == false)
{
this.ResponseStatus = "Unexpected Server Response!";
return false;
}
this.ResponseStatus = "License OK";
return true;
The Int64.TryParse() method takes arguments string s and out long result.
I can recreate the same error you are getting, but with ref instead of out. Here's an example:
private void Test(ref long result)
{
//some code in here
}
I try to call the method like this:
Test(ref long time);
And with this I get the same errors your are getting.
Now the question is, why you are getting the exact same error while using out.
If you don't need the variable long time afterwards, you could just call the TryParse method like this:
Int64.TryParse(Response.ToString(), out _);
The underscore _ just discards the value that would be outputted.
But I think you just didn't provide the correct code corresponding the error. You should provide us with the whole and correct code, so we can help.
The code you show is not the code that causes those compiler errors. You must have something that looks like this:
if (Int64.TryParse(long time) == false)
This yields exactly those three errors:
Error CS1525 Invalid expression term 'long'
Error CS1003 Syntax error, ',' expected
Error CS0103 The name 'time' does not exist in the current context
The format you need is exactly as you've posted it, so fix your code so it looks like the code in your question.

Escaping double quotes in JSON result

I have a set of codes where i have done error handling. I want the result to be {"ErrorMessage": Server is down} However i keep getting the result as {"ErrorMessage":"Server is down"}.
Here are my codes:
catch (Exception e)
{
var result = "Server is down";
return Ok(new { ErrorMessage = result });
}
I have tried using '#' and '\' characters however it did not work. How do i escape those extra double quotes? Someone please do help me. Thank you so much in advance.
I have decided to leave the result as it is as {"ErrorMessage":"Server is down"} is the correct way of displaying a JSON output. As explained by #dbc, that is a valid JSON object with a property named ErrorMessage whose value is the string Server is down.

Sanitizing a String for a Property Name

Problem
I need to sanitize a collection of Strings from user input to a valid property name.
Context
We have a DataGrid that works with runtime generated classes. These classes are generated based on some parameters. Parameter names are converted into Properties. Some of these parameter names are from user input. We implemented this and it all seemed to work great. Our logic to sanitizing strings was to only allow numbers and letters and convert the rest to an X.
const string regexPattern = #"[^a-zA-Z0-9]";
return ("X" + Regex.Replace(input, regexPattern, "X")); //prefix with X in case the name starts with a number
The property names were always correct and we stored the original string in a dictionary so we could still show a user friendly parameter name.
However, where the trouble starts is when a string only differs in illegal characters like this:
Parameter Name
Parameter_Name
These were both converted into:
ParameterXName
A solution would be to just generate some safe, unrelated names like A, B C. etc. But I would prefer the name to still be recognizable in debug. Unless it's too complicated to implement this behavior of course.
I looked at other questions on StackOverflow, but they all seem to remove illegal characters, which has the same problem.
I feel like I'm reinventing the wheel. Is there some standard solution or trick for this?
I can suggest to change algorithm of generating safe, unrelated and recognizable names.
In c# _ is valid symbol for member names. Replace all invalid symbols (chr) not with X but with "_"+(short)chr+"_".
demo
public class Program
{
public static void Main()
{
string [] props = {"Parameter Name", "Parameter_Name"};
var validNames = props.Select(s=>Sanitize(s)).ToList();
Console.WriteLine(String.Join(Environment.NewLine, validNames));
}
private static string Sanitize(string s)
{
return String.Join("", s.AsEnumerable()
.Select(chr => Char.IsLetter(chr) || Char.IsDigit(chr)
? chr.ToString() // valid symbol
: "_"+(short)chr+"_") // numeric code for invalid symbol
);
}
}
prints
Parameter_32_Name
Parameter_95_Name

Incorrect string value: '\xEF\xBF\xBD' for column

I have a table I need to handle various characters. The characters include Ø, ® etc.
I have set my table to utf-8 as the default collation, all columns use table default, however when I try to insert these characters I get error: Incorrect string value: '\xEF\xBF\xBD' for column 'buyerName' at row 1
My connection string is defined as
string mySqlConn = "server="+server+";user="+username+";database="+database+";port="+port+";password="+password+";charset=utf8;";
I am at a loss as to why I am still seeing errors. Have I missed anything with either the .net connector, or with my MySQL setup?
--Edit--
My (new) C# insert statement looks like:
MySqlCommand insert = new MySqlCommand( "INSERT INTO fulfilled_Shipments_Data " +
"(amazonOrderId,merchantOrderId,shipmentId,shipmentItemId,"+
"amazonOrderItemId,merchantOrderItemId,purchaseDate,"+ ...
VALUES (#amazonOrderId,#merchantOrderId,#shipmentId,#shipmentItemId,"+
"#amazonOrderItemId,#merchantOrderItemId,#purchaseDate,"+
"paymentsDate,shipmentDate,reportingDate,buyerEmail,buyerName,"+ ...
insert.Parameters.AddWithValue("#amazonorderId",lines[0]);
insert.Parameters.AddWithValue("#merchantOrderId",lines[1]);
insert.Parameters.AddWithValue("#shipmentId",lines[2]);
insert.Parameters.AddWithValue("#shipmentItemId",lines[3]);
insert.Parameters.AddWithValue("#amazonOrderItemId",lines[4]);
insert.Parameters.AddWithValue("#merchantOrderItemId",lines[5]);
insert.Parameters.AddWithValue("#purchaseDate",lines[6]);
insert.Parameters.AddWithValue("#paymentsDate",lines[7]);
insert.ExecuteNonQuery();
Assuming that this is the correct way to use parametrized statements, it is still giving an error
"Incorrect string value: '\xEF\xBF\xBD' for column 'buyerName' at row 1"
Any other ideas?
\xEF\xBF\xBD is the UTF-8 encoding for the unicode character U+FFFD. This is a special character, also known as the "Replacement character". A quote from the wikipedia page about the special unicode characters:
The replacement character � (often a black diamond with a white question mark) is a symbol found in the Unicode standard at codepoint U+FFFD in the Specials table. It is used to indicate problems when a system is not able to decode a stream of data to a correct symbol. It is most commonly seen when a font does not contain a character, but is also seen when the data is invalid and does not match any character:
So it looks like your data source contains corrupted data. It is also possible that you try to read the data using the wrong encoding. Where do the lines come from?
If you can't fix the data, and your input indeed contains invalid characters, you could just remove the replacement characters:
lines[n] = lines[n].Replace("\xFFFD", "");
Mattmanser is right, never write a sql query by concatenating the parameters directly in the query. An example of parametrized query is:
string lastname = "Doe";
double height = 6.1;
DateTime date = new DateTime(1978,4,18);
var connection = new MySqlConnection(connStr);
try
{
connection.Open();
var command = new MySqlCommand(
"SELECT * FROM tblPerson WHERE LastName = #Name AND Height > #Height AND BirthDate < #BirthDate", connection);
command.Parameters.AddWithValue("#Name", lastname);
command.Parameters.AddWithValue("#Height", height);
command.Parameters.AddWithValue("#Name", birthDate);
MySqlDataReader reader = command.ExecuteReader();
...
}
finally
{
connection.Close();
}
To those who have a similar problem using PHP, try the function utf8_encode($string). It just works!
I have this some problem, when my website encoding is utf-u and I tried to send in form CP-1250 string (example taken by listdir dictionaries).
I think you must send string encoded like website.

Categories