Why does StringBuilder.AppendLine not add a new line with some strings? - c#

I'm trying to use stringbuilder to create a body of string to be used in a text (not HTML) email. However some lines (where i include dynamic data, a new line is not added, but in some the newline works as intended.
Is there something basic i'm missing when using the stringbuilder class or is there some more fundamental process that should be happening?
in the below code:
sbUser.AppendLine("Please find below confirmation of your registration details. If any of these details are incorrect, please email someone#somewhere.com");
sbUser.AppendLine();
sbUser.AppendLine("Selected event : " + ContentPage.FetchByID(int.Parse(ddlEvent.SelectedValue)).PageTitle);
sbUser.AppendLine("Date of event : " + thisEvent.EventStartDate.ToString("dd MMM yyyy"));
sbUser.AppendLine("==============================================================");
sbUser.AppendLine();
(ContentPage and thisEvent are custom classes built using Subsonic(v2). PageTitle is an output type of string)
is get this as an output:
Please find below confirmation of your registration details. If any of these details are incorrect, please email someone#somewhere.com
Selected event : My Event Date of event : 16 Sept 2012 ==============================================================
as you can see, everything after the 3rd line in the code makes everything go on to one line.
however, further down the code i use:
sbRR.AppendLine("First name : " + txtFirstname.Text.Trim());
sbRR.AppendLine("Surname : " + txtSurname.Text.Trim());
etc,
and all these appear on seperate lines correctly. I can't see why this is happening.
the email is composed as such
mailMessage.Body = sbUser.ToString() + sbRR.ToString();
adding the following code:
sbUser.AppendLine("Selected event : " + ContentPage.FetchByID(int.Parse(ddlEvent.SelectedValue)).PageTitle + Environment.NewLine);
sbUser.AppendLine("Date of event : " + thisEvent.EventStartDate.ToString("dd MMM yyyy") + Environment.NewLine);
produces the following output:
Selected event : My Event
Date of event : 16 Sept 2012
==============================================================
which works i suppose, except it's added 2 newlines (the AppendLine and the Environment.NewLine). it seems that pulling the data directly straight from the database into a stringbuilder seems to be messing with the line ending. Even if I add text after the database pull, it still stays on one line.
UPDATE
doing
StringBuilder.Append("blah"+Environment.NewLine)
produces the correct result, however i'm still not understanding why that works and .AppendLine("blah"+<database content>) doesn't work.

I know the question is old and has been marked as answered, but I thought I'd add this here in case anyone else comes across this as it's the first hit on Google for StringBuilder.AppendLine() not working.
I had the same problem and it turned out to be an Outlook issue. Outlook re-formats text based emails by removing extra line breaks. You can click "We removed extra line breaks in this message -> Restore line breaks" in the header of the individual email, or change the setting that does this nasty little trick "Options->Mail->Message Format->Remove extra line breaks in plain text messages"
The workaround (since you can't control the settings on every potential email target) I found here Newsletter Formatting And The Remove Extra Line Breaks Issue.
Basically, if you add two white space characters to the beginning of each line, Outlook won't reformat the email.
Here's an extension method to help (method name is a bit verbose so change to your liking :))
namespace System.Text
{
public static class StringBuilderExtensions
{
public static void AppendLineWithTwoWhiteSpacePrefix(this StringBuilder sb, string value)
{
sb.AppendFormat("{0}{1}{2}", " ", value, Environment.NewLine);
}
public static void AppendLineWithTwoWhiteSpacePrefix(this StringBuilder sb)
{
sb.AppendFormat("{0}{1}", " ", Environment.NewLine);
}
}
}

Instead of
sbUser.AppendLine();
Try using
sbUser.Append(Environment.NewLine);
No idea why this works...

use Environment.NewLine
sbUser.AppendLine("Please find below confirmation of your registration details. If any of these details are incorrect, please email someone#somewhere.com");
sbUser.AppendLine(Environment.NewLine);
sbUser.AppendLine("Selected event : " + ContentPage.FetchByID(int.Parse(ddlEvent.SelectedValue)).PageTitle);
sbUser.AppendLine("Date of event : " + thisEvent.EventStartDate.ToString("dd MMM yyyy"));
sbUser.AppendLine("==============================================================");
sbUser.AppendLine(Environment.NewLine);

use Environment.NewLine after each line or where you want new line
eg:-
sbUser.AppendLine("Please find below confirmation of your registration details. If any of these details are incorrect, please email someone#somewhere.com" + Environment.NewLine);
sbUser.AppendLine("Selected event : " + ContentPage.FetchByID(int.Parse(ddlEvent.SelectedValue)).PageTitle);

Windows 10 Insider preview Build 15007. The Default Line Terminator and the Environment.NewLine are both "\n". To use "\r\n" I had to create a string constant and use it instead.

First
sbUser.Appendline();
Second
sbUser.Append("texto loco ");
Voila!
=)

