ConfigurationManager.AppSettings convert "\n" to "\\n" why? - asp.net

I have a AppSetting in web.config.
<add key="key" value="\n|\r"/>
When i read it by ConfigurationManager.AppSettings["key"] it gives "\\n|\\r".
Why ?

In the debugger, becuase the backslash is a special character used for things like tabs (\t) and line endings (\n), it has to be escaped by the use of another backslash. Hence any text that contains an actual \ will be displayed as \. If you print it out to a file or use it in any other way, you will find your string only contains the one .
This isn't ConfigurationManager doing anything.

The backslash escaping syntax is only recognized inside of string literals by the C# compiler. Since your string is being read from an XML file at runtime, you need to use XML-compatible escaping (character entities) in order include those characters in your string. Thus, your app settings entry should look like the following:
<add key="key" value="&x10;|&x13;"/>
Because 10 and 13 are the hex values for linefeed and carriage return, respectively.
Like cjk said, the extra slash is being inserted by the debugger to indicate that it is seeing a literal slash and not an escape sequence.

I solved the same problem with a string replacement.
Not beautful.. but works!
ConfigurationManager.AppSettings["Key"].Replace("\\n", "\n")

string str = "\n";// means \n
string str1 = #"\n";// means \\n
From the AppSettings, It seems that when you extract the key's value, # is internally wrapped.. It is done by the compiler not runtime.

Related

Warning on regex string in Python

So, I am doing a small function to strip all the weird chars from a string, eg. #$& will be replaced just for a " "
The chars I am trying to remove are the following, defined into a string:
xChars = r"#$%()'^*\;:/|+_.–°ªº"
However I kepp getting the warning:
Anomalous backslash in string: '\;'. String constant might be missing an r prefix
However, when i used the r prefix eg. r"\" python rules out some of the special chars i want to replace. It doesnt produce an error it just thinks that those chars are ok or something and it rules them out.
Any ideas on how to fix this ?
Normally backslashes escape characters, therefore the compiler isn´t sure if the backslash has to be escaped. Maybe try using a double backslash to escape the backslash itself like: xChars = r"#$%()'^*\\;:/|+_.–°ªº"

How to escape quotechar in opencsv CSVReader. Default quotechar is (") double quote

The data which I am passing through CSV file contain text as - 1 Micron Filter Cartridge 10"-(DNL). I want to escape " in the text.
Create a CSVReader with a RFC4180Parser and that will allow the data you listed above.
The default CSVReader uses a CSVParser and for that you need to use a \ character, unless you set a different escape character, to let the CSVParser know the quote is just another character in the string and not to be acted upon.
Hope that helps.
Scott :)

Escaping backslash (\) in string or paths in R

