Minor bug in plain-text to HTML conversion using Regular Expressions - c#

I am facing a minor bug when doing the conversion from plain text to HTML. What might be the reason for this?
Input: (plain-text)
this is test input.
Output: (virtual plain-text but HTML)
this is test input.
BUG: Moves one or two spaces forward. I have no clue why is this happening.
Code for your reference
string Text = "<html><body><pre style=\"font-family:consolas;font-size:88%;\">"
+ mailItem.Body + "</pre></body></html>";
mailItem.HTMLBody = Text;
mailItem.HTMLBody = Regex.Replace(mailItem.HTMLBody,
"(ASA[a-z][a-z][0-9][0-9])", "$&");

I tested the following, and it works (eg. no spaces at beginning of output):
string mailItemBody = "ASAss87";
string oldText = "<html><body><pre style=\"font-family:consolas;font-size:88%;\">"
+ mailItemBody + "</pre></body></html>";
string newText = Regex.Replace(
oldText, "(ASA[a-z][a-z][0-9][0-9])", "$&");
Console.WriteLine("Old text is: \n\n" + oldText + "\n\n");
Console.WriteLine("New text is: \n\n" + newText + "\n\n");
I would investigate the class used to instantiate mailItem, and review at the HTMLBody property to see if anything funny is happening there.

Related

StreamReader from .csv - "foreign" chars and blank values showing up as '?'

I'm having two problems with reading my .csv file with streamreader. What I'm trying to do is get the values, put them into variables which I'll be using later on, inputting the values into a browser via Selenium.
Here's my code (the Console.Writeline at the end is just for debugging):
string[] read;
char[] seperators = { ';' };
StreamReader sr = new StreamReader(#"C:\filename.csv", Encoding.Default, true);
string data = sr.ReadLine();
while((data = sr.ReadLine()) != null)
{
read = data.Split(seperators);
string cpr = read[0];
string ydelsesKode = read[1];
string startDato = read[3];
string stopDato = read[4];
string leverandoer = read[5];
string leverandoerAdd = read[6];
Console.WriteLine(cpr + " " + ydelsesKode + " " + startDato + " " + stopDato + " " + leverandoer + " " + leverandoerAdd);
}
The code in and of itself works just fine - but I have two problems:
The file has values in Danish, which means I get åøæ, but they're showing up as '?' in console. In notepad those characters look fine.
Blank values also show up as '?'. Is there any way I can turn them into a blank space so Selenium won't get "confused"?
Sample output:
1372 1.1 01-10-2013 01-10-2013 Bakkev?nget - dagcenter ?
Bakkev?nget should be Bakkevænget and the final '?' should be blank (or rather, a bank space).
"Fixed" it by going with tab delimited unicode .txt file instead of .csv. For some reason my version of excel doesn't have the option to save in unicode .csv...
Don't quite understand the problem of "rolling my own" parser, but maybe someday someone will take the time to explain it to me better. Still new-ish at this c# stuff...

String.Replace Not modifying my String

I am trying to save a number of images and I'd like to use the DateTime to have distinct and identifiable Filenames.
So I create a String with the correct Path, add the datetime to it and remove the spaces, dots and colons.
String imagePath = "D:\\Patienten\\" + username;
imagePath += "\\"+DateTime.Now.ToString();
Console.WriteLine("WithFilename: " + imagePath);
imagePath.Replace(" ", "");
Console.WriteLine("Without \" \" : " + imagePath);
imagePath.Replace(".", "");
Console.WriteLine("Without \".\": " + imagePath);
imagePath.Replace(":", "");
Console.WriteLine("Output format: " + imagePath);
imagePath += ".png";
image.Save(imagePath);
According to the console output the String doesnt change at all.
Meaning all the Output Strings from Console.Writeline are identical.
I am using c# in visual Studio Express 2010 in case that makes a difference.
Can anyone find an Error here?
Thanks in advance!
Strings are immutable, the modified string will be a new string that is returned from the function
e.g.
imagePath = imagePath.Replace(" ", "");
Why strings are immutable
Why not just use DateTime.ToString() with a format and drop the dividers using that? Would be more efficient than performing several String.Replace() yourself:
string imagePath = "D:\\Patienten\\" + username + "\\" + DateTime.Now.ToString("yyyyMMdd hhmmssfff") + ".png";
You should use:
imagePath = imagePath.Replace(" ", ""); You should assign returned value
From the documentation (emphasis mine):
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
It is supposed to work like that. Use
imagePath = imagePath.Replace(" ", "");
instead.

How to send an email with its text/html encoded in UTF-8 using SendGrid for C#?

I'm trying to send emails that contains special characters like á, é, ó, í, ú, etc. My code looks like this:
try
{
Mail message = Mail.GetInstance();
foreach (Users u in users)
{
message.AddBcc(u.Email);
}
message.From = new MailAddress(Microsoft.WindowsAzure.CloudConfigurationManager
.GetSetting("emailFrom"), Microsoft.WindowsAzure.CloudConfigurationManager
.GetSetting("emailFromName"));
message.Subject = Microsoft.WindowsAzure.CloudConfigurationManager
.GetSetting("emailSubject");
message.Html = "<meta charset=\"UTF-8\"/>" +
Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("emailText1") +
" " + address+ ".<br/>" +
Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("emailText2");
var transport = SMTP.GetInstance(new NetworkCredential(
Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("emailLogin"),
Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("emailPass")));
transport.Deliver(message);
isEmailSent = true;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + " \n " + ex.InnerException + " \n " + ex.StackTrace);
isEmailSent = false;
}
I tried to specify the charset in the Html I'm sending but it doesn't work, instead of sending this San Jerónimo Amanal, this is what is being sent San Jerónimo Amanal.
How can I send it in the correct encoding? Any help will be appreciated.
EDIT
I tried this two approches:
message.Html = "<meta charset=\"UTF-8\"/>" +
Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("emailText1") +
" " + address+ ".<br/>" +
Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("emailText2");
And this:
message.Html = Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting
("emailText1") + " " + address+ ".<br/>" +
Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("emailText2");
But the email is still being sent with the wrong encoding.
EDIT 2
I tried the answer on this question Converting Unicode strings to escaped ascii string, more especifically, I tried the method EncodeNonAsciiCharacters but I got this in the email San Jer\u00c3\u00b3nimo Amanal. Did I take the wrong approach in this one?
Well it took some time, but at least I found a way to send the email without the special characters, I had to normalize the string I got with Normalization Form Compatibility Decomposition, which is done through the String class' Normalize method like this:
string normalizedString = InString.Normalize(NormalizationForm.FormKD);
With this, quoting from wikipedia:
characters are decomposed by compatibility, and multiple combining
characters are arranged in a specific order.
Meaning if there's also a character whose compability is represented by two characters, then it will be replace by said characters. With characters like é, it will be replaced by e.