Related

Calling a Python script from C# - changing the script's filepath causes the program to not work

The following code works perfectly without flaw:
public partial class MainForm : Form
{
string pyInterp = File.ReadAllText(Directory.GetCurrentDirectory() + #"\config\pathToPythonInterpreter.txt");
string pyWeather = #"C:\getWeather.py";
public MainForm()
{
InitializeComponent();
UpdateWeather();
}
public void UpdateWeather()
{
labelWeather.Text = PySharp.ExecutePy(pyInterp, pyWeather);
}
}
However, when I change the path to getWeather.py to not be in an arbitrary random location, like this:
string pyWeather = Directory.GetCurrentDirectory() + #"\scripts\getWeather.py";
Then my program no longer obtains the script's output. The script still works: I launched it using IDLE and it completed its function properly. When I call it using C#, the console opens, yet no output is obtained.
The Python script is the following:
from requests import get
from bs4 import BeautifulSoup as soup
r = get("http://www.ilmateenistus.ee/ilm/prognoosid/4-oopaeva-prognoos/")
parsed = soup(r.content, "html.parser")
container = parsed.find("div",{"class":"point kuusiku"})
print(str(container["data-title"]))
(It webscrapes my local weather)
PySharp.ExecutePy() can be viewed here
By far the strangest bug I've ever encountered. Any ideas?
EDIT 1: It seems that C# is indeed reading something from the script. It just appears that this something is.. nothing. I gave the label a default sample text, and after running the program, the label's text is simply changed to an empty string. Hope this incredible discovery helps somehow.
EDIT 2: The program fails to call the script correctly when its filepath contains spaces. For example:
C:\foo bar\testing\pyWeather.py
does not work!
Try surrounding the path that contains spaces with 2 double quotes.
For e.g.
string pyWeather = #"""C:\Users\[myname]\Documents\Visual Studio 2017\Projects\testing\testing\scripts\getWeather.py""";
Similarly, you can do string pyWeather = Directory.GetCurrentDirectory() + #"\scripts\getWeather.py"; followed by pyWeather = "\"" + pyWeather + "\"";.
I would want you to return the answer instead of printing. Printer is an I/O based solution to display. So it will work super fine with IDLE however it may not return results as you expected. I strongly believe this will solve your problem.
instead of printing please try return. I can give more support after trying this.
return(str(container["data-title"]))

Can I add a variable in a format string?

I'm new to this and just did my first Hello World program yesterday.
I'm wondering if i can change the f5 to a varible.
Console.WriteLine("{0:f5}", theAnswer);
The 5 would change depending on the user input.
This didn't work, but is it possible to use something like it,
Console.WriteLine("{0:f + myVarible}", theAnswer);
If not, any suggestions on what route I should take would be helpful.
You could try with:
Console.WriteLine("{0}", theAnswer.ToString("f" + myVariable));
Or, if you only have the {0} in:
Console.WriteLine(theAnswer.ToString("f" + myVariable));
You can try solve this by changing your code:
Console.WriteLine("{0:f + myVarible}", theAnswer);
to this
Console.WriteLine("{0}", usersAnswer.ToString("f" + myVariable));

Create clearcase dynamic view using CAL in C#

I'm trying to create a clearcase dynamic view using CAL in C# using the following code.
private static ClearCase.ClearTool ct;
string viewName = "tmp_view";
string cmd = "mkview –tag "+ viewName + " –stream " + selectedStream +"#"+ projectVob + " \\\\<Network Shared Path>\\"+ viewName +".vws";
ct.CmdExec(cmd);
On execution, ct.CmdExec method throws exception saying viewTag must be specified.
For the same cmd string I'm able to create a view using cleartool command prompt.
Can you please tell me why I'm unable to create a view in C#?
It is possible that you didn't used -tag but –tag: replace '–' (minus) by '-' (hyphen minus).
Note: same for –stream: use -stream.
(plus , minus , hyphen-minus)
See What's the toughest bug you ever found and fixed? :
"Hyphen-minus" is the regular familiar character on keyboards, ASCII 45 and U+002D, (ab)used in both "5-4=1" and "vice-versa".
The actual minus sign, which is longer, is U+2212 and is not in ASCII.
It is typical of IBM documentation which, unfortunately, use minus (the long '–'): any copy-paste coming from their page doesn't work immediately.

Variables, strings and increasing frustration

I'm pretty new to C# and am having a mare trying to get what should be a simple task to work, in a nutshell I've written a PowerShell script to create VApps within a vSphere environment, the PoSh script works perfectly, next I have created (my first go) a Windows Console Application to run (initially) this script with user input, here's the problem, within my console app I'm using Process.Start to call my PoSh script and pass parameters, but, they come out joined up and completely missing the last parameter, here's the line in question:
Process.Start("Powershell.exe","-ExecutionPolicy bypass F:\\hello.ps1 -Location " + location + " -AppName" + appname);
AppName is completely ignored and Location tends to come out as -Locationanywhere instead of -Location Anywhere, I'm sure it's something basic and I've trawled the usual group and RTFM but no joy!
Hello.ps1 is a test script that just records the parameters passed to it so I can check the output before touching my real script.
Any help gratefully received.
You're lacking a space between -AppName and the double quotes.
string.Format is a useful method in .Net - it allows you to easily replace placeholders with dynamic content in a way that makes viewing the 'complete' string intuitive:
string parameters = string.Format("-ExecutionPolicy bypass F:\\hello.ps1 -Location {0} -AppName {1}", location, appName);
Process.Start("Powershell.exe", parameters);
I'm not sure, but I think you need an space between -AppName and the appname
" -AppName " + appname
It's all I can help you :(
Might I suggest using String.Format() instead of using the + operator?
String.Format("-ExecutionPolicy bypass F:\\hello.ps1 -Location {0} -AppName {1}", location, appname)

C# - MessageBox - Message localization in resources and lines breaks

I would like to show MessageBox (WinForms) with string from Resources with lines breaks.
example without Resources (WORKS):
string someMsg = "Message. Details:\n" + someDetails;
MessageBox.Show(someMsg);
Result:
Message. Details:
here are some details
When I move string "Message. Details:\n" into Resources:
string someMsg = GlobalStrings.MsgBoxJustTest + someDetails;
MessageBox.Show(someMsg);
Result:
Message. Details:\nhere are some details
When I moved string with "\n" to resources then MessageBox.Show() stopped to interpret it as newline.
Edit: I'm thinking about: someMsg.Replace(#'\n',Environment.NewLine);
but it's still quite annoying for so simple thing.
if you add that to resources it doesn't take \n as escape charecter
Just open your resource file in notepad to see this and cahnge in XML file(resx)
or
Type your data in notepad with new line.
Copy that and paste in your resource editor
edit:
or
Type/Paste your data into the resource editor UI, select the \n and replace it with an actual linebreak, with Shift-Enter.
You could do something like this (as long as your not .net 2.0):
public static class StringExt
{
public static String FixNewLines(this String str)
{
return str.Replace(#'\n',Environment.NewLine);
}
}
And then:
string someMsg = GlobalStrings.MsgBoxJustTest + someDetails;
MessageBox.Show(someMsg.FixNewLines());
However, this will affect ALL strings in your application (namespace scope)
It's a dirty fix, but it's a quick fix.
Personally, I would just fix my logic all the way through, rather than do something like the above.
Maybe you can Open the resx file as code and add the line breaks directly in the
XML
OR
Possibly they get lost when reading due to escape character maybe try using \\
One easy solution is to store “placeholders” in a resource strings. For instane, this string is stored in *.resx under “MessageDetails” key: "Message. Details:{0}{1}". Then, in your code, use it like this:
MessageBox.Show(String.Format(GlobalStrings.MessageDetails, Environment.NewLine, #"The message"));
The advantage here is a portability, as you can see.

Categories

Resources