Windows copies path with backslash \, which R does not accept. So, I wanted to write a function which would convert \ to /. For example:
chartr0 <- function(foo) chartr('\','\\/',foo)
Then use chartr0 as...
source(chartr0('E:\RStuff\test.r'))
But chartr0 is not working. I guess, I am unable to escape /. I guess escaping / may be important in many other occasions.
Also, is it possible to avoid the use chartr0 every time, but convert all path automatically by creating an environment in R which calls chartr0 or use some kind of temporary use like using options
From R 4.0.0 you can use r"(...)" to write a path as raw string constant, which avoids the need for escaping:
r"(E:\RStuff\test.r)"
# [1] "E:\\RStuff\\test.r"
There is a new syntax for specifying raw character constants similar to the one used in C++: r"(...)" with ... any character sequence not containing the sequence )". This makes it easier to write strings that contain backslashes or both single and double quotes. For more details see ?Quotes.
Your fundamental problem is that R will signal an error condition as soon as it sees a single back-slash before any character other than a few lower-case letters, backslashes themselves, quotes or some conventions for entering octal, hex or Unicode sequences. That is because the interpreter sees the back-slash as a message to "escape" the usual translation of characters and do something else. If you want a single back-slash in your character element you need to type 2 backslashes. That will create one backslash:
nchar("\\")
#[1] 1
The "Character vectors" section of _Intro_to_R_ says:
"Character strings are entered using either matching double (") or single (') quotes, but are printed using double quotes (or sometimes without quotes). They use C-style escape sequences, using \ as the escape character, so \ is entered and printed as \, and inside double quotes " is entered as \". Other useful escape sequences are \n, newline, \t, tab and \b, backspace—see ?Quotes for a full list."
?Quotes
chartr0 <- function(foo) chartr('\\','/',foo)
chartr0('E:\\RStuff\\test.r')
You cannot write E:\Rxxxx, because R believes R is escaped.
The problem is that every single forward slash and backslash in your code is escaped incorrectly, resulting in either an invalid string or the wrong string being used. You need to read up on which characters need to be escaped and how. Take a look at the list of escape sequences in the link below. Anything not listed there (such as the forward slash) is treated literally and does not require any escaping.
http://cran.r-project.org/doc/manuals/R-lang.html#Literal-constants

Escape quote in web.config connection string

I have a connection string in my web config:
<add name="MyConString" connectionString="Server=dbsrv;User ID=myDbUser;Password=somepass"word" providerName="System.Data.SqlClient" />
As you see, there is a quotation sign ( " ) in the password (given from other dept. I can't change this db users password).
How do I have to escape the quote in this connection string?
Btw: I already tried & quot; in the string. That didn't work - ado.net got an ArgumenException then: "Format of the initialization string does not conform to specification starting at index 57."
57 is where the & quot; is in my connection string.
I also tried enclosing the password part in ' - didn't work either.
Also tried "" and \" - web.config can't be parsed then.
Thanks for the solution:
I had to combine the escaping of the double quote and putting the password in single quotes:
<add name="MyConString" connectionString="Server=dbsrv;User ID=myDbUser;Password='somepass"word'" providerName="System.Data.SqlClient" />
Use " instead of " to escape it.
web.config is an XML file so you should use XML escaping.
connectionString="Server=dbsrv;User ID=myDbUser;Password=somepass"word"
See this forum thread.
Update:
" should work, but as it doesn't, have you tried some of the other string escape sequences for .NET? \" and ""?
Update 2:
Try single quotes for the connectionString:
connectionString='Server=dbsrv;User ID=myDbUser;Password=somepass"word'
Or:
connectionString='Server=dbsrv;User ID=myDbUser;Password=somepass"word'
Update 3:
From MSDN (SqlConnection.ConnectionString Property):
To include values that contain a semicolon, single-quote character, or double-quote character, the value must be enclosed in double quotation marks. If the value contains both a semicolon and a double-quote character, the value can be enclosed in single quotation marks.
So:
connectionString="Server=dbsrv;User ID=myDbUser;Password='somepass"word'"
The issue is not with web.config, but the format of the connection string. In a connection string, if you have a " in a value (of the key-value pair), you need to enclose the value in '. So, while Password=somepass"word does not work, Password='somepass"word' does.
connectionString="Server=dbsrv;User ID=myDbUser;Password=somepass"word"
Since the web.config is XML, you need to escape the five special characters:
& -> & ampersand, U+0026
< -> < left angle bracket, less-than sign, U+003C
> -> > right angle bracket, greater-than sign, U+003E
" -> " quotation mark, U+0022
&apos; -> ' apostrophe, U+0027
+ is not a problem, I suppose.
Duc Filan adds:
You should also wrap your password with single quote ':
connectionString="Server=dbsrv;User ID=myDbUser;Password='somepass"word'"
if " isn't working then try " instead.
Odeds answer is almost complete. Just one thing to add.
Escape xml special chars like Emanuele Greco said.
Put the password in single quotes like Oded said
(this one is new) Escape single ticks with another single tick (ref)
having this password="'; this sould be a valid connection string:
connectionString='Server=dbsrv;User ID=myDbUser;Password='"&&;'
Use " That should work.

ASP.NET Server.HtmlEncode Limitations

I'm using Server.HTMLEncode to encode my HTML.
I notice it dosn't escape single quotes, which is a limitation if your using single quotes in your html e.g.
<input type='text' .... />
(I've checked this is valid XHTML).
Are there any other limitations or things to note about Server.HTMLEncode, in particular any characters that are not valid XHTMl that this method dosn't deal with?
MSDN says Server.HTMLEncode only does the following:
The less-than character (<) is converted to &lt ;.
The greater-than character (>) is converted to &gt ;.
The ampersand character (&) is converted to &amp ;.
The double-quote character (") is converted to &quot ;.
Any ASCII code character whose code is greater-than or equal to 0x80 is converted to &#< number>, where number is the ASCII character value.
To include single quote encoding, I use (in VB.Net):
Server.HTMLEncode("Here's a string with a single quote").Replace("'", "'")
I've tested HTmlENcode against all the character codes listsed here http://www.ascii.cl/htmlcodes.htm
It appears it escapes most characters, and those that it dosn't escape dont break XHTML compliance
HTML Encode should ensure all non-HTML compliant characters in a string are converted to their equivalent entity. As you discovered, single quotes etc. are perfectly valid in (X)HTML and do not require encoding. You could use UrlEncode/UrlDecode if you require this, or roll your own function using Replace.
I came here searching for the same answer. In my case the solution was to actually... use double quotes in your surrounding HTML ..

Resources