Simplify e-mail body in string? - asp.net

I'm just wondering about this one. I'm creating an ASP.NET webform containing lots of textboxes etc. And I want to send an e-mail based on this stuff.
And the e-mails body needs to go into a string.
And the string is supposed to contain HTML code, but the syntax changes because of the string. So how can I simplify this? Is there any software or something that lets me do this? Perhaps paste in some HTML code and then convert this to string format, ready to use with vb.net?

If I understand correctly, you are wanting to generate an HTML email from user input via textboxes. If so, you can easily generate HTML using the HtmlTextWriter:
StringBuilder sb = new StringBuilder();
using(HtmlTextWriter writer = new HtmlTextWriter(new StringWriter(sb)))
{
writer.WriteBeginTag("span");
writer.WriteAttribute("style", "font-weight:bold;");
writer.Write(HtmlTextWriter.TagRightChar);
writer.Write(textboxName.Text);
writer.WriteEndTag("span");
}
return sb.ToString();
The above will generate a string which looks like:
<span style="font-weight:bold;">user input</span>
The HtmlTextWriter makes it very easy to ensure your markup is semantically correct and valid by mimicking the XML writers.

For converting a HTML formatted string back to plain text try this link,
[http://www.dreamincode.net/code/snippet1578.htm][Strip HTML from string using Regular Expressions]
This will only strip the tags and doesn't remove the html symbols like an ampersand but it will get you started.

Related

How to effectively load in dataTable an XML string that contains html string in its nodes. asp.net 4.0

I want to load XML in a single table of a dataset. I use following code
string val = getAbonentInfoParametr(ai,"abonentDescription");
DataSet ds = new DataSet();
ds.ReadXml(new StringReader(val));
but when I do this, I got three tables because in one node of XML file I now get HTML code that I want to have like a string field in my only table. What should I do?
Also I prefer not to use scheme files because the structure of that xml file can be changeable except several field that I use, please suggest me something.
Use CDATA to wrap around the HTML, otherwise there is no way to differentiate HTML from XML.

How should I store comments in database so that I can efficiently display them on page as html text?

I have a form where use enters multiple line of texts in a text area.
Some of the lines can have html markups as well. Say one line is bold.
How should I save the text in my database?
Should I store them as like this?
This is a greap post
<br/>
I love this type of findings.
<br/>
<br/>
Thanks for sharing
OR like this?
This is a greap post
<br/>
I love this type of findings.
<br/>
<br/>
Thanks for sharing
During editing:
I must show the text as they were entered. So line break will be replaced by new line
That way use sees there is a line break. Textarea won't unserstand br markup
During displaying:
I must render the text so that it appears like this on the page:
This is a greap post
I love this type of findings.
Thanks for sharing
I want to know the cleanest way to store text that can have markup in them.
Thanks for help
Since you want to output HTML, you will have to store the input in it's raw format in the database. There is only one catch though. You never should trust input, since all input is evil, especially in this case, since outputting HTML directly as it is inputted, opens the possibility of an cross-site scripting (XSS) attack.
You have basically got two options:
Use a HTML sanitizer that let's you remove all tags that are not known to be safe. A good sanitizer is the one that comes with the Microsoft AntiXss toolkit.
Encode the input and decode parts of the result that are known to be safe, for instance:
string[] safeList = { "<br/>", "<b>", "</b>", "<i>", "</i>" };
public static string EncodeInputWithSafeList(string unsafeInput)
{
// First: encode the complete input.
string safeInput = Encoder.HtmlEncode(unsafeInput);
// Next: decode each tag that is known to be safe.
foreach (string safeTag in safeList)
{
string encodedTag = Encoder.HtmlEncode(safeTag, false);
safeInput = safeInput.Replace(encodedTag, safeTag);
}
return safeInput;
}
Note: The example uses the Encoder class from the Microsoft AntiXss toolkit.
Now the question becomes, at what point should we clean it up. Normally you should encode the output just before you send it to the client and not store it encoded in the database, since it depends on the output type (HTML, PDF, JSON) how data should be encoded. This is amplified by the fact that in case there is a bug in the encoder, there is no way to fix it, since the data is already encoded.
In this case it is a bit more tricky though, since the input is HTML and not just text. I would say that sanitizing is something you still would want to do before hand, because this way you prevent bad input from entering your database. The EncodeInputWithSafeList method is a bit tricky, because it is both a sanitizer and an encoder. When we run it before it goes into the database, it prevents the output from changing when we change the safe list. This can be both a good thing and a bad thing, but I would say that when you add new tags to the safe list, you wouldn't want old data to suddenly change. So in this case I would go with input encoding, instead of output encoding.
When you go with input encoding, name the database column in such way that it is clear that we're dealing with sanitized, encoded data.
Try htmlentities($str, ENT_QUOTES); before you save the data, and html_entity_decode($str) after you fetch it from your db, before you render it to the browser.
saving it to your database like this:
<p>This is a greap post
<br/>
I love this type of findings.
<br/>
<br/>
Thanks for sharing</p>
would work..

Emitting unencoded strings in a Razor view

As ScottGu says in his blog post «by default content emitted using a # block is automatically HTML encoded to better protect against XSS attack scenarios».
My question is: how can you output a non-HTML-encoded string?
For the sake of simplicity, pls stick to this simple case:
#{
var html = "<a href='#'>Click me</a>"
// I want to emit the previous string as pure HTML code...
}
This is my favorite approach:
#Html.Raw("<p>my paragraph text</p>")
Source was Phil Haack's Razor syntax reference: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx
You can create a new instance of MvcHtmlString which won't get HTML encoded.
#{
var html = MvcHtmlString.Create("<a href='#'>Click me</a>")
}
Hopefully there will be an easier way in the future of Razor.
If you're not using MVC, you can try this:
#{
var html = new HtmlString("<a href='#'>Click me</a>")
}
new HtmlString is definitely the answer.
We looked into some other razor syntax changes, but ultimately none of them ended up really being any shorter than new HtmlString.
We may, however, wrap that up into a helper. Possibly...
#Html.Literal("<p>something</p>")
or
#"<p>something</p>".AsHtml()
I'm using ASP.NET MVC and Razor under Mono.
I couldn't get HtmlHelper from System.Web.WebPages of System.Web.Mvc for some reasons.
But I managed to output unencoded string after declaring model's property as RazorEngine.Text.RawString. Now it outputs as expected.
Example
#{
var txt = new RawString("some text with \"quotes\"");
var txt2 = "some text with \"quotes\"";
}
<div>Here is unencoded text: #txt</div>
<div>Here is encoded text: #txt2</div>
Output:
<div>Here is unencoded text: some text with "quotes"</div>
<div>Here is encoded text: some text with "quotes"</div>
I ran into this problem as well when transitioning our project to the new Razor view engine. The approach I took was slightly different because we had to generate JSON data from C# and wanted to output it upon page load.
What I eventually did was to implement a RawView that was a parallel of View inside of the cshtml files. Essentially, to get a raw string,
#(new HtmlString(View.Foo))
// became
#RawView.Foo
This requires a few changes to the project layout, so I just wrote up a blog post about it here. In short, this required a duplicate implementation of MVC's DynamicViewDataDictionary and a new WebViewPage that contains the RawView. I also went ahead and implemented the index operator on the RawView to allow for
#RawView["Foo"]
In the off-chance that someone needs to loop over the data with a list of keys.
Reading anurse's comment, it probably would have been better off if I had named this as a Literal instead of RawView.

how to get xml html after transpose and databind()

I have some code that uses xsl and xml.
The Xml control is on the design page.
The xml control id is xmlApplication
The xmlstring is generated and xsl has the format with all the tables and cells etc.
Here is a part of thecode of a page which generates the final product which shows the xml in a certain format.
xmlApplication.Document = xmlDoc;
xmlApplication.Transform = transApp;
xmlApplication.DataBind();
I am guessing after xmlApplication.Databind(), xmlApplication will be converted into something that can be put inside .
Is it possible to grab as a string?
Please let me know if I have a wrong idea abut this.
Thanks a lot.
http://www.logiclabz.com/c/net-c-function-to-convert-xml-document-into-html-string-using-xslt.aspx

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

Resources