How to dump all string values in an ArrayList C# - c#

I'm trying to code an email button into a program I use at the school where I work (Essentially, the program generates random passwords for a class I input, it then sets those passwords for that session, and changes them after the session finishes). The email button is so it sends the usernames and passwords to the teachers without me having to manually type it out.
I've got to the point where I can send the email via an SMTP relay, and I receive it. I've formatted the subject line which I'm happy with, I'm just stuck on the body now. Essentially, I have an ArrayList which holds each line as a value. I'm looking for a way to dump each value in the ArrayList to a new line in the body. So far I have this:
mailMsg.Body = ("Hi," + Environment.NewLine + Environment.NewLine + "Below are the usernames and passwords for the Controlled Assessment." + Environment.NewLine + Environment.NewLine + "Usernames Firstname Surname Passwords" + Environment.NewLine + "-----------------------------------------------------" + Environment.NewLine + );
My ArrayList is called SW, and I've parsed this into an Array too called aSW, using: String[] aSW = (String[]) SW.ToArray(typeof(string));
Can anyone give me pointers on how to do this? I apologise if more info is needed, only been coding in C# for about 3 weeks!

You can use LINQ
var arr = SW.OfType<string>().ToArray();
To concatenate all values with newline you can use string.Join
string.Join(Environment.NewLine, arr);

U can declare a stringbuilder and append each item in the arraylist
and after that assign body = sb.tostring()

Related

Add double quotes to a list to display in a label

Morning folks,
I have an ASP.Net C# page that pulls in a list of servers from a SQL box and displays the list of servers in a label. ("srv1,srv2,srv3"). I need to add double quotes around each of the servers names. ("srv1","srv2","srv3",)
Any help would be greatly appreached.
If you have string
string str = "srv1,srv2,srv3";
Then you can simply do
str = "\"" + str.Replace(",", "\",\"") + "\"";
Now str contains "srv1","srv2","srv3"
As far as I can understand, you are trying to use double quotes in a string.
If you want to use such,
you can use escape character:
("\"srv1\",\"srv2\",\"srv3\"",)
for the sake of simplicity, you can even convert it to a function:
private string quoteString(string serverName){
return "\"" + serverName + "\"";
}
Also, if you have already "srv1,srv2,srv3" format, find ',' characters in the string and add " before and after comma. Also, notice that you should add to first index and last index ".

How to write array values to columns of same line C#

I have a loop, which writes the values of an array into a .csv file. It is appending each line, so it writes the values vertically, however, I would like it to write each value in a different column rather than by line, that way I can filter the content after running the program.
My initial thought was to save all the values in one variable and then just write the variable to the .csv file, but I believe this would fill all values into one cell instead of distributing them to different columns.
I need it to write all of the values of the array on each loop, and then move to the next line on the each time it loops if that makes sense.
string pathCleansed = #"myfilename.csv";
string[] createText = {
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress1,
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress2,
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].SubDivision,
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].City,
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].PostalCode,
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].MainDivision,
resCleansedMulti.TaxAreaResult[0].confidenceIndicator
};
File.AppendAllLines(pathCleansed, createText, System.Text.Encoding.UTF8);
These are the current results: current results
This is what I would like it to do: desired results
I have had good success with CsvHelper package. You can find more information about it here https://joshclose.github.io/CsvHelper/api/CsvHelper/CsvWriter/.
This helper implements IDisposable so be sure to dispose if it when you're done or wrap it in a using which is more preferred. You will have to provide a writer object to CsvHelper. In the past I've used MemoryStream and StreamWriter.
//Headers if you want
csvWriter.WriteField("StreetAddress1");
csvWriter.WriteField("StreetAddress2");
csvWriter.WriteField("subDivision");
csvWriter.WriteField("City");
csvWriter.WriteField("PostalCode");
csvWriter.WriteField("MainDivision");
csvWriter.WriteField("ConfidenceIndicator");
csvWriter.NextRecord();
//Your Loop Here
{
csvWriter.WriteField(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress1);
csvWriter.WriteField(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress2);
csvWriter.WriteField(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].SubDivision);
csvWriter.WriteField(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].City);
csvWriter.WriteField(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].PostalCode);
csvWriter.WriteField(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].MainDivision);
csvWriter.WriteField(resCleansedMulti.TaxAreaResult[0].confidenceIndicator);
csvWriter.NextRecord();
}
Update: I was able to get the desired results by changing to code to:
string pathCleansed = #"myfilename.csv";
string[] createText = {
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress2 + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].SubDivision + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].City + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].PostalCode + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].MainDivision + "," +
resCleansedMulti.TaxAreaResult[0].confidenceIndicator
};
File.AppendAllLines(pathCleansed, createText, System.Text.Encoding.UTF8);

How to do that int variable which obtains data through textbox gets displayed in a double-quoted format in the txt log file?

