String randomly containing a newline C# - c#

I'm completely lost with what is happening here.
string send = "!points add " + entries[winner] + " " + prize.ToString();
What I want to send is "!points add winnername prizeamount" but what I get is "!points add winnername\nprizeamount". I put \n because it writes a new line but trying to replace "\n", "\r" and "\t" with " " does nothing.
enter image description here
all I need is the message to be exactly"!points space add space winnername space prizeamount space"
If it's important the entries in my code is a List of strings

The entries strings already contain the new line character(s).
I suggest you replace with Environment.NewLine:
Replace Line Breaks in a String C#

The string object, 'entries[winner]' is having line-feeds (LF) or carriage-returns (CR). You try this to remove all LFs and CRs,
string send = "!points add "
+ entries[winner].Replace("\r", string.Empty).Replace("\n", string.Empty)
+ " " + prize.ToString();
Alternatively, you can use Trim() to remove leading\ trailing LFs\ CRs.
string send = "!points add "
+ entries[winner].Trim()
+ " " + prize.ToString();

No repro. The following code doesn't assert.
var entries=new List<string>{"Aaa", "Bbb", "Ccc"};
int prize=90;
int winner=1;
var send=String.Format("!points add {0} {1}",entries[winner],prize);
var send2="!points add " + entries[winner] + " " + prize.ToString();
Trace.Assert("!points add Aaa 90"==send);
Trace.Assert(send2==send);
If the result contains newlines, it's because the entries values contain newlines.
The best solution would be to clean the input data before storing it in the list, eg with String.TrimEnd or String.Trim, When loading data from a file for example, you can't be sure it doesn't contain trailing spaces.
To read clean data from a file you could use :
var entries=File.ReadLines()
.Select(line=>line.Trim())
.ToList();
If you add the entries one by one from user input :
entries.Add(newEntry.Trim());
If you can't change how the data is read (why?) you can trim when whenever you use an entry value:
var send=String.Format("!points add {0} {1}",entries[winner].Trim(),prize);
Loading clean data is a lot easier

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

how to insert newline after word in sql table in c#

