Incorrect output from text-replace loop, unexpected duplicated output - c#

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

Related

TempData not retaining value in FileContentResult

I have the following code:
[Authorize]
[HttpGet]
public FileContentResult DownloadMsgAsPdf(string FileId, string outer = "")
{
var Results = (SearchResult)TempData["Results"];
var msg = Results.emails[FileId];
...
return File(pdfBytes, System.Net.Mime.MediaTypeNames.Application.Octet, msg.Id + ".pdf");
}
Now upon running it once (clicking a link) it does everything completely fine. However upon clicking it a second time (with nothing else changed or called) it errors out, with Results being null. I assume this means TempData is getting cleared, but how could this be?
Here is the full code if it's needed:
[Authorize]
[HttpGet]
public FileContentResult DownloadMsgAsPdf(string FileId, string outer = "")
{
var Results = (SearchResult)TempData["Results"];
var msg = Results.emails[FileId];
TempData.Keep();
msg.BodyHTML = System.Web.HttpUtility.HtmlDecode(msg.BodyHTML);
var htmlContent = String.Format("<center><p><b>Case ID</b>: " + msg.Id
+ " <b>User ID</b>: " + Session["userid"]
+ " <b>Privileged</b>: ");
if (msg.Tags != null)
{
htmlContent += msg.Tags.ContainsKey("privileged");
}
else
{
htmlContent += "False";
}
htmlContent += " <b>Downloaded</b>: " + DateTime.Now.ToString("g") + "</center>"
+ " <p> -- Forwarded message -- </p> "
+ " <p><b> From :</b> <a href='#'>" + msg.From + "</a> </p> "
+ " <p><b> Date:</b> Mon, oct 25 2010 at 4:42 PM </p> "
+ " <p> <b>Subject:</b> " + msg.Subject + " </p> "
+ " <p><b> To:</b> " + msg.To + " </p> "
+ " <p><b> Cc: </b> </p> "
+ " <div> "
+ " <ul> ";
if(msg.attachementList != null){
if (!msg.attachementList.Any())
{
htmlContent += "<text> "
+ "<li><label style='color:gray'>No attachment</label></li></text>";
}
else
{
foreach (var attachment in msg.attachementList)
{
var filename = System.IO.Path.GetFileName(attachment);
htmlContent += "<text> "
+ "<li><a href='#'>" + filename + "</a></li></text>";
}
}
}
htmlContent += "</ul>"
+ "</div>"
+ "<div padding: 5px;'>"
+ msg.BodyText
+ "</div>"
+ "</div>";
var pdfBytes = (new NReco.PdfGenerator.HtmlToPdfConverter()).GeneratePdf(htmlContent);
if (outer != "")
{
return File(pdfBytes, System.Net.Mime.MediaTypeNames.Application.Octet, msg.Id + ".pdf");
}
return new FileContentResult(pdfBytes, "application/pdf");
}
TempData means you only can get once. And i see you use TempData.Keep(), but this method only effect on the same http context. I think you can use Session or Cache instead of the TempData.

Pasting into a textbox breaks back end email construction

