updating values in web.config - asp.net

I need to store an escaped html string in a key in web.config using the
KeyValueConfigurationElement.Save method built into framework 3.5. But when I try to do so,
it keeps escaping my ampersands.
Code looks like this:
strHTML = DecodeFTBInput(FTB1.Text)
FTB1.Text is a string of HTML, like this: <b><font color="#000000">Testing</font></b>
DecodeFTPInput uses the String.Replace() method to change < and > to < and >, and " to ".
Given the above string and function, let's say strHTML now contains the following:
<b><font color="#000000">Testing</font></b>
Of course I can manually edit web.config to store the correct value, but I need the authenticated admin user to be able to change the html themselves.
The problem is that when I try to save this string into its key in web.config, it escapes all ampersands
as & which ruins the string.
How can I get around this?

web.config is an XML file, so when it writes values there the .NET Framework stores strings using HTML encoding, replacing the < > & characters with <, > and &, and much more besides.
You'll need to stop your DecodeFTPInput method from HTML encoding the string if you want the HTML in the web.config file to be editable. Otherwise you'll be HTML encoding twice, which isn't the result you want!

Related

cannot insert a string with & into the database from asp.net code

Here is a snippet of my code:
cmd.CommandText = "INSERT_ACS_STUDIES_DATA";
cmd.Parameters.AddWithValue("#mrn", mrn);
cmd.Parameters.AddWithValue("#log_id", crid);
cmd.Parameters.AddWithValue("#panel_id", panel_id);
cmd.Parameters.AddWithValue("#PROC_NAME", procName);
It fails when the vairable #PROC_NAME has a value with & in it - e.g. A & A
What is the correct syntax to insert strings which have these characters?
It sails because when using C# parameters you need to encode all special characters. C# will reject unencoded special characters to help prevent SQL Inject Attacks. You can use HttpServerUtility.HtmlEncode(string) to encode it.

ASP.NET - Reading quoted text from local resource file

i'm using a little javascript in my website for my navigation bar, which is made up of a few ImageButton controls. in the code behind i have this:
Dim homeImage As String = GetLocalResourceObject("HomeImage")
imgBtnHome.Attributes.Add("OnMouseOver", HomeImage)
and in the resx file, i've tried these, but they don't work: (note the single and double quotes)
key: HomeImage value: "this.src='images/HomeImage.gif'"
key: HomeImage value: "this.src=&apos;images/HomeImage.gif&apos;"
can anyone tell me what i'm doing wrong? is it even possible to read "quoted" text from a local resource file?
Yes, you can store quotes in a resx string value. If you look at the XML that's generated for a resource file, you'll see that the quotes are in the value entries.
However, your script isn't going to work with quotes around it. Think of it this way - say you wanted to pop up an alert box. You would do:
imgBtnHome.Attributes.Add("OnMouseOver", "alert('hi')")
NOT
imgBtnHome.Attributes.Add("OnMouseOver", """alert('hi')""");
You're passing in a string value for the script, not a quoted string value. Try removing the double quotes altogether, and leave the single quotes.

html injection question

Using FreeTextBox, I'm capturing HTML-formatted text. The purpose is to allow a website owner to update their web page content on a few pages. I have the system completed except for knowing what to do with the resultant HTML markup.
After the page editor completes their work, I can get the output from FreeTextBox, in html format, like so: <font color="#000080"><b>This is some text.</b></font>
I tried storing it as escaped markup in web.config, but that didn't work since it kept hosing the tags even after I changed them to escaped characters, like so: <font color="#000080">
The reason I wanted to store this kind of string as a key in web.config is that I could successfully store a static string, set a lebel's value to it, and successfully render the text. But when I try to escape it, it gets reformatted in web.config by .Net somehow.
So I escaped all the characters, encoded them as Base64 and stored that. Then on page_load, I tried to decode it, but it just shows up as text, with all the html tags showing as well - it doesn't get rendered. I know a million people use this control, but I'm damned if I can figure out how to do it right.
So here's my question: how can I inject the saved HTML into an edited page so it shows up in browsers like the editor wants it to look?
Try Server.HtmlDecode to output the HTML to the screen.
As a side note, I prefer to use CKEditor for html-formatted input. I found it is the better option among all options (FreeTextBox, TinyMCE, anything else?) and it has got completely rewritten and faster in the version 3.0!
In case anyone comes here for the answer, here's one way to do it.
I had initial problems with web.config changing some of the HTML tags upon storage, so we use B64 encoding (may not be necessary). Store the saved html markup to an AppSettings key in web.config as Base64 encoding, using this for your setting update function. Add error checking and whatever else you need it to do:
'create configuration object
Dim cfg As Configuration
cfg = WebConfigurationManager.OpenWebConfiguration("~")
'get reference to appsettings("HTMLstring")
Dim HTMLString As KeyValueConfigurationElement = _
CType(cfg.AppSettings.Settings("HTMLstring"), KeyValueConfigurationElement)
'get text entered by user and marked up with HTML tags from FTB1, then
'encode as Base64 so we can store it as XML-safe string in web.config
Dim b64String As String = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(FTB1.Text))
'save new value into web.config
If Not HTMLString Is Nothing Then
HTMLString.Value = b64String
cfg.Save()
End If
Next, add a Literal control to the aspx markup:
<asp:Literal id="charHTML" runat="server"/>
To add the saved HTML to the post-edited page, do the following in Page_Load:
'this string of HTML code is stored in web.config as Base64 to preserve XML-unsafe characters that come from FreeTextBox.
Dim injectedHTML As String = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(AppSettings("HTMLstring")))
'the literal control will directly inject this HTML instead of encoding it
charHTML.Mode = LiteralMode.PassThrough
'set the value
charHTML.Text = injectedHTML
Hope this helps. sF