Issue with forming a string with double quotes

I want to form a string as <repeat><daily dayFrequency="10" /></repeat>
Wherein the value in "" comes from a textboxe.g in above string 10. I formed the string in C# as
#"<repeat><daily dayFrequency=""+ txt_daily.Text + "" /></repeat>" but i get the output as
<repeat><daily dayFrequency="+ txt_daily.Text+ " /></repeat>. How to form a string which includes the input from a textbox and also double quotes to be included in that string.
To insert the value of one string inside another you could consider string.Format:
string.Format("foo {0} bar", txt_daily.Text)
This is more readable than string concatenation.
However I would strongly advise against building the XML string yourself. With your code if the user enters text containing a < symbol it will result in invalid XML.
Create the XML using an XML library.
Related
How can I build XML in C#?
Escape it with \ Back slash. putting # in front wont do it for you
string str = "<repeat><daily dayFrequency=\"\"+ txt_daily.Text + \"\" /></repeat>";
Console.Write(str);
Output would be:
<repeat><daily dayFrequency=""+ txt_daily.Text + "" /></repeat>
You could do it like this:
var str = String.Format(#"<repeat><daily dayFrequency="{0}" /></repeat>",
txt_daily.Text);
But it would be best to have an object that mapped to this format, and serialize it to xml
string test = #"<repeat><daily dayFrequency=" + "\"" + txt_daily.Text + "\"" + "/></repeat>";

How can I format C# string output to contain newlines?

strEmail =
"Hi All,"
+ "<br>"
+ "The User "
+ lstDataSender[0].ReturnDataset.Tables[0].Rows[0][1].ToString()
+ " has been created on "
+ DateTime.Now.ToShortDateString()
+ "."
I am writing C# code to generate an email whenever a new user has been created. I need the body of the mail in a mail format like
hi,
The user "xxx" has been created on "todaysdate".
Thanks,
yyyy
so I need to insert linebreaks and bold for some characters. How might I achieve this?
If this is a plain text email (which it looks like it is), use \r\n for new lines.
strEmail = string.Concat("Hi All,\r\n\r\nThe User",
lstDataSender[0].ReturnDataset.Tables[0].Rows[0][1].ToString(),
"has been created on ",
DateTime.Now.ToShortDateString(),
".\r\n\r\nThanks, yyyy");
Strickly speaking this should be Environment.NewLine to support different platforms, but I doubt this is a concern.
Set
yourMessage.IsBodyHtml = true
Msdn-Reference can be found here.
In order to form, you can use like below:
Response.Write("Hi,<br/><br/>The user.......");

Categories

Resources