Padding problem for text email using PadRight in C# - c#

I have a question regarding encoding for text email messages using C# .net because I have mine as simple ASCII but when doing padding for formatting a recipt to the user the data is not lining up although when I check the lines in say NotePad++ they are exactly the same No. of character. Below is some code, can anyone tell me what I'm doing wrong?
StringBuilder oSB = new StringBuilder();
oSB.AppendLine(EmailLine("Amount", oTrans.PaymentAmount.ToString()));
oSB.AppendLine(EmailLine("Payment Method", oTrans.CardType));
private static string EmailLine(string FieldLabel, string FieldVal)
{
return PadLabel(FieldLabel) + FieldVal ;
}
private static string PadLabel(string FieldLabel)
{
return FieldLabel.PadRight(40, char.Parse(" ")) + ": ";
}
My output looks like this:
Amount : 100.00
Payment Method : VISA

Whether or not they line up will depend on the font being used to display the email. That's a setting on the email client. For example, here is where I would set it in Outlook:
Try changing the font in Notepad++ to Times new Roman and Courier and you'll see that they line up differently.
You have no control over the user's font if you're sending it as a plan text mail. The best you can do it indicate "Best read with ___ font" or format it as HTML where you have some control.
Other options would include outputting this to a PDF file, or an image (again where you have more control).

Related

I have a text field, who's value is being HTML encoded every time the value gets saved.... C# ASP.NET Web Forms ADO.NET

So there are text field and text area web form controls, which are being HTML encoded. A string like "alert(‘XSS’)" would be HTML encoded and look like this "<script>alert(‘XSS’)</script>"... the problem with that is the next time that value is processed via a form control that does not allow HTML, it will encode this encoded string yet again this time and turn the leading < into <
namespace EncodingExample
{
class Program
{
static void Main(string[] args)
{
// every single time a form is saved, any text fields which have
// previously encoded fields (meaning they had HTML in them before)
// will be encoded again. > becomes &gt; on the second pass...
string example = "<script>alert(‘XSS’)</script>";
Console.WriteLine("Original screen input by malicious user: " + example);
var encodedOnce = HttpUtility.HtmlEncode(example);
Console.WriteLine("Original string encoded once: " + encodedOnce);
var encodedAgain = HttpUtility.HtmlEncode(encodedOnce);
Console.WriteLine("Original string encoded a second time: " + encodedAgain);
Console.ReadKey();
}
}
}
How do I prevent the < (which is the < character) from being messed with on subsequent processing?
Should I be decoding this on page load (this is a legacy ASP.NET web forms app)? Does encoding the content upon posting, and decoding it upon page load still block XSS attacks?
What is considered, if any, safe HTML that can somehow get "past" the HttpUtility.HtmlEncode method. That would be ideal, if say for example, styling were still allowed to be applied via HTML input in a text control. Is this possible?

Read an HTML/Text file and Send it as a HTML Formated Email in WPF/C#

I have a WPF application that sends out a HTML-formatted email when a button is clicked. The entire email message is in HTML-format and it does work.
However, I was wondering if there was a way to read a html file and send it out rather than writing the whole message in the code behind...keeping all the HTML formatting in-tact.
I tried something like this:
string MessageTosend = File.ReadAllText("path to txt/html file");
But that just sent out an email that only has text (no styling, no html...just the plain text found in the file).
Then I thought, I may have to convert everything:
string MessageTosend = Convert.ToString(File.ReadAllText("path to txt/html file"));
But that does the same thing as before.
Is there a way to do achieve this? Or will I have to stick to having
string MessageTosend = #"<html> ... lots of html stuff ... </html>";
for every button that sends an email?
For notice: The contents of the .txt and .html file I attempted to read from was tested using the same contents of the above string (which, again, works as expected), and without the double quotes (example: width=""100"" and width="100")
Try adding an encoding to your file read:
string MessageTosend = File.ReadAllText("path to txt/html file", Encoding.UTF8);
Try reading a file simply containing < and compare it to the string "<". Repeat for any special characters until you find a mismatch. Then find the character number like this:
(int)MessageTosend[0] // < should be 60 (3C in UTF-8)
Find out what the offending characters are, and we may be able to help. If I read a file, I do not see this problem.

Get C# to respect \n returned in a string from a web service?