I try to write a log file and have created a desktop app containing
two textboxes and one button. I want int variables to be displayed in
the double-quoted style in the txt file. I tried to Convert
$"{textBox1.Text}\"" to the int in the assignment process but to no
avail - got the format exception error. So how to do that int variable
gets displayed as double marked in the txt file?
string username = $"\"{textBox1.Text}\"";
File.AppendAllText(#"C:\Users\Cavid\Desktop\LogFiles\" +DateTime.Now.ToString("dd.MM.yyyy") + ".txt", DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + " " +username+ " has typed as username \r\n");
int password = Convert.ToInt32($"\"{textBox1.Text}\"");
File.AppendAllText(#"C:\Users\Cavid\Desktop\LogFiles\"+DateTime.Now.ToString("dd.MM.yyyy") + ".txt", DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + " " +password+ " has typed as password\r\n");
I'm simply trying to keep variables in the double-quoted format
Sorry, but you have to seem a wrong idea of how variables and data types work. An integer variable is just a 32 bit piece of memory with no quotes, or other formatting.
You simply can't assign or parse (without custom parse strings) a double quoted text to an integer. Stop trying that. Use this instead:
if (int.TryParse(textBox1.Text, out int password))
{
// text is a valid int, use `password`
}
To add double quotes use the following code:
string username = textBox1.Text;
//add double quote
username = "\"" + username + "\"";
//you can test it as shown below
File.WriteAllText(#"C:\text2.txt", username);
For the error, you are getting as others also mentioned you cannot convert all of string s to an integer( For example if your username is alphanumeric)
Do you really want password being integer only? User is allowed to have 123 password only, but not, say, a;sldf123_'vdkdm?
More natural choice is get the password (let it be in textBox2.Text) as it is:
string fileName = Path.Combine(
#"C:\Users\Cavid\Desktop\LogFiles", // Directory
$"{DateTime.Now.ToString("dd.MM.yyyy")}.txt"); // File Name
// Do not call DateTime.Now twice: you may have different times for username and password
DateTime moment = DateTime.Now;
string prefix = $"{moment.ToShortDateString()} {moment.ToShortDateString()}";
// It seems you want textBox2.Text, not textBox1.Text as a password (typo?)
string[] lines = new string[] {
$"{prefix} \"{textBox1.Text}\" has typed as username",
$"{prefix} \"{textBox2.Text}\" has typed as password",
};
// Append file once
File.AppendAllLines(fileName, lines);
If you insist on having integers as a password only, add int.Parse or int.TryParse:
...
string[] lines = new string[] {
$"{prefix} \"{textBox1.Text}\" has typed as username",
$"{prefix} \"{int.Parse(textBox2.Text)}\" has typed as password",
};
...

C# : Printing variables and text in a textbox

I need to know the command that I can print a sentence like "the item Peter at row 233 and column 1222 is not a number " .
I far as now I have made this:
string[] lineItems = (string[])List[]
if (!Regex.IsMatch(lineItems[0], (#"^\d*$")))
textBox2.Text += " The number ,lineItems[0], is bigger than
10 " + Environment.NewLine;
I want to print the array fields that have error. So if it finds something it will print it.
I made a code that correctly prints that there is an error on this line of the array, but I cant print the item of the array.
I need to have an Environment.NewLine because I will print many lines.
Thanks ,
George.
foreach (int lineNumber in lineItems)
{
if (lineNumber > 10)
textBox2.Text += "The number " + lineNumber + " is bigger than 10\n";
}
Something like this should work, (I have not checked the c# code, I am working on a mac at the moment)
TextBox2.Text="This is FirstLine\nThis is Second Line";
The code is not compilable absolutely, but I may be understand what you're asking about.
If you are asking about how to compose the string of text box, by adding new strings to it, based on some desicional condition (regex), you can do folowing, pseudocode:
StringBuilder sb = new StringBuidler();
if (!Regex.IsMatch(lineItems[i], (#"^\d*$")))
sb.Append(string.Format(The number ,{0}, is bigger than 10, lineItems[i]) + Environment.NewLine);
textBox2.Text = sb.ToString();
If this is not what you want, just leave the comment, cause it's not very clear from post.
Regards.

String concatenation doesn't seem to work in C#

I don't know what is wrong with the following string:
"Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " + System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")"
I can't get the concatenated string. I am getting Report(29-Dec-2009. That's all and
the rest gets left out from the string.
What is the reason?
Try this:
string filename =
String.Format(
"Report({0:dd-MMM-yyyy} to {1:dd-MMM-yyyy})",
System.DateTime.Now, System.DateTime.Now.AddMonths(-1));
EDIT: Since in your download box you got your filename broken in first whitespace, you could to try ONE of these:
filename = HttpUtility.UrlEncode(filename); // OR
filename = """" + filename + """";
Seems some browsers doesn't handles whitespaces very nicely: Filenames with spaces are truncated upon download. Please check it you can to download other filenames with whitespace in other sites.
You need to assign it to something:
string s = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " + System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")"
Update: I just saw your update to the question. How are you displaying the string? I'm guessing that you are displaying it in a GUI and the label is too short to display the complete text.
Try this:
string newstring =
string.Format(
"Report ({0} to {1})",
System.DateTime.Now.ToString("dd-MMM-yyyy"),
System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy")
);
What are you assigning the result to? It would be easier to read the code if you used string.Format
You are not assigning the concatenated result to anything, so can't use it:
string myConcatenated = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + ")";
Using this code...
string test = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " +
System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")";
I saw the following result.
Report(29-Dec-2009 to 29-Nov-2009)
It could be that the string is being truncated later on. Make sure that you set a breakpoint right after this code is run and check the value of the variable to which it is assigned (test in my case).
If, as in your previous question, you are using this value to create a file, it may be that it's the space before "to" that is causing the problem. Try to use:
"Report("
+ System.DateTime.Now.ToString("dd-MMM-yyyy")
+ "To"
+ System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy")
+ ")"
instead and see if that fixes it.
If that does fix it, you'll probably need to either figure out how to quote the entire file name so it's not treated as the three separate arguments, "Report(29-Dec-2009", "to" and "29-Nov-2009)". Or simply leave your reports names without spaces.
I'd choose the latter but then I'm fundamentally opposed to spaces in filenames - they make simple scripts so much harder to write :-)

Categories