How to clean parse HTML code to string - c#

I need to parse html code into string, because i'm later using it as my body content of email message:
Is there a way to parse html code like this:
<div class="alert alert-success" role="alert">
<h4 class="alert-heading">Well done!</h4>
<p>You have successfully subscribed!</p>
<hr>
<p class="mb-0">We will be sending you newsletter on weekly basis.</p>
</div>
into string in a clean way, without doing it like this:
string body = #"<div class=""alert alert-success"" role=""alert"">" + "</div>"
so i could pass it to mail like this:
MailMessage mailMessage = new MailMessage();
mailMessage.Body = body;
instead of having a whole series of html code inside string there.
Is there maybe any other "way" to make "design" for email messages?
PS: i also do not want to load html from external file
I would like to use html code to have a decent design for subscribing to newsletter message on email.
Thank you!

/*
If they are static and don't need to be read from a file, as you've indicated, I would create a project->property->resource string for each message. You can paste the email body into a string variable and then just access it like this:
*/
string body = MyNamespace.Properties.Resources.emailBody1;
/* the string will be formatted with all the quotes and \r\n just as it was from what you pasted in. */
// you could even add some substitution to customize the email
body.Replace("{EmailRecipient}", strEmailRecipient);

Since you are using C#, you can use String interpolation. http://www.informit.com/articles/article.aspx?p=2422807
You can create a template object were you can pass all the necessary variables for your message.
e.g
class WelcomeEmail {
public WelcomeEmail(String message, String title) {
}
public override string ToString() {
}
}

Related

C# asp.net mail.body text

Situation:
1)I want to send a email with body text, like below.
Problem:
1)I have different variables that need to insert into the mail.body. But it can only show the first variable "name".
2)How can I leave the space or shift between lines in mail.body text?
mail.Body = string.Format("Thank you for online maintanence {0}. Your details is as following: Model:{0} colour:{0}Storage:{0}type of maintanence:Also , Your choose {0} for your phone retake location Any queries , Please contact 16681668 to our office! ", name ,clientid,model,colour,storage,type,Location,contactno);
Because you say so. You always used {0} for every variable that's why it always shows the first one.
Increase your {0} index every time by 1. Like;
mail.Body = string.Format("Thank you for online maintanence {0}. Your details is as following: Model:{1} colour:{2} Storage:{3} type of maintanence: Also, Your choose {4} for your phone retake location Any queries , Please contact 16681668 to our office! ",
name ,clientid,model,colour,storage,type,Location,contactno);
In such a case, your type,Location,contactno variables will be unnecessary since you didn't define them any {} in your string.
I would take a different approach if I were you. Generating formatted emails from code like that is just ugly. And using String.Format() to insert your values into your template? Ugh, that's a mess if you ever need to change the order or add new items!
There is a tool called Postal that allows you to use the Razor layout syntax to generate emails. This promotes separation of concerns, your logic for sending the email is no longer coupled to the logic that determines the layout for the email body. It's easier to write, because you won't need to write HTML inside a string inside C#. I'll show you how to do it with a strongly typed model.
public class MailInfo : Email
{
public string Name {get; set;}
public string ClientId {get; set;}
public string Model {get; set;}
public string Colour {get; set;}
public string Storage {get; set;}
public string Type {get; set;}
public string Location {get; set;}
public string ContactNo {get; set;}
}
The MailInfo will hold all the data we want to use to generate the email. We would create an instance of the class and populate it.
var email = new MailInfo();
email.Name = "Bob";
email.ClientId = "A57C";
//set rest of properties
Then we create the Razor layout (.cshtml) file, and the layout file is going to declare that it needs an instance of our MailInfo class on the first line. Sine we did that, we can embed properties from MailInfo class into your email by using the #Model.PropertyName syntax.
#model MailInfo
<p>Thank you for online maintanence #Model.Name. Your details are as follows:</p>
<ul>
<li>Model: #Model.Model</li>
<li>Colour: #Model.Colour</li>
<li>Storage: #Model.Storage</li>
<li>Type: #Model.Type</li>
</ul>
<p>Also, you choose #Model.Location for your phone retake location. Any questions, please contact our office at 16681668!</p>
All that's left is to create the MailMessage, passing the instance of MailInfo that we created above, and send it.
MailMessage mail = new EmailService().CreateMailMessage(email);
//send mail like you would any other MailMessage, populating To, From, Subject etc.
(I did simplify the code slightly, not showing using declarations, where to put the .cshtml file, or how to install Postal via NuGet. Let me know if you want me to flesh the answer out more.)
What you can do is using '#' character before the string in order to split the text on multiple lines.
string mailTemplate = #"Thank you for online maintanence {0}. <br />
Your details is as following: <br />
Model:{0} <br />
colour:{0} <br />
Storage:{0} <br />
type of maintanence: <br />
Also , Your choose {0} for your phone retake location Any queries ,
Please contact 16681668 to our office! ";
mail.Body = string.Format(
mailTemplate,
name,
clientid,
model,
colour,
storage,
type,
Location,
contactno);
make sure that you set the IsBodyHtml property to true.
mail.IsBodyHtml = true;
You can also use this approach:
mail.IsBodyHtml = true;
mail.Body += "This is some text";
mail.Body += "<br />";
mail.Body += "This a variable: " + variableName;
<br /> would insert the line break.