I'm having the oddest issue that I can't even rationalize.
I have a form with several textboxes, one of which is the comments box:
MVC:
<div class="contactUsTextArea">
Comments or Questions:<br />
#Html.TextAreaFor(x => x.Comments, new { maxlength = 990 } )
</div>
Rendered HTML:
<div class="contactUsTextArea">
Comments or Questions:
<br>
<textarea id="Comments" rows="2" name="Comments" maxlength="990" cols="20"></textarea>
</div>
When the forms is submitted, this code runs:
public bool SendEmail(ContactUsModel formSubmission) {
MailMessage email = new MailMessage();
SmtpClient smtp = new SmtpClient();
string upc = formSubmission.ProductUpcCode;
string comments = formSubmission.Comments;
string comments_small = formSubmission.Comments;
if (!string.IsNullOrEmpty(formSubmission.ProductUpcCode) && upc.Length > 14 )
upc = upc.Substring(0, 13);
if (!string.IsNullOrEmpty(comments) && comments.Length > 990)
comments = comments.Substring(0, 989);
if (!string.IsNullOrEmpty(comments_small) && comments_small.Length > 255)
comments_small = comments_small.Substring(0, 254);
string bodyText = "FIRST_NAME:" + formSubmission.FirstName + "\n" +
"LAST_NAME:" + formSubmission.LastName + "\n" +
"COMPANY:" + formSubmission.CompanyName + "\n" +
"ADDRESS:" + formSubmission.StreetAddress + "\n" +
"CITY_TOWN:" + formSubmission.City + "\n" +
"STATE_PROVINCE:" + formSubmission.Province + "\n" +
"ZIP_POSTAL:" + formSubmission.PostalCode + "\n" +
"COUNTRY:CAN\n" +
"EMAIL:" + formSubmission.Email + "\n" +
"PHONE:" + formSubmission.PhoneNumber + "\n" +
"UPC:" + upc + "\n" +
"DATE_CODE:\n" +
"BRAND_PRODUCT:" + formSubmission.ProductName + "\n" +
"COMMENTS:" + comments_small + "\n" +
"FULL_COMMENTS:" + comments + "\n" +
"LANGUAGE:English" + "\n" +
"OPTIN:N";
email.From = new MailAddress(ConfigurationManager.AppSettings["emailSubmission_FROM"]);
email.To.Add(new MailAddress(ConfigurationManager.AppSettings["emailSubmission_TO"]));
email.Subject = ConfigurationManager.AppSettings["emailSubmission_SUBJECT"];
email.IsBodyHtml = false;
email.Body = bodyText;
email.BodyEncoding = System.Text.Encoding.UTF8;
smtp.Send(email);
return true;
}
(Don't ask me why I need a small comments and large comments, clients will be clients)
Anyway, my issue is when I type a comment into the comment box I get this return:
http://i.imgur.com/zraNy.png
However when I copy paste text I get this return:
http://i.imgur.com/doWrw.png
Why is this happening?
There are only a few things that this could be (that I could think of) - both of which are related to the client.
Something with the email client where its not rendering the \n like it should.
Although for Windows, \r\n is the standard, and many applications dont honor '\n' properly. I would try using that for newlines instead of just \n.
Also something with the client, related to encoding (but i doubt it)
Alright... so I'll just post a picture of what my issue was... and then I'm going to go hide in shame in a cave forever.
http://i.imgur.com/tEiKj.png
Thanks for the help though everyone.

Loop Button inside the Loop Div

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'>

How can I check for a stream before initializing one in a loop in C#

I've got the following bit of code that generates a list I'm trying to process. I need to create multiple files as I go through the list.
Currently I'm getting the following error on the calls to genStream outside of the IF, (in and out of the FOREACH loop), and I'm not sure why:
The name genStream' does not exist in the current context
I'm trying to figure out how I can close the one stream, and open another in the IF statement. I tried to put a .close() before creating the new stream, and it gave me an error for using it before initializing the stream.
Here is my bit of code:
/// <summary>
/// Creates a file for each Genre, and writes movie info to each for the cooresponding movies
/// </summary>
/// <param name="cPath">Path to create HTML files in</param>
/// <param name="mList">List of Movies to generate Genre and Movie info from</param>
public static void WriteGenreHTML(string cPath, List<Movie> mList)
{
int lineID = 0;
string tmpGen = null;
string strHeader, strMovie, strGenre, tmpGenre = null;
// Gets a list of unique Genres from the MovieList
var distinctGenres = from m in mList
from genre in m.Genres
group genre by genre into genres
select genres.First();
// Gets a list of Movies with the associated Genres
var moviesWithGenre = from g in distinctGenres
from m in mList
where m.Genres.Contains(g)
orderby g, m.Title
select new { Genre = g, Movie = m };
// Traverses list of movies creating new HTML Genre files, and writing movie info to the HTML genre files
foreach (var m in moviesWithGenre)
{
// Creates new HTML file if new Genre is detected
if (m.Genre != tmpGen)
{
tmpGen = m.Genre;
// initiates streamwriter for catalog output file
FileStream fs = new FileStream(cPath + Path.DirectorySeparatorChar + m.Genre, FileMode.Create);
StreamWriter genStream = new StreamWriter(fs);
// Generates header info for new file, and new Genre
strHeader = "<style type=\"text/css\">\r\n" + "<!--\r\n" + "tr#odd {\r\n" + " background-color:#e2e2e2;\r\n" + " vertical-align:top;\r\n" + "}\r\n" + "\r\n" + "tr#even {\r\n" + " vertical-align:top;\r\n" + "}\r\n" + "div#title {\r\n" + " font-size:16px;\r\n" + " font-weight:bold;\r\n" + "}\r\n" + "\r\n" + "div#mpaa {\r\n" + " font-size:10px;\r\n" + "}\r\n" + "\r\n" + "div#genre {\r\n" + " font-size:12px;\r\n" + " font-style:italic;\r\n" + "}\r\n" + "\r\n" + "div#plot {\r\n" + " height: 63px;\r\n" + " font-size:12px;\r\n" + " overflow:hidden;\r\n" + "}\r\n" + "\r\n" + "div#genre_heading {\r\n" + " height: 50px;\r\n" + " font-size: 24px;\r\n" + " font-weight: bold;\r\n" + " text-align: center;\r\n" + " text-decoration: underline;\r\n" + "}\r\n" + "-->\r\n" + "</style>\r\n" + "\r\n" + "<html>\r\n" + " <body>\r\n" + " <table>\r\n";
strHeader += " <tr>\r\n" + " <td colspan=2>\r\n" + " <div id=\"genre_heading\">" + m.Genre + "</div>\r\n" + " </td>\r\n" + " </tr>\r\n" + "\r\n";
// Writes header HTML to stream
genStream.WriteLine(strHeader);
Console.WriteLine();
Console.WriteLine("Now Processing " + m.Genre);
}
// Generates the HTML for the Movie
strMovie = lineID == 0 ? " <tr id=\"odd\" style=\"page-break-inside:avoid\">\r\n" : " <tr id=\"even\" style=\"page-break-inside:avoid\">\r\n";
strMovie += " <td>\r\n" + " <img src=\".\\images\\" + m.Movie.ImageFile + "\" width=\"75\" height=\"110\">\r\n" + " </td>\r\n" + " <td>\r\n" + " <div id=\"title\">" + m.Movie.Title + "</div>\r\n" + " <div id=\"mpaa\">" + m.Movie.Certification + " " + m.Movie.MPAA + "</div>\r\n" + " <div id=\"genre\">" + strGenre + "</div>\r\n" + " <div id=\"plot\">" + m.Movie.Plot + "</div>\r\n" + " </td>\r\n" + " </tr>\r\n";
// Writes the HTML to the stream
genStream.WriteLine(strMovie);
lineID = lineID == 0 ? 1 : 0;
}
string closingHTML = " </table>\r\n" + " </body>\r\n" + "</html>";
genStream.WriteLine(closingHTML);
genStream.Close();
}
Side note. I'd GREATLY appreciate it if someone could point me towards something I can use to convert the HTML files into PDFs. I tried EO, and it has a nasty "watermark", and chokes on files over a couple MB (mine are 5-10mb+). I have WkHTMLToSharp, but I am not sure how to use it, and can't find any documentation on how to intitialize/use it.
Thanks as always!
Declare the genStream outside of foreach loop, and then initialize it as needed within the if statement:
StreamWriter genStream;
foreach (var m in moviesWithGenre)
{
// Creates new HTML file if new Genre is detected
if (m.Genre != tmpGen)
{
tmpGen = m.Genre;
// initiates streamwriter for catalog output file
FileStream fs = new FileStream(cPath + Path.DirectorySeparatorChar + m.Genre, FileMode.Create);
// Set genStream to the FileStream
genStream = new StreamWriter(fs);

Why is EO.PDF Timing Out When Converting HTML File to PDF in C#

I have the following bits of code:
public static void WriteHTML(string cFile, List<Movie> mList)
{
int lineID = 0;
string strMovie, strGenre, tmpGenre = null;
// initiates streamwriter for catalog output file
FileStream fs = new FileStream(cFile, FileMode.Create);
StreamWriter catalog = new StreamWriter(fs);
string strHeader = "<style type=\"text/css\">\r\n" + "<!--\r\n" + "tr#odd {\r\n" + " background-color:#e2e2e2;\r\n" + " vertical-align:top;\r\n" + "}\r\n" + "\r\n" + "tr#even {\r\n" + " vertical-align:top;\r\n" + "}\r\n" + "div#title {\r\n" + " font-size:16px;\r\n" + " font-weight:bold;\r\n" + "}\r\n" + "\r\n" + "div#mpaa {\r\n" + " font-size:10px;\r\n" + "}\r\n" + "\r\n" + "div#genre {\r\n" + " font-size:12px;\r\n" + " font-style:italic;\r\n" + "}\r\n" + "\r\n" + "div#plot {\r\n" + " height: 63px;\r\n" + " font-size:12px;\r\n" + " overflow:hidden;\r\n" + "}\r\n" + "-->\r\n" + "</style>\r\n" + "\r\n" + "<html>\r\n" + " <body>\r\n" + " <table>\r\n";
catalog.WriteLine(strHeader);
foreach (Movie m in mList)
{
strMovie = lineID == 0 ? " <tr id=\"odd\" style=\"page-break-inside:avoid\">" : " <tr id=\"even\" style=\"page-break-inside:avoid\">";
catalog.WriteLine(strMovie);
foreach (string genre in m.Genres)
tmpGenre += ", " + genre;
try
{ strGenre = tmpGenre.Substring(2); }
catch (Exception)
{ strGenre = null; }
strMovie = " <td>\r\n" + " <img src=\".\\images\\" + m.ImageFile + "\" width=\"75\" height=\"110\">\r\n" + " </td>\r\n" + " <td>\r\n" + " <div id=\"title\">" + m.Title + "</div>\r\n" + " <div id=\"mpaa\">" + m.Certification + " " + m.MPAA + "</div>\r\n" + " <div id=\"genre\">" + strGenre + "</div>\r\n" + " <div id=\"plot\">" + m.Plot + "</div>\r\n" + " </td>\r\n" + " </tr>\r\n";
catalog.WriteLine(strMovie);
lineID = lineID == 0 ? 1 : 0;
}
catalog.WriteLine(" </table>\r\n" + " </body>\r\n" + "</html>");
catalog.Close();
}
public static void WritePDF(string cFile, string pdfFile)
{
// Sets up PDF to write to
EO.Pdf.HtmlToPdf.Options.PageSize = new SizeF(8.5f, 11f);
EO.Pdf.HtmlToPdf.Options.OutputArea = new RectangleF(0.5f, .25f, 7.5f, 10.25f);
HtmlToPdf.ConvertUrl(cFile, pdfFile);
}
My HTML file writes fine, but when it tried to convert the HTML file to PDF I get an exception that it times out.
I did a test previously, and had it convert the code (not the file) within the WriteHTML function and it worked great. I have confirmed that the cFile exists and is a valid file (created previously in WriteHTML). The path to pdfFile is valid, and the documentation does not state the file needs to already exist (.ConvertHTML did not need an existing file).
Only thing I can think of is that the catalog.html file isn't released and ready to read yet. I made sure I closed it in the WriteHTML function. How can I test that the file is ready to be read?
Tried setting .MaxLoadWaitTime = 120000 with no luck.
Any clues would be greatly appreciated!
After a battery of further testing, and scouring the EO support forums, it appears to be a limitation of the free version of EO. It seems to have difficulty with HTML files over 3MB.
It's a shame since the EO product is very good, but not unfortunately not worth $250 IMO.

Categories

Resources