How does one pass string contains '\' from from asp.net server side to Javascript function?

How does one pass string contains '\' from from asp.net
server side to javascript function?
After checking parameters at client side, all '\' replaced with '' even,
replacing '\' with '%5C' at server side doesn't work.
Any idea?
\ is a special character - basically it "escapes" the character after it. Try passing \\ instead. BTW - if you're using C# you can use the # character before a string to avoid needing to pass it as a double slash, e.g.
string path = #"c:\documents\mydocuments";
I got solution for that.
parameter.Replace("\\", "\\\\") solve it.
Are you using ASP.NET to write a JavaScript string literal? ie. something like:
Page.RegisterStartupScript("foo",
"<script type='text/javascript'>"+
" var bar= '"+myBarValue+"';"+
"</script>"
);
If so, then you are embedding text inside a delimited JavaScript string literal and you must use an escaping scheme that follows the syntax for string literals. In particular any \ character inside the text must be escaped with \\, and any ' character must be replaced by \', since that's the delimiter being used in this case (JavaScript can use either type of quote to delimit strings).
What's more if you're using an inline <script> block like in the above example, you're actually embedding text in a string literal in an HTML element, so you have to do some HTML escapes too. In particular you have to break up any </ sequences in the text, because that would end the script block. Also, in XHTML, there are no CDATA elements, so you'd also have to ampersand-escape any < or & characters in the text, except that would make it incompatible with legacy-HTML parsers. So to solve all these problems it is better to use JavaScript string literal escapes for that too, replacing < with \x3C and & with \x26.
Ideally what you would do would be to pass the simple string to a JSON encoder library, which would take care of escaping it appropriately for JavaScript. However I don't know of one for .NET that will escape the HTML for you as above, so you'd still need some replaces.

How to stop .NET from encoding an XML string with XML.Serialization

I am working with some Xml Serialization in ASP.NET 2.0 in a web service. The issue is that I have an element which is defined such as this:
<System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=True)> _
Public Property COMMENTFIELD() As String
Get
Return CommentField ' This is a string
End Get
Set(ByVal value as String)
CommentField = value
End Set
End Property
Elsewhere in code I am constructing a comment and appending
as a line-break (according to the rules of the web service we are submitting to) between each 'comment', like this: (Please keep in mind that
is a valid XML entity representing character 10 (Line Feed I believe).
XmlObject.COMMENTFIELD = sComment1 & "
" & sComment2
The issue is that .NET tries to do us a favor and encode the & in the comment string which ends up sending the destination web service this: &#xA;, which obviously isn't what we want.
Here is what currently happens:
XmlObject.COMMENTFIELD = sComment1 & "
" & sComment2
Output:
<COMMENTFIELD>comment1 &#xA comment2</COMMENTFIELD>
Output I NEED:
<COMMENTFIELD>comment1
comment2</COMMENTFIELD>
The Question Is: How do I force the .NET runtime to not try and do me any favors in regards to encoding data that I already know is XML compliant and escaped already (btw sComment1 and sComment2 would already be escaped). I'm used to taking care of my XML, not depending on something magical that happens to escape all my data behind my back!
I need to be able to pass valid XML into the COMMENTFIELD property without .NET encoding the data I give it (as it is already XML). I need to know how to tell .NET that the data it is receiving is an XML String, not a normal string that needs escaped.
If you look at the XML spec section 2.4, you see that the & character in an element's text always used to indicate something escaped, so if you want to send an & character, it needs to be escaped, e.g., as & So .Net is converting the literal string you gave it into valid XML.
If you really want the web service to receive the literal text &, then .NET is doing the correct thing. When the web service processes the XML it will convert it back to the same literal string you supplied on your end.
On the other hand, if you want to send the remote web service a string with a newline, you should just construct the string with the newline:
XmlObject.COMMENTFIELD = sComment1 & "\n" & sComment2
.Net will do the correct thing to make sure this is passed correctly on the wire.
It is probably dangerous to mix two different encoding conventions within the same string. Since you have your own convention I recommend explicitly encoding the whole string when it is ready to send and explicitly decoding it on the receiving end.
Try the HttpServerUtility.HtmlEncode Method (System.Web) .
+tom

Resources