Dynamic Html Attribute format in Razor

How can I format my own attribute in the codebehind?
The idea is to overwrite CSS inline style so I added a property to my Model.
public string GetBannerBackgroundStyle
{
get
{
return !string.IsNullOrEmpty(GetBannerImageMediaUrl) ? string.Format("style=background-image: url('{0}')", GetBannerImageMediaUrl) : string.Empty;
}
}
In the view I simply set the property on the HTML
<div class="anything" #Model.GetBannerBackgroundStyle></div>
The output however is scrambled. It generates something but not properly as if the quotes weren't closed.
Any better ideas?
Thanks in advance!
UPDATE:
public HtmlString GetBannerBackgroundStyle
{
get
{
return new HtmlString(!string.IsNullOrEmpty(GetBannerImageMediaUrl) ? string.Format("style=background-image: url('{0}')", GetBannerImageMediaUrl) : string.Empty);
}
}
This didn't seem to work :s
UPDATE2:
public IHtmlString GetBannerBackgroundStyle
{
get
{
return new HtmlString(!string.IsNullOrEmpty(GetBannerImageMediaUrl) ? string.Format("style=\"background-image: url('{0}')\"", GetBannerImageMediaUrl) : string.Empty);
}
}
This did work ^^
From MSDN:
The Razor syntax # operator HTML-encodes text before rendering it to the HTTP response. This causes the text to be displayed as regular text in the web page instead of being interpreted as HTML markup.
That's where you can use Html.Raw method (if you don't want/can't change your property to return an HtmlString, please remember that right way to do it is that one as suggested by SLaks):
Use the Raw method when the specified text represents an actual HTML fragment that should not be encoded and that you want to render as markup to the HTTP response.
<div class="anything" #Html.Raw(Model.GetBannerBackgroundStyle)></div>
That said I wouldn't put that logic inside your model. An helper method, some JavaScript...but I wouldn't mix styling with data. In your example it should be:
<div class="anything"
style="background-image: url('#Model.GetBannerImageMediaUrl')">
Please note that your code was also wrong because you're missing quotes for HTML style attribute:
if (!String.IsNullOrEmpty(GetBannerImageMediaUrl))
return String.Empty;
return String.Format("style=\"background-image: url('{0}')\"", GetBannerImageMediaUrl);
---^ ---^
You need to make your property return an IHtmlString to tell Razor to not escape it.
First, however, you need to properly escape it yourself, in case the URL has tags or quotes.
How about the code snippet below?
<div class="anything" #(Model != null && !string.IsNullOrWhiteSpace(GetBannerImageMediaUrl)
? "style=background-image: url('" + GetBannerImageMediaUrl + "')"
: string.Empty)></div>

printing some HTML in a string in Asp.net

i have some html content and i stored it in string variable and i want to print it directly.Is there any way in c# ?i have a javascript code which is not working
string emailbody="HTML i need to send";
Page.RegisterStartupScript("StatusMessage", "<SCRIPT LANGUAGE=\"JavaScript\">function printsheet(" + emailbody + "){var win = window.open('mywindow', 'left=0', 'top=0')var html = Zstring; win.document.open()win.document.write(html);win.print();}</Script>");
You have many ways to do that.
One way, make the string public
public string emailbody="HTML i need to send";
and on aspx page you render it as:
<%=emailbody%>
One other way is to use a Literal control and render it there. When you have UpdatePanel this is the only way.
Eg, you place the Literal on page, on the point you wish to render your text as:
<asp:Literal runat="server" id="txtRenderOnMe" />
and on code behind you type:
txtRenderOnMe.Text = "HTML i need to send";
Now, in your case the issue is that you render a string on the javascript code without the quotas as the other jesse point out on their comments.
string emailbody="HTML i need to send";
Page.RegisterStartupScript("StatusMessage", "<script language=\"JavaScript\">function printsheet('" + emailbody + "'){var win = window.open('mywindow', 'left=0', 'top=0')var html = Zstring; win.document.open()win.document.write(html);win.print();}</script>");

Format string to HTML in C#