I am trying to insert New Line after word car but it is not working with folowing solution
Char(13) - not working
Environment.NewLine - when i use this it works but appends '(' this char in sql rows like 'Car ( Rate:2CR'
\n\r - not working
Code:
cmd.Parameters.AddWithValue("#ColumnCar", Car + "char(13)" + "Rate:2CR";
//cmd.Parameters.AddWithValue("#ColumnCar", Car + "\n\r" + "Rate:2CR";
//cmd.Parameters.AddWithValue("#ColumnCar", Car + Environment.NewLine + "Rate:2CR";
cmd.ExecuteNonQuery();
Need output in sql table ColumnCar row value as follows:
Car
Rate:2cr
Note : here after Car there will be a newline and then Rate:2Cr will be added
With the LoC Car + "char(13)" + "Rate:2CR"; you will get a literal string "char(13)" between your 2 values, not a new line. If you want only a new line you can append "\n" or you can append the character equivalent (char)10 of new line.
Now what character or string actually represents a new line might depend on your environment including the collation you are using. In simple ascii/ansi this will work. It might not be the same for another collation. As #mhasan pointed out it could also be different depending on the O/S.
Using characters
const char carriageReturn = (char) 13; // see https://en.wikipedia.org/wiki/Carriage_return
const char newLine = (char) 10;
var car = "some car";
var toInsert = car + newLine + "Rate:2CR";
cmd.Parameters.AddWithValue("#ColumnCar", toInsert);
This would also work and produce the same result:
var toInsert = car + "\n" + "Rate:2CR";
Use combination of newline and carriage return characters i.e. char(13) + char(10) for inserting new line in windows OS system.
For MAC its \r char(13) , for Linux its \n i.e. char(10) but for windows its combination of both.
Try this code hope its working...
Make a string variable and store all value in variable..
ex: string abc=textbox1.text+" "+"Rate:2cr";
#ColumnCar=abc.tostring();
now put your code
cmd.Parameters.AddWithValue("#ColumnCar",datatype);
cmd.executenonquery();
The following code works fine with unicode fields in a MS SQL-Server 2016 DB :
string carString = $"Volvo{Environment.NewLine}Rate: 2CR";
SqlParameter parameter = new SqlParameter("#ColumnCar", carString);
command.Parameters.Add(parameter);
The '(' when you use Environment.NewLine must be another error somewhere else. What is Car in your code? A class instance? What does its ToString() expand to?
Don't use string1 + " " + string2 concatenation.
Use string.Format(), $"" - inline syntax (like above) or StringBuilder to build your strings.

Get a specific word from a line read from a .txt

right now I am reading some lines from a .txt.
Lets say, a user enters his name and in the .txt will be saved "Logged in {username} on 13/04/2016 at 10:55 am".
(Just an example.)
Now I want to read the .txt and print only specific parts into a textbox.
Meaning, in the textbox shall appear "{Username} - 13/04/2016 - 10:55 am".
So far, I am able to read from the .txt and print the whole line.
private void button_print_results_Click(object sender, RoutedEventArgs e)
{
int counter = 0;
string actual_line;
System.IO.StreamReader file_to_read =
new System.IO.StreamReader("myText.txt");
while ((actual_line = file_to_read.ReadLine()) != null)
{
textBox_results.Text = textBox_results.Text +"\n"+ actual_line;
counter++;
}
file_to_read.Close();
}
Is there a way, to reach this without overwriting the whole file?
And no, I can't change the format how the names etc. are saved.
(I used them here for a better understanding, the actual lines I need to read/check are different and auto-generated).
I don't expect full working code, it would be just great if you could tell me for which commands I need to look. Been a long time since I last worked with c#/wpf and I never worked much with Streamreader...
Thanks
I think regular expressions is the best tool for what you're trying to achieve. You can write something like this:
Regex regex = new Regex("Logged in (?<userName>.+) on (?<loginTime>.+)");
while ((actual_line = file_to_read.ReadLine()) != null)
{
Match match = regex.Match(actual_line);
if (match.Success) {
string loginInfo = string.Format("{0} - {1}", match.Groups["userName"], match.Groups["loginTime"]);
textBox_results.Text = textBox_results.Text +"\n"+ loginInfo;
}
}
There are couple of possible solutions for this. One most straight forward way for your case would be to use Substring and Replace.
Since the earlier string is always Logged in (note the last space) and you simply want to get the rests of the string after the phrase, replacing only the preposition of time words (" on ", " at ") with dash (" - ") you could take advantage on that:
string str = "Logged in {username} on 13/04/2016 at 10:55 am";
string substr = str.Substring(("Logged in ").Length) //note the last space
.Replace(" on ", " - ")
.Replace(" at ", " - ");
In your implementation, this is how it look like:
while ((actual_line = file_to_read.ReadLine()) != null)
{
actual_line = actual_line.Substring(("Logged in ").Length) //note the last space
.Replace(" on ", " - ")
.Replace(" at ", " - ");
textBox_results.Text = textBox_results.Text +"\n"+ actual_line;
counter++;
}
(Note: the solution above assumes the {username} does not contain spaced preposition of time words - which would almost likely be the case for a {username})
You could split the actual_line String so you get an array of Strings. And then fill the Strings you want to show in the TextBox into it.
string[] values = actual_line.Split(' ');
textBox_results.Text = textBox_results.Text + "\n" + values[2] + " " + values[6] + " " + values[7];
The text in the TextBox for example is "{username} 10:55 am"
You can use Regex for better performances as #Dmitry-Rotay suggested in the previous comment, but if you jave a not-so-big file your loop+string manipulations is an acceptable compromise.
Always use Environment.NewLine instead of "\n", it's more portable.
while ((actual_line = file_to_read.ReadLine()) != null)
{
actual_line = actual_line
.Replace(("Logged in "), String.Empty)
.Replace(" on ", " - ")
.Replace(" at ", " - ");
textBox_results.Text = textBox_results.Text
+ System.Environment.NewLine
+ actual_line;
counter++;
}

adding space in texbox results when sending thru email

wassup guys im new to C# coding and i did a search but couldn't find exactly what im looking for. So i have a couple of text-boxes which holds string elements and integers
what i want to do is when these boxes are filled in i want to send a summary of the email to client/customer but the format is whats getting me.
(first, one) are strings equaling different text-boxes
my code is:
emailCompseTask.Body = first + one + Enviroment.NewLine +
second + two + Enviroment.NewLine
and so on problem is which i send thru email it shows something like this:
computer service25.00
instead of:
computer service 25.00
is there a way to add spacing to make this more presentable? or even a better way perhaps thanks in advance guys
try this :
emailCompseTask.Body = first + one + " "+ second + two ;
body takes as HTML input, check here for more spacing option.
I'm a bit confused, but you just want to add some spacing in the output? Just throw some spaces in there like you would another variable.
first + " " + one + Environment.NewLine
+ second + " " + two + Environment.NewLine;
You can use a table
string tableRow = #"<tr>
<td>{0}</td>
<td>{1}</td>
</tr>";
string htmlTable = #"<table>
{0}
</table>";
string rows = "";
// Can do this in a loop
rows += string.Format(tableRow, first, one);
rows += string.Format(tableRow, first, one);
emailComseTask.Body = string.Format(htmlTable, rows);

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>";

Categories

Resources