I want to create an HTML table with my c# program.
I've tried this:
internal string CreateMailBody(mailObj dataObj)
{
string body = string.Empty;
body +=
"Dear all, there is my new table:" +
"TableNo: " + dataObj.Obj.Table.TableNumber+ "<br /> <br />";
body += "<table border='1'><tr><th>Line No</th><th>Table</th><th>Description</th><th>Count</th><th>Met</th><th>something</th></tr>";
foreach (var item in dataObj.Table.TableLineCollection)
{
body += "<tr><td>" + item.LineNumber +"</td>";
body += "<tr><td>" + item.Table+"</td>";
body += "<tr><td>" + item.Description+"</td></tr>";
}
return body;
}
Will it give a better solution for this ?
You may mix StringBuilder using the method AppendFormat and string literals (# in from of a string, so you can write multiple lines).
StringBuilder body = new StringBuilder();
body.AppendFormat (
#"Dear all, there is my new table:
TableNo: {0} <br /> <br />
<table border='1'><tr><th>Line No</th><th>Table</th><th>Description</th><th>Count</th><th>Met</th><th>something</th></tr>"
, dataObj.Obj.Table.TableNumber);
foreach (var item in dataObj.Table.TableLineCollection)
{
body.AppendFormat(
#"<tr><td> {0}</td>
<tr><td> {1}</td>
<tr><td> {2}</td></tr>",
item.LineNumber, item.Table, item.Description);
}
Related
It's print double, I can't see any error of my code, I use match collection in regular expression, if match collection found 2 (youtube link). the function print 4 images. by the way the function get the youtube thumnails.
Plaintext:
string Plainttext = "This selection is automatically generated based on videos that were popular <br/>" +
" in the past few weeks. <br/>" +
" ------------------------------------------------------------------- \n" +
" 'Anniversary Prank Backfires!! \n" +
" http://www.youtube.com/watch?v=R7AXBOT8KzU&feature=em-hot \n" +
" by RomanAtwood " +
" 23,268,129 views " +
" ------------------------------------------------------------------- \n" +
" We Are The World for Philippines [TYPHOON HAIYAN] \n" +
" http://www.youtube.com/watch?v=1bI8pGLBagY&feature=em-hot \n" +
" by Kevin Ayson " +
" 3,607,584 views <br/>" +
" ------------------------------------------------------------------- <br/>" +
" end of text ";
Button:
protected void Button1_Click(object sender, EventArgs e)
{
Literal1.Text = GetYoutubeThumbnails(Plainttext);
}
Function:
string geturl;// static string id ;
protected string GetYoutubeThumbnails(string plaintext)
{
var youtuberegex = new Regex("youtu(?:\\.be|be\\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
StringBuilder sb = new StringBuilder();
MatchCollection matches = youtuberegex.Matches(plaintext);
ArrayList arrayURL = new ArrayList(matches);
// foreach (Match match in matches)
for (int i = 0; i <= arrayURL.Count-1 ; i++ )
{
geturl = arrayURL[i].ToString();
string id = string.Empty;
Match youtubeMatch = youtuberegex.Match(geturl);
id = youtubeMatch.Groups[1].Value;
// if(match.Success)
// {
sb.Append(string.Format(#"<table runat ='server'><tr> <td id = 'tduserPicture'
rowspan='1' style='text-align:left' runat='server'>
<img ID='Imagess2' runat='server' src='{0}' Height='80px' Width='100px' /alt='image'>
<br/> {1} </td> </tr></table>", "http://img.youtube.com/vi/" + id + "/0.jpg", "www." + geturl));
// }
}
plaintext = youtuberegex.Replace(plaintext, sb.ToString());
return plaintext;
}
Output:
Thanks
The problem is your modifying the text inside your loop, a separate output should be created rather than an in-place replace.
Don't even bother doing it like that, use a Regex.Replace callback function.
Knocked this together as a super quick sample
using System.IO;
using System;
using System.Collections;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string Plainttext = "This selection is automatically generated based on videos that were popular <br/>" +
" in the past few weeks. <br/>" +
" ------------------------------------------------------------------- \n" +
" 'Anniversary Prank Backfires!! \n" +
" http://www.youtube.com/watch?v=R7AXBOT8KzU&feature=em-hot \n" +
" by RomanAtwood " +
" 23,268,129 views " +
" ------------------------------------------------------------------- \n" +
" We Are The World for Philippines [TYPHOON HAIYAN] \n" +
" http://www.youtube.com/watch?v=1bI8pGLBagY&feature=em-hot \n" +
" by Kevin Ayson " +
" 3,607,584 views <br/>" +
" ------------------------------------------------------------------- <br/>" +
" end of text ";
MatchEvaluator evaluator = new MatchEvaluator(MatchFilter);
Console.WriteLine(Regex.Replace(Plainttext,
"youtu(?:\\.be|be\\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)", evaluator,
RegexOptions.IgnorePatternWhitespace));
}
static string MatchFilter(Match match) {
var id = match.Groups[1].Value;
var geturl = match.ToString();
return string.Format(#"<table runat ='server'><tr> <td id = 'tduserPicture'
rowspan='1' style='text-align:left' runat='server'>
<img ID='Imagess2' runat='server' src='{0}' Height='80px' Width='100px' /alt='image'>
<br/> {1} </td> </tr></table>", "http://img.youtube.com/vi/" + id + "/0.jpg", "www." + geturl);
}
}
This outputs the following:
This selection is automatically generated based on videos that were popular <br/> in the past few weeks. <br/> -------------------------------------------------------------------
'Anniversary Prank Backfires!!
http://www.<table runat ='server'><tr> <td id = 'tduserPicture'
rowspan='1' style='text-align:left' runat='server'>
<img ID='Imagess2' runat='server' src='http://img.youtube.com/vi/R7AXBOT8KzU/0.jpg' Height='80px' Width='100px' /alt='image'>
<br/> www.youtube.com/watch?v=R7AXBOT8KzU </td> </tr></table>&feature=em-hot
by RomanAtwood 23,268,129 views -------------------------------------------------------------------
We Are The World for Philippines [TYPHOON HAIYAN]
http://www.<table runat ='server'><tr> <td id = 'tduserPicture'
rowspan='1' style='text-align:left' runat='server'>
<img ID='Imagess2' runat='server' src='http://img.youtube.com/vi/1bI8pGLBagY/0.jpg' Height='80px' Width='100px' /alt='image'>
<br/> www.youtube.com/watch?v=1bI8pGLBagY </td> </tr></table>&feature=em-hot
by Kevin Ayson 3,607,584 views <br/> ------------------------------------------------------------------- <br/> end of text
I have a DataTable of records which I need to append as information to my Email template htm. Currently what I am doing here works fine but that is if I only have 1 row of record. How can I go about appending the htm template such that I can have multiple postings in the email
e.g Sample Email Screen (Assuming my DataTable returns 3 rows of record):
Dear Sir, your daily car posting results:
Image
Toyota
Cambry
$10000
Image
Honda
GT
$10000
Image
Nissan
Sunny
$10000
Loop DataTable row:
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
primaryImage = dr["PrimaryImage"].ToString();
email = dr["Email"].ToString();
postTitle = dr["Model"].ToString();
model = dr["Model"].ToString();
askingPrice = dr["AskingPrice"].ToString();
var mail = new Email();
mail.IsBodyHtml = true;
mail.MailAddresses = email;
mail.MailSubject = "Test";
mail.HtmFileName = "Email.htm";
var dict = new Dictionary<string, string>
{
{"<%PrimaryImage%>", primaryImage },
{"<%PostTitle%>", postTitle},
{"<%Model%>", model},
{"<%AskingPrice%", askingPrice}
};
mail.Dict = dict;
MailMessage mailMessage;
mailMessage = mail.CreateMailMessage();
Email.Send(mailMessage, 3, 3000, true);
}
}
Create Mail Message:
public MailMessage CreateMailMessage()
{
MailMessage mail = new MailMessage();
mail.IsBodyHtml = IsBodyHtml;
mail.From = new MailAddress("xxx#yahoo.com", "xxx");
mail.Bcc.Add(MailAddresses);
mail.Subject = MailSubject;
string body = "";
string filePath =
HttpContext.Current.Server.MapPath("~/" + ConfigurationManager.AppSettings["TEMPLATES"] + "/");
if (File.Exists(filePath + HtmFileName))
{
FileStream f = new FileStream(filePath + HtmFileName, FileMode.Open);
StreamReader sr = new StreamReader(f);
body = sr.ReadToEnd();
foreach (var pair in Dict)
{
body = body.Replace(pair.Key, pair.Value);
}
f.Close();
}
mail.Body = body;
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess |
DeliveryNotificationOptions.OnFailure;
return mail;
}
Portion of the Email.htm template:
<body>
<form id="form1" runat="server">
<div style="border: thin solid #E1E1E1; background-color: #F0F0F0; margin-bottom: 10px; padding-top: 3px; padding-bottom: 3px; padding-left:5px;">
Postings
</div>
<div>
<a><img src="<%PrimaryImage%>"/></a>
<br/><br/>
Sell Post Title: <%PostTitle%>
<br/><br/>
Model: <%Model%>
<br/><br/>
Asking Price: <%AskingPrice%>
</div>
</form>
</body>
#M.S : There must be some condition on the basis of which you will decide which attribute goes to which td. You can wrap up this logic in some method and generate a class name. Below is a way how you generate a classname on the basis of rownum.
var className="" ;
var rowNum=0;
foreach (var entry in dataTable)
{
className=GetClassName(rowNum)
innerHtml += "<tr>";
innerHtml += "<td class='"+ className +"'>" + entry.PrimaryImage + "</td> ";
innerHtml += "</tr>";
rowNum++;
}
public static string GetClassName(int rowCount)
{
switch (rowCount)
{
case 1:
return "class1";
case 2:
return "class2";
case 3:
return "class3";
default:
return "unassignedClass";
}
}
I have always used HtmlAgilityPack to prepare htmlcontent and achieve things like this.
private string PrepareHtmlContent(List<DataRow> dataTable)
{
var htmlDocument = new HtmlDocument();
var html = EmailTemplates.GetTemplate("yourTemplate");
htmlDocument.LoadHtml(html);
var recordsContainerNode = htmlDocument.GetElementbyId("dataTable");
if (recordsContainerNode != null)
{
var innerHtml = "";
foreach (var entry in dataTable)
{
innerHtml += "<tr>";
innerHtml += "<td>" + entry.PrimaryImage + "</td> ";
innerHtml += "<td>" + entry.Model + "</td> ";
innerHtml += "<td>" + entry.AskingPrice + "</td> ";
innerHtml += "</tr>";
}
recordsContainerNode.InnerHtml = innerHtml;
}
using (var stringWriter = new StringWriter())
{
htmlDocument.Save(stringWriter);
return stringWriter.GetStringBuilder().ToString();
}
}
And your template should be sth like this
<body>
<form id="form1" runat="server">
<div style="border: thin solid #E1E1E1; background-color: #F0F0F0; margin-bottom: 10px; padding-top: 3px; padding-bottom: 3px; padding-left:5px;">
Postings
</div>
<table>
<thead> </thead>
<tbody id="dataTable">
</tbody>
</table>
</form>
</body>
I have a variable str which is having some text. I just show this text on the my UI.
But I have a condition, suppose this variable is having 5oo words, so I need to put a tag after every 50 words.
How can I do that?
below is my c# code through which I am sending a mail as html
Emailbody += " <tr>";
Emailbody += " <td align='left' valign='Top' nowrap><span class=style17>Purpose of travel</span></td>";
Emailbody += "<td align='center' valign='Top'>:</td>";
Emailbody += " <td align='left' valign='Top'><span class=style17> " + TextBox1.Text + "</span></td>";
Emailbody += " <td> </td>";
Emailbody += " <td align='left' nowrap'><span class=style17>Advance</span></td>";
Emailbody += " <td align='center'>:</td>";
Emailbody += "<td align='left' nowrap><span class=style17>"+TextBox2.Text+"</td>";
Emailbody += " </tr>";
I need the the solution for mt TextBox1.Text
If you are using C#, then you can do so like :
public string SplitLine(string input)
{
var wordList = input.Split(' ');
var sb = new StringBuilder();
for (int index = 0; index < wordList.Length; index++)
{
if(index % 50 == 0 && index > 0)
sb.Append("<br/>" + wordList[index]);
else
sb.Append(wordList[index] + ' ');
}
return sb.ToString();
}
Use javascript as follows:
var count=0;
for(var i=0;i<str.length;i++)
{
if((str[i])=="")
{
count++;
if(count==50)
{
str[i]="<br/>"
count=0;
}
}
}
Hope its helpful.
I assume you want to do that in c#?
Have a look at possible duplicate. The given function allows you do specify rather than a number of characters or words a line width in pixels and with the font and font size it calculates a proper length. You have to adapt it to your HTML output, but the rest stays the same.
You can use the List then like this:
List<string> lines = WrapText(TextBox1.Text, 300, "Calibri", 11);
string longText = string.Empty
foreach (var item in lines)
{
longText += item + "</br>";
}
Emailbody += " <tr>";
Emailbody += " <td align='left' valign='Top' nowrap><span class=style17>Purpose of travel</span></td>";
Emailbody += "<td align='center' valign='Top'>:</td>";
Emailbody += " <td align='left' valign='Top'><span class=style17>" + longText + "</span></td>";
Emailbody += " <td> </td>";
Emailbody += " <td align='left' nowrap'><span class=style17>Advance</span></td>";
Emailbody += " <td align='center'>:</td>";
Emailbody += "<td align='left' nowrap><span class=style17>"+TextBox2.Text+"</td>";
Emailbody += " </tr>";
I'm new here, I'm stuck in problem in which i have to loop my button so that i will be able to put it on my looping div. How will I do that? This is what I got so far:
//my loop
for (i = 0; i < MPreply.recommendation.Length; i++) {
html += "<div class='rec'> ";
html += "</br> <div id = 'from1' value = > Depart From:" + " ";
html += emz + " " + "(" + + ")" + "</div>";
html += "<div id = 'date1' > Schedule:" + " " + flytDate;
html += " , " + convertedString;
html += "</div>" + "<div id = 'to1' >To:" + " " + emz2 + " " + "(" + "" + ")";
html += "</div> </br> </br> </br> ";
html += "<div id = 'RecNo'>" + " " + (i + 1) + " )" + " </br> </br> </div> ";
html += "<div id = 'fare1'> $" + em + " </div> ";
html += " </div> <br/> <br/>";
div_rec.InnerHtml = html;
}
html:
<div id = 'modal' runat="server" >
<div id="dialog" runat="server">
</div>
<input id="_menuitem" type="button" value="Click" runat="server" />
</div>
Thanks in advance.
You have at least a few problems:
"<div id = 'fare1'>
and similar sections will generate multiple elements with the same id.
div_rec.InnerHtml = html;
Should be moved outside of your loop so that div_rec is only updated once, when everything is done.
emz + " " + "(" + + ")" + "</div>";
Should (probably) be changed to
emz + " " + "(" + your_variable_here + ")" + "</div>";
In order to (I think) add the creation of a button in your loop, you'll have to piece it together as a string just like your other elements. To get a function handler wired up you'll have to either:
a) Build a dom level-0 handler as a string, or
b) Wait until your html is updated, then query out the newly added buttons and add event handlers in code (using either btn.onclick = function(... or dom level-2 handlers (addEventListener or attachEvent)
The Problem i see here is with the ID field.
You have mentioned same ID name for all the Div's you are generating.
Like,
<div id = 'from1'>
<div id = 'to1'>
ID is a unique identifier to an element. It must always be unique.
You can Use Class instead.
Like,
<div class = 'from1'>
<div class = 'to1'>
I'm trying to read a text file containing the name of the image, and display it opon pageload.
Let's say that the content in the text file is
Australia Picture101
Singapore Picture201
Following is the code i tried and it does not display the image.
tableString += "<table class='content_background' cellpadding='0' cellspacing='0'>";
foreach (string line in lines)
{
string[] country = line.Split(token2);
string[] image = country[1].Split(token);
string row = "<tr><td class='left_content'>" + country[0] + "</td>" +"<td><table><tr>";
tableString += row;
for (int i = 0; i < image.Length; i++)
{
---> string row2 = "<td class='right_content'> <asp:ImageButton ImageUrl='~/img/missing children pictures/" + "image[i]" + ".jpg'/>" + "</td>";
tableString += row2;
}
tableString += "</tr></table></td>";
}
tableString += "</tr></table>";
container.InnerHtml = tableString;
Is there any other way to do this ? Thanks in advance.
the screen shot is as follow
That's no button ! You're outputting non-parsed HTML - the ASP.NET engine does not parse that, it just sends the data as HTML to the client.
Instead, use
var btn = new ImageButton();
btn.ImageUrl = "~/img/missing children pictures/" + "image[i]" + ".jpg";
Panel1.Controls.Add(btn);
As an easy hack, you can use
string row2 = "<td class=\"right_content\"> <input type=\"button\" style=\"background:url('/img/missing%20children%20pictures/" + image[i] + ".jpg')\"/></td>";
If you want to generate HTML directly, then use HTML tags:
<a href="[Img_CLick Link]"><img src="[image path]"
alt="Click" border="0" /></a>
Put appropriate values in the square brackets.
Otherwise consider using asp:Table control and add rows/cells at run time.