So I am writing a game with Unity and I am sending players an email with all of their stats on how they played. The way I send the email is I format a string that has the html already written that replaces a specifier $_table to insert the data I need to send to a php script on my server that emails the user. All of this works.
I am having a problem though with sending links to images. Since I am doing this in a C# program I am having a hard time with <img src ="example.com/example.png"/> tags.
When it sends it sends it formated as <img src=\"example.com/example.png\"/> and doesn't show the image.
How can I send this string correctly in C#?
I have already tried " and using #"""" to format the string.
Any and all help is appreciated.
::Edit::
Updated for code.
So in my C# code I am reading from a txt file my base html. The problem is
when I am replacing with my table which has img tags in it.
I have a Email Function SendEmail which sends a form. In the form it has a
message parameter which is just a string. This form is sent to a php script
which sends to the email from the form.
//Unity Code
public static void SendEmail(string _email, string subject, string message)
{
if(CheckEmail(_email))//Checks if valid email form
{
WWWForm form = new WWWForm();
form.AddField("from", "example#example.com");
form.AddField("email", _email);
form.AddField("subject", subject);
form.AddField("message", message);
WWW web = new WWW("http://www.example.com/_email.php", form); //Unity class for various web functions
}
else
{
label.text = "Invalid Email";
}
}
The message I am sending is a table with img links which are referenced by string variables for readability.
public static string GetFormatedMetricTable(){
int time = 0;
string clockIcon = "<img src = "http://files.softicons.com/download/web-icons/web- grey-buttons-by-axialis-team/png/48x48/Clock.png"/>";
return "<table><tr><td>" + time + clockIcon + "</td></tr></table>";
}
The code above is reduced for this example but only content wise.
In my php code I am using a simple mail function to send the email from my smtp server.
The problem is in the string formatting of the double quote.
When viewed within the html code from the email I get /" which results in the images not showing.
Desired result http://subligaming.com/example.html
Note: Using Mono .Net
Here is my php code just incase.
<?php
$from = $_REQUEST['from'];
$name = $_REQUEST['name'];
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
// $newMessage = str_replace(""", '$_"', $message);
// $newerMessage = str_replace("$_", "", $newMessage);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: Subliminal Gaming <$from>\r\n";
mail($email, "$subject",
$message, $headers );
echo "Thank you for using our mail form";
?>
I am currently reading up on how the string literals work in php and that may be the problem but I do not know how to fix it. Any pointers?
Just try to use simple quotes in the html tag
<img src ='example.com/example.png'/>

How to display html elements like links in errors rendered via Html.ValidationSummary()

One of my error message renders a link. However, Html.ValidationSummary() encodes it and therefore it displays as follow:
An account with the mobile or email you have specified already exists.
If you have forgotten your password, please Reset it.
Instead, it should render as:
An account with the mobile or email you have specified already exists.
If you have forgotten your password, please Reset it.
The error is added to the ModelState inside view as follows:
if (...)
{
ViewData.ModelState.AddModelError(string.Empty, string.Format("An account with the mobile or email you have specified already exists. If you have forgotten your password, please {0} it.", Html.ActionLink("Reset", "Reset")));
}
In short, how should I prevent Html.ValidationSummarry() to selectively/entirely encoding html in errors.
The current HTML helpers for displaying error messages do not support this. However, you could write your own HTML helpers that display the error message without HTML escaping it, i.e. they would treat the error message as raw HTML.
As a starting point, you could use the ASP.NET MVC source code from Codeplex, specifically the ValidationSummary method of the ValidationExtensions class:
public static string ValidationSummary(this HtmlHelper htmlHelper, string message, IDictionary<string, object> htmlAttributes) {
// Nothing to do if there aren't any errors
if (htmlHelper.ViewData.ModelState.IsValid) {
return null;
}
string messageSpan;
if (!String.IsNullOrEmpty(message)) {
TagBuilder spanTag = new TagBuilder("span");
spanTag.MergeAttributes(htmlAttributes);
spanTag.MergeAttribute("class", HtmlHelper.ValidationSummaryCssClassName);
spanTag.SetInnerText(message);
messageSpan = spanTag.ToString(TagRenderMode.Normal) + Environment.NewLine;
}
else {
messageSpan = null;
}
StringBuilder htmlSummary = new StringBuilder();
TagBuilder unorderedList = new TagBuilder("ul");
unorderedList.MergeAttributes(htmlAttributes);
unorderedList.MergeAttribute("class", HtmlHelper.ValidationSummaryCssClassName);
foreach (ModelState modelState in htmlHelper.ViewData.ModelState.Values) {
foreach (ModelError modelError in modelState.Errors) {
string errorText = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, null /* modelState */);
if (!String.IsNullOrEmpty(errorText)) {
TagBuilder listItem = new TagBuilder("li");
listItem.SetInnerText(errorText);
htmlSummary.AppendLine(listItem.ToString(TagRenderMode.Normal));
}
}
}
unorderedList.InnerHtml = htmlSummary.ToString();
return messageSpan + unorderedList.ToString(TagRenderMode.Normal);
}
You can then change this method to treat the error message as raw HTML.
Two warnings though:
You're changing the meaning of certain properties of the ModelState class. While you get away with using your own HTML helpers now, a future version of ASP.NET MVC might introduce changes that no longer work with this approach.
Be very careful about not using error messages that aren't properly escaped so you don't expose your web app to XSS attacks. Certain standard validation annotation might not work any longer since they don't HTML escape the error message.

Categories