I have a messaging system that is a .NET 2 ASMX web service, very basic system. I push messages and would like to have newline symbols in the message so it's formatted on the receiving end. For example, I'd like to send a string such as: "Hello\n\nMy Name Is..." and have it have two line breaks. When the receiver reads the text it's actually outputting the \n's in the text. How can I get the \n's to be interpreted as if I was writing it in C#? Or \t etc.
Thank you.
You should compose the message using Environment.NewLine to insert the character(s) used to represent a newline on your system.
See here for references
However using Environment.NewLine has some problems.
For example, your message should be written in this way
string msg = "Hello" + Environment.NewLine + Environment.NewLine + "My Name Is...";
a bit cumbersome to use from a programmer point of view.
Then you could write an extension method for the string class which takes your message and insert at the place of a placeholder the Environment.NewLine chars.
This example use the | (pipe) character as placeholder for the newline pos.
public static string InsertLineBreaks(this string inMsg)
{
Strinbuilder sb = new StringBuilder(inMsg);
sb.Replace("|", Environment.NewLine);
return sb.ToString();
}
and you can call this extension in this way
string msg = "Hello||My Name Is...".InsertLineBreaks();
The web service is likely sending the message back with carriage returns listed as "%0D". What I have done in my programs is use:
str.Replace("%0D", Environment.NewLine);
That seems to work for me.
I'm sure you could also use:
str.Replace("%0D", "\n");
You have to replace the \n with something that is interpreted as a new line by the browser, i.e. <br/>. I suppose you're using it as an HTML string.
Besides you need to get sure that it isn't HtmlEncoded, i.e., that your <br/> isn't converted into <br/>. This shouldn't happend if you're using JSON serialization. but will happen if you serialize it as XML and isn't properly decoded in client side.
Use this:
string returnString = "Hello" + Environment.NewLine+ "My Name Is..";

How to read Cyrillic symbols from a .txt file with C#

I saw similar topics but could not find a solution. My problem is that I have a .txt file in which the symbols are in Bulgarian language / which is Cyrillic /, but after trying to read them, there is no sucess. I tried to read with this code:
StreamReader reader = new StreamReader(fileName,Encoding.UTF8);
if (File.Exists(fileName))
{
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
And I also changed the Encoding value to all possible , as I tried with GetEncoding(1251), which I wrote is for cyrillic. And when I save the .txt file I tried to save it with each different encoding which was there / UNICODE,UTF-8,BigEndianUnicode,ANSI / in each combination with the Encoding I am settin through the code, but again no success.
Any ideas for how to read the cyrillic symbols in the right way will be appriciated.
And here is sample text for this: "Ето примерен текст."
Thanks in advance! :)
Your problem is that the console can't show cyrillic characters. Try putting a breakpoint on the Console.WriteLine and inspect the line variable. Clearly you'll need to know the correct encoding first! :-)
If you don't trust me, try this: make a console program that does this:
string line = "Ето примерен текст";
Console.WriteLine(line);
return 0;
put a breakpoint on the return 0;, watch the console and watch the line variable.
I'll add that unicode consoles should be one of the "new" things in .NET 4.5
And you can try to read this page: c# unicode string output
The problem you are having is not reading the text, but displaying it.
If your real intention is to display Unicode text in a console window, then you'll have to make a few changes. If however, you will be displaying the text in a WinForms or WPF app for instance, then you will not have problems - they work with Unicode by default.
By default, the console will not handle unicode, or use a font which has unicode glyphs. You need to do the following:
Save your text file as UTF8.
Start a console which is unicode enabled: cmd \u
Change the font to "Lucida Sans Unicode": console window menu -> properties -> font
Change the codepage to Unicode: chcp 65001
Run your app.
Your characters will now be displayed correctly:

System.IO.File.ReadAllText(path) does not read the html file

I want to read the html file.And for that I use System.IO.File.ReadAllText(path).It can read all the html file but there is one file which is not read through this function.
I have also used
using (StreamReader reader = File.OpenText(fileName)) {
text = reader.ReadToEnd(); But still there is same problem.
What is the reason can be there ? And for that what can be the solution ? Or any other way to read the file ?
I'll take a wild guess:
The file contains unicode sequences for extended chars and the diagnose is based on (mismatched) length.
if I debug the code in the it looks
like
"<\0h\0t\0m\0l\0>\0<\0h\0e\0a\0d\0>\0\r\0\n\0<\0M\0E\0T\0A\0
\0h\0t\0t\0p\0-\0e\0q\0u\0i\0v\0=\0\"\0C\0o\0n\0t\0e\0n
Which is a valid beginning of a HTML file except for the very first char. The file is probably damaged by missing a unicode marker at the start. This damage was probably caused when it was written and is not (easy) repairable now.
You could try setting the WebClient.Encoding to UTF8 (and try a few ASCII as well).
Does MsgBox shows anything? Any error? What does varText.Length show?
string varText = File.ReadAllText(varFile, Encoding.Default);
MessageBox.Show(varFile + " Text: " + varText + " Lenght: " + varText.Length);
Verify in MessageBox that the path to file is correct, verify that the access rights from inside your application are the same as if you would be reading the file with notepad.
Came across this on google recently. The correct way to do it is via WebClient...
WebClient client = new WebClient();
String guestMsg = client.DownloadString("C:\\temp\\TheBarGuestDetailsEmail.htm");
File.ReadAllText will mess up the html when it's doing a read, and characters like £ or ' will get messed up.

Categories