How can I write raw XML to a Label in ASP.NET - asp.net

I am getting a block of XML back from a web service. The client wants to see this raw XML in a label on the page. When I try this:
lblXmlReturned.Text = returnedXml;
only the text gets displayed, without any of the XML tags. I need to include everything that gets returned from the web service.
This is a trimmed down sample of the XML being returned:
<Result Matches="1">
<VehicleData>
<Make>Volkswagen</Make>
<UK_History>false</UK_History>
</VehicleData>
<ABI>
<ABI_Code></ABI_Code>
<Advisory_Insurance_Group></Advisory_Insurance_Group>
</ABI>
<Risk_Indicators>
<Change_In_Colour>false</Change_In_Colour>
</Risk_Indicators>
<Valuation>
<Value xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></Value>
</Valuation>
<NCAP>
<Pre_2009></Pre_2009>
</NCAP>
</Result>
What can I do to make this appear on the screen? I noticed that Stack Overflow does a pretty good job of putting the XML on the scren. I checked the source and it's using <pre> tags. Is this something that I have have to use?

It would be easier to use a <asp:Literal /> with it's Mode set to Encode than to deal with manually encoding Label's Text
<asp:Literal runat="server" ID="Literal1" Mode="Encode" />

You need to HtmlEncode the XML first (which escapes special characters like < and > ):
string encodedXml = HttpUtility.HtmlEncode(xml);
Label1.Text = encodedXml;
Surrounding it in PRE tags would help preserve formatting, so you could do:
string encodedXml = String.Format("<pre>{0}</pre>", HttpUtility.HtmlEncode(xml));
Label1.Text = encodedXml;
As Bala R mentions, you could just use a Literal control with Mode="Encode" as this automatically HtmlEncodes any string. However, this would also encode any PRE tags you added into the string, which you wouldn't want. You could also use white-space:pre in CSS which should do the same thing as the PRE tag, I think.

Related

New Line Character not Recognized in ASP .Net Text Box

I want to display the data with new line in text box. I am saving the comment in DB and then displaying the data on the UI.
The below is the .aspx code :-
<asp:TextBox ID="comment" TextMode="MultiLine" runat="server"
Rows="5" Columns="100" CssClass="multiline-text"></asp:TextBox>
Here is my DB Comment :-
This is test Comment./r/n Please do some reply on this.
How its showing on UI :-
This is test Comment./r/n Please do some reply on this.
Then I updated DB Comment :-
This is test Comment.<br /> Please do some reply on this.
How its showing on UI :-
This is test Comment.<br /> Please do some reply on this.
What I can change in asp .net file or in DB so that the data displays with new line in text box.
There are a few things to mention here:
You are actually using wrong escape sequences, it should be \r\n (backslash instead of slash)
If you get this data from somewhere else (e.g. the database), it probably would be correctly escaped
Consider check the string while debugging to verify what's actually coming from your source
When you've verified the text, you can then replace the necessary characters by correct escape characters:
Assuming this is coming as text in a variable myText:
This is test Comment.\r\n Please do some reply on this.
then you can think of This is test Comment.\\r\\n Please do some reply on this.
and you can do the following:
comment.Text = myText.Replace("\\r\\n", "\n"); // replace text "\r\n" by a new line escape sequence
You can use Wrap Property which display ASP.Net TextBox with multiline property to automatically continues on next line when it reaches the end.
<asp:TextBox ID="comment" TextMode="MultiLine" runat="server" Wrap="true" Rows="5" Columns="100" CssClass="multiline-text"></asp:TextBox>
Additionally, you can add this line in your css class to make sure proper lines break at <br> and preserve white space.
word-wrap: break-word;

Line breaks are being lost when sending text to the Database

For some reason the line breakes from ASP.NET textboxes are not being stored in my database.
I am using Server.HtmlEncode(txtAbout.Text) to take the text from the textbox.
This part works and text is taken out with line breaks.
But when I trace the text, the line breaks are lost after this line:
db.AddInParameter(dbCommand, "About", DbType.String, about);
db.ExecuteNonQuery(dbCommand);
In the stored procedure the varable #about is ntext.
In the table the column about is ntext
I hope someone can help.
Could you trace what the value of "about" is before sending it off to the stored procedure?
I suspect what is happening is when you are outputting the stored result, you are assigning it to a label. Rather output it to a literal:
<asp:Literal runat="server" id="litAbout" />
Then once you have done that, then do the "placement". For example:
litAbout.Text = Server.HtmlEncode(aboutText).Replace(Environment.NewLine, "<br/>");
Also, that is where you want to encode the output. You almost always only do the final transformations prior to outputting the result; the thinking is that you don't want to lose that raw input.
Outputting to a label isn't the problem. The problem is outputting it to a label without doing the replace Justin mentioned.
I just tested this in VS2010 (.NET 3.5) and it worked.
<asp:Label runat="server" ID="lblAbout" />
lblAbout.Text = Server.HtmlEncode(aboutText).Replace(Environment.Newline, "<br />");
This solution will work the same as the literal.

Using ASP <% .... %> Tags

I have been searching for this for quite a while and couldn't find a solution...
I have my aspx file and in it a asp:SqlDataSource, where I want to get values which are equal to the Request.QueryString["key"]. I have defined a parameter for it but I can't find the right syntax to set the value.
Currently it is looking like this:
<SelectParameters>
<asp:Parameter Name="courseID" DefaultValue="<%= Request.QueryString["course_name"]
</SelectParameters>
where I always get the error, it is not well formed. What is the correct syntax, and is there an article how you use this <%.. %> commands?
There's an MSDN page that goes over what each tag is and what it does. Probably using <%...%> is not correct, as that's just a code tag. You want <%=...%> or <%:...%> which actually write values to the page.
But! Actually, if I'm reading what your problem is correctly, you want neither of those. For a SqlDataSource to pull in a query string value, you want to add a <SelectParameters> tag to the datasource, then add a <QueryStringParameter> to that.
Edit:
Yep, looking at the edit you just made, you definitely want a QueryStringParameter.
You can't use <%= within high-level asp controls. That construct writes directly to the output buffer, whereas the controls need to be processed first. In other words, rather than processing your <%= before expanding the control, it must first expand the control before it can process your <%=. They are at different levels of abstraction.
To do what you want to accomplish, rather than a plain <asp:Parameter> use an <asp:QueryStringParameter>. This will allow you to set the key you want to use from the query string.

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

Possible Encoding Issue Reading HTM File using .Net Streamreader

I have an HTML file with a ® (copyright) and ™ (trademark) symbol in the text. These are just two among many other symbols. When I read the html file into a literal control it converts the symbols to something else.
The copyright symbol converts to � (open box in ff)
The trademark symbol converts to ™ (as expected)
If (System.IO.File.Exists(FullName)) Then
Dim StreamReader1 As New System.IO.StreamReader(FullName)
Contents.Text = StreamReader1.ReadToEnd()
StreamReader1.Close()
End If
Contents is a <asp:Literal runat="server" ID="Contents"></asp:Literal> and it's the only control in the aspx page.
From some research I think this is related to the encoding but I don't know why it would change how to fix it.
The html file does not contain any Content-Type settings in the head section.
If it's at all possible to shift this processing to the Render method, you could use HttpResponse.WriteFile to see if it handles these characters better than the Literal control does. If you're doing nothing with the content of this file other than assigning it to the control and then letting it render, then you should be able to do this OK.

Resources