odd text display C# - c#

I have the following code in a windows form:
for (int i = 1; (i <= 10); i++)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
try
{
string message = "";
string m = "";
textBox2.Text = "";
int count = 0;
while (TestConnection(client))
{
char tt = ' ';
try
{
tt = Convert.ToChar(sr.Read());
if (count < 4)
{
message = tt.ToString();
m += message;
count += 1;
}
else if (count >= 4)
{
this.Invoke(new BindTextBoxControl(UpdateTextbox), new object[] {m + "\r\n"});
textBox2.Text = m + "\r\n";
m = "";
count = 0;
}
}
catch (OverflowException)
{
m += "";
}
}
}
catch (Exception g)
{
string error = "An error occurred: '{0}'" + g;
}
this gets a continuous stream of data from a StreamReader and then displays the data (4 character string). It is supposed to replace the current string shown with a new one(if the string is rrrr and then i receive tttt it shows tttt) but what it does is remove the first letter of the current string and add the next revived letter (have rrrr get tttt shows rrrt then rrtt and so forth).
how do i get this to work properly?
EDIT:
private void UpdateTextbox(string _Text)
{
textBox1.Text = _Text;
}
delegate void BindTextBoxControl(string text);
Nothing special about these.

Related

how do I check index of my file when I do certain operations C#

Hello I have a list of recipes (they are all file.dat).
In my software I can do certain operations, like "copy", "rename", "create new recipe" and "delete".
The structure name of these files is always date_index_nameOfRecipe.dat and they are all sorted by index.
For example I have 3 files:
date_1_name.dat
date_2_name.dat
date_3_name.dat
And if I want to copy the second one it becomes date_3_name.dat but I already have a file with index=3 and when I sort the list it creates conflict. The same goes with the function "rename" and "create new recipe". How can I solve this problem?
This is the function I use when I click on "copy":
private void buttonCopy_MouseUp(object sender, MouseEventArgs e)
{
_filePaths = Directory.GetFiles(_folder, "*.dat");
numberOfRecipes = _filePaths.Length;
indexCopy = numberOfRecipes + 1
}
this is what I do when I copy the file:
string index = indexCopy.ToString();
string date = DateTime.Now.ToString("yyyyMMddHHmmss_");
string nameDef = date + index + "_" + this.tbNewCopy.Text + ".dat";
string folder = ManageForm.ManageForm.formChooseRecipe.Folder;
_nameFileDestinationWithPath = folder + #"\" + nameDef;
string[] st = ManageForm.ManageForm.formChooseRecipe.FilePaths;
int num = st.Length;
string name = "";
string nameData = "";
string nameToPass = "";
int ind = -1;
bool fileExist = false;
for (int i = 0; i < num; i++)
{
name = Path.GetFileNameWithoutExtension(st[i]);
nameData = name;
ind = name.LastIndexOf("_");
name = name.Substring(ind + 1, (name.Length - ind - 1));
if (name == this.tbNewCopy.Text)
{
fileExist = true;
ind = i;
nameToPass = nameData + ".dat";
break;
}
}
if (!fileExist)
{
try
{
File.Copy(_nomeFileOrigin, _nameFileDestinationWithPath);
}
catch (Exception ex)
{
string s = ex.Message;
}
}
else
{
//SHOW POPUP Overwrite file copied
FormPopupOverwriteFileCopy formShowDialog = new FormPopupOverwriteFileCopy();
//Show testDialog as a modal dialog and determine if DialogResult = OK.
if (formShowDialog.ShowDialog() != DialogResult.OK)
{
if (formShowDialog.ChooseOverwrite)
{
try
{
File.Copy(_nomeFileOrigin, _nameFileDestinationWithPath, true);
ManageForm.ManageForm.formChooseRecipe.overwritten = true;
File.Delete(_nomeFileOrigin);
}
catch (Exception ex)
{
string s = ex.Message;
}
}
else
{
//chosen to not overwrite, setting destination name = origin name
ManageForm.ManageForm.formChooseRecipe.overwritten = true;
_nameFileDestinationWithPath = _nameFileOrigine;
}
formShowDialog.Dispose();
}
}
and this is the function I use for sorting:
public string[] SortArray(string[] recipes)
{
string[] sorted = new string[recipes.Length];
foreach (string r in recipes)
{
int index = new ComparableRecipe(r).IndexPart;
if (index != Int32.MaxValue)
{
if (index >= 1)
{
sorted[index - 1] = r; // top
}
}
}
return sorted;
}

When trying to output scrambled word from another method I get System.Char[]

I send a word to my scramble method that returns the scrambled word but when I try to output the word I get System.Char[]. I have seen another thread that is similar to mine but he used .ToCharArray and .ToString and that was his problem and I couldn't figure out mine from that. This is C# and I am still learning. I do not want answers. I want to know what am I doing wrong and suggestions on how to fix it. Thank you in advance.(I don't know why the for loop is showing up that way)
namespace Farmer_JumbleApp
{
//Author: Aaron Farmer
class Jumble
{
string hiddenWord = "";//chosen word from array
string[] words = new string[] { "sauce", "iphone", "tick", "time", "think", "dream", "awake" };
Random randy = new Random();
string display = " ";
public Jumble()
{ }
public void Master()
{
UIJumble Graphics = new UIJumble();
Admin Info = new Admin();
string userGuess = " ";
int randNum = 0;
int quit;
bool cont = true;//Loop condition
char[] scrambledWord = new char[] { };//Scrambled word
randNum = randy.Next(words.Length);
hiddenWord = words[randNum];
scrambledWord = Scramble(hiddenWord);
while (cont)
{
display = "The Scrambled Word is: ";
Graphics.DisplayOnLine(display);
for (int i = 0; i < scrambledWord.Length; i++)
{
display = "" + scrambledWord;
Graphics.DisplayOnLine(display);
}
//display = " ";
//Graphics.DisplayString(display);
display = "\n\n\nEnter your guess: ";
Graphics.DisplayOnLine(display);
userGuess = Graphics.RecieveString();
if (userGuess == hiddenWord)
{
Graphics.CleanUp();
Info.MyInfo();
display = "You are correct";
Graphics.DisplayString(display);
}//end of if
else if (userGuess != hiddenWord)
{
display = "Sorry, You are Incorrect";
Graphics.DisplayString(display);
}//end of else if
display = "Would you like to quit?\n1. Yes\n2. No";
Graphics.DisplayString(display);
quit = Graphics.RecieveInt();
if (quit == 1)
{
cont = false;
}
}//End of While_Loop
display = "Hope you enjoyed";
Graphics.DisplayString(display);
Environment.Exit(0);
}//End of Master Method
-----------------------------Next Method--------------------
public char[] Scramble(string word)
{
int randNum = 0;
int random;
char temp;
randNum = randy.Next(words.Length);
hiddenWord = words[randNum];
var displayWord = new char[word.Length]; //initializing array
for (int i = 0; i < word.Length; i++)
{
do
random = randy.Next(word.Length);
while (displayWord[random] != 0);
temp = word[i];
displayWord[random] = temp;
}
return displayWord;
}//End of Scramble Method
}//End of Class
}//End of Namespace
for (int i = 0; i < scrambledWord.Length; i++)
{
display = "" + scrambledWord;
Graphics.DisplayOnLine(display);
}
should be replaced with
for (int i = 0; i < scrambledWord.Length; i++)
{
display = "" + scrambledWord[i];
Graphics.DisplayOnLine(display);
}
as "" + scrambledWord will use scrambledWord.ToString() which returns System.Char[] (its type name)
OR
shortly put, as Joel Coehoorn has suggested:
Graphics.DisplayOnLine(new String(scrambledWord));

Parallel.For error

Im trying to pare a DateTime in a Parallel.For:
part of the code:
public void LoadLogFile(String fileName) {
//Thread.CurrentThread.Priority = ThreadPriority.Lowest;
String currentFile = "";
if (fileName.Contains("Compass")) {
currentFile = "Compass";
CompassLogLoadCompleted = false;
compassLogCollection.Clear();
compassLogCollection.AsParallel();
} else if (fileName.Contains("")) {
currentFile = "CoreService";
CoreServiceLogLoadCompleted = false;
coreServiceLogCollection.Clear();
;
compassLogCollection.AsParallel();
} else {
Console.Out.WriteLine("Wrong File");
}
if (fileName.Contains("CoreService") ||
fileName.Contains("Compass")) {
int numberOfSingleLineLog = 0;
int numberOfmultipleLineLog = 0;
String[] lines = new string[] {};
String temp = "";
string[] parts;
DateTime dateTime = new DateTime();
LoggingLvl loggingLvl = new LoggingLvl();
LoggingLvl.ELoggingLvl eLoggingLvl = new LoggingLvl.ELoggingLvl();
int id = 0;
char[] delimiters = new[] {' '};
string threadId = "";
string loggingMessage;
string loggingMessage2 = "";
//string dateAndTimestamp = "";
int ff = 0;
// Read the File and add it to lines string
try {
swCompass.Start();
lines = File.ReadAllLines(fileName);
swCompass.Stop();
} catch (Exception e) {
CompassLogLoadCompleted = true;
CoreServiceLogLoadCompleted = true;
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
swCompass.Reset();
swCompass.Start();
// Adding the objects to the collections
//compassLogCollection.EnableNotify = false;
Parallel.For(0, lines.Count(), j => {
//for (int i = 0; i < lines.Count(); i++) {
string dateAndTimestamp = "";
if (!CompassLogLoadCompleted || !CoreServiceLogLoadCompleted) {
try {
if (SingleLined(ref lines, j)) {
parts = lines[j].Split(delimiters,
StringSplitOptions.
RemoveEmptyEntries);
numberOfSingleLineLog++;
foreach (string t in parts) {
switch (ff) {
case 0:
dateAndTimestamp = t;
break;
case 1:
dateAndTimestamp += " " + t.Replace(",", ".");
dateTime = DateTime.Parse(dateAndTimestamp);
//dateTime = new DateTime();
dateAndTimestamp = "";
break;
case 2:
eLoggingLvl = loggingLvl.ParseLoggingLvl(t);
break;
case 3:
threadId = t;
break;
default:
temp += t;
break;
}
ff++;
}
loggingMessage = temp;
temp = "";
ff = 0;
id++;
loggingLvl = new LoggingLvl(eLoggingLvl);
if (fileName.Contains("Compass")) {
//CompassLogLoadPercent = ((double) numberOfSingleLineLog/lines.Count())*100;
CompassLogData cLD =
new CompassLogData(
(numberOfSingleLineLog +
numberOfmultipleLineLog),
dateTime,
loggingLvl, threadId,
loggingMessage);
//await addRoCompassLogCollectionAsync(cLD);
compassLogCollection.Add(cLD);
} else if (fileName.Contains("CoreService")) {
CoreServiceLogData cSLD =
new CoreServiceLogData(
(numberOfSingleLineLog +
numberOfmultipleLineLog),
dateTime,
loggingLvl,
threadId,
loggingMessage);
//await addRoCoreServiceCollectionAsync(cSLD);
coreServiceLogCollection.Add(cSLD);
} else {
Console.Out.WriteLine("File Not recognizable ");
}
//Console.Out.WriteLine(loggingMessage);
//loggingMessage = "";
} else {
loggingMessage2 += lines[j];
loggingMessage2 += "\n";
//parts[i] += lines[i];
//parts[i] += "\n";
if (NextLineIsANumber(ref lines, j)) {
numberOfmultipleLineLog++;
//Console.Out.WriteLine(loggingMessage2);
parts = loggingMessage2.Split(delimiters,
StringSplitOptions.
RemoveEmptyEntries);
foreach (string t in parts) {
switch (ff) {
case 0:
dateAndTimestamp = t;
break;
case 1:
dateAndTimestamp += " " +
t.Replace(",", ".");
//dateTime = DateTime.Parse(dateAndTimestamp);
dateTime = new DateTime();
dateAndTimestamp = "";
break;
case 2:
eLoggingLvl =
loggingLvl.ParseLoggingLvl(t);
break;
case 3:
threadId = t;
break;
default:
temp += t;
break;
}
ff++;
}
loggingMessage = temp;
temp = "";
ff = 0;
id++;
loggingLvl = new LoggingLvl(eLoggingLvl);
if (fileName.Contains("Compass")) {
CompassLogData cLD =
new CompassLogData(
(numberOfSingleLineLog +
numberOfmultipleLineLog),
dateTime,
loggingLvl, threadId,
loggingMessage);
//await addRoCompassLogCollectionAsync(cLD);
compassLogCollection.Add(cLD);
} else if (fileName.Contains("CoreService")) {
CoreServiceLogData cSLD =
new CoreServiceLogData(
(numberOfSingleLineLog +
numberOfmultipleLineLog),
dateTime,
loggingLvl,
threadId,
loggingMessage);
//await addRoCoreServiceCollectionAsync(cSLD);
coreServiceLogCollection.Add(cSLD);
} else {
Console.Out.WriteLine("File Not recognizable ");
}
loggingMessage2 = "";
}
}
} catch (Exception e) {
Console.Out.WriteLine("Shit Happens");
Console.Out.WriteLine(e.StackTrace);
}
if (currentFile == "Compass") {
//CompassLogLoadPercent =
// ((double)
// i
// /lines.Count())*100;
CompassLogLoadPercent = ((double)
j
/lines.Count())*100;
} else if (currentFile == "CoreService") {
CoreServiceLogLoadPercent =
((double)
j
/lines.Count())*100;
}
}
});
//}
//compassLogCollection.EnableNotify = true;
//compassLogCollection.notifyAll();
if (currentFile == "Compass") {
Console.Out.WriteLine("Compass TIME: " + swCompass.Elapsed);
} else {
Console.Out.WriteLine("CoreSevice TIME: " + swCompass.Elapsed);
}
if (currentFile == "Compass") {
CompassLogLoadCompleted = true;
Console.Out.WriteLine("Compass LOADING DONE");
} else if (currentFile == "CoreService") {
CoreServiceLogLoadCompleted = true;
Console.Out.WriteLine("CoreService LOADING DONE");
}
//CoreServiceLogLoadCompleted = true;
Console.Out.WriteLine("numberOfSingleLineLog: " +
numberOfSingleLineLog);
Console.Out.WriteLine("numberOfmultipleLineLog: " +
numberOfmultipleLineLog);
Console.Out.WriteLine("numberOfLogs: " +
(numberOfSingleLineLog +
numberOfmultipleLineLog));
Console.Out.WriteLine("");
//}
}
}
but i get the following Exception:
at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
at System.DateTime.Parse(String s)
at LogViewerV1.LogSession.<>c__DisplayClass3.<LoadLogFile>b__0(Int32 i) in c:\Users\Reza\Documents\Visual Studio 2012\Projects\Pallas informatik\LogViewerV1\LogViewerV1\src\LogSession.cs:line 169
A first chance exception of type 'System.FormatException' occurred in mscorlib.d
If I run this in a ordinary for loop i dont get any exception and everything works fine.
any Idea how to fix This?
FormatException would indicate that the input DateTime is not in the expected format. You should be using the overloads of DateTime.Parse which allow you to specify the DateTypeStyle.
See http://msdn.microsoft.com/en-us/library/system.datetime.parse.aspx#Parse1_Example
I think the problem is that you somehow set the culture of the main thread. But culture is not copied to any other thread, so the background threads that run (parts of) the Parallel.For() loop have different culture.
What you should do is to explicitly specify the culture to use:
DateTime.Parse(dateAndTimestamp, theCorrectCulture)

Changing commas within quotes

I am trying to read the data in a text file which is separated by commas. My problem, is that one of my data pieces has a comma within it. An example of what the text file looks like is:
a, b, "c, d", e, f.
I want to be able to take the comma between c and d and change it to a semicolon so that I can still use the string.Split() method.
using (StreamReader reader = new StreamReader("file.txt"))
{
string line;
while ((line = reader.ReadLine ()) != null) {
bool firstQuote = false;
for (int i = 0; i < line.Length; i++)
{
if (line [i] == '"' )
{
firstQuote = true;
}
else if (firstQuote == true)
{
if (line [i] == '"')
{
break;
}
if ((line [i] == ','))
{
line = line.Substring (0, i) + ";" + line.Substring (i + 1, (line.Length - 1) - i);
}
}
}
Console.WriteLine (line);
}
I am having a problem. Instead of producing
a, b, "c; d", e, f
it is producing
a, b, "c; d"; e; f
It is replacing all of the following commas with semicolons instead of just the comma in the quotes. Can anybody help me fix my existing code?
Basically if you find a closing " you recognize it as it was an opening quote.
Change the line:
firstQuote = true;
to
firstQuote = !firstQuote;
and it should work.
You need to reset firstquote to false after you hit the second quote.
else if (firstQuote == true) {
if (line [i] == '"') {
firstquote = false;
break;
}
Here is a simple application to get the required result
static void Main(string[] args)
{
String str = "a,b,\"c,d\",e,f,\"g,h\",i,j,k,l,\"m,n,o\"";
int firstQuoteIndex = 0;
int secodQuoteIndex = 0;
Console.WriteLine(str);
bool iteration = false;
//String manipulation
//if count is even then count/2 is the number of pairs of double quotes we are having
//so we have to traverse count/2 times.
int count = str.Count(s => s.Equals('"'));
if (count >= 2)
{
firstQuoteIndex = str.IndexOf("\"");
for (int i = 0; i < count / 2; i++)
{
if (iteration)
{
firstQuoteIndex = str.IndexOf("\"", firstQuoteIndex + 1);
}
secodQuoteIndex = str.IndexOf("\"", firstQuoteIndex + 1);
string temp = str.Substring(firstQuoteIndex + 1, secodQuoteIndex - (firstQuoteIndex + 1));
firstQuoteIndex = secodQuoteIndex + 1;
if (count / 2 > 1)
iteration = true;
string temp2= temp.Replace(',', ';');
str = str.Replace(temp, temp2);
Console.WriteLine(temp);
}
}
Console.WriteLine(str);
Console.ReadLine();
}
Please feel free to ask in case of doubt
string line = "a,b,mc,dm,e,f,mk,lm,g,h";
string result =replacestr(line, 'm', ',', ';');
public string replacestr(string line,char seperator,char oldchr,char newchr)
{
int cnt = 0;
StringBuilder b = new StringBuilder();
foreach (char chr in line)
{
if (cnt == 1 && chr == seperator)
{
b[b.ToString().LastIndexOf(oldchr)] = newchr;
b.Append(chr);
cnt = 0;
}
else
{
if (chr == seperator)
cnt = 1;
b.Append(chr);
}
}
return b.ToString();
}

How do you convert a string to ascii to binary in C#?

A while back (freshman year of high school) I asked a really good C++ programmer who was a junior to make a simple application to convert a string to binary. He gave me the following code sample:
void ToBinary(char* str)
{
char* tempstr;
int k = 0;
tempstr = new char[90];
while (str[k] != '\0')
{
itoa((int)str[k], tempstr, 2);
cout << "\n" << tempstr;
k++;
}
delete[] tempstr;
}
So I guess my question is how do I get an equivalent to the itoa function in C#? Or if there is not one how could I achieve the same effect?
This is very easy to do with C#.
var str = "Hello world";
With LINQ
foreach (string letter in str.Select(c => Convert.ToString(c, 2)))
{
Console.WriteLine(letter);
}
Pre-LINQ
foreach (char letter in str.ToCharArray())
{
Console.WriteLine(Convert.ToString(letter, 2));
}
Use an ASCIIEncoding class and call GetBytes passing the string.
It's not clear precisely what you want, but here's what I think you want:
return Convert.ToString(int.Parse(str), 2); // "5" --> "101"
This isn't what the C++ code does. For that, I suggest:
string[] binaryDigits = str.Select(c => Convert.ToString(c, 2));
foreach(string s in binaryDigits) Console.WriteLine(s);
Thanks, this is great!! I've used it to encode query strings...
protected void Page_Load(object sender, EventArgs e)
{
string page = "";
int counter = 0;
foreach (string s in Request.QueryString.AllKeys)
{
if (s != Request.QueryString.Keys[0])
{
page += s;
page += "=" + BinaryCodec.encode(Request.QueryString[counter]);
}
else
{
page += Request.QueryString[0];
}
if (!page.Contains('?'))
{
page += "?";
}
else
{
page += "&";
}
counter++;
}
page = page.TrimEnd('?');
page = page.TrimEnd('&');
Response.Redirect(page);
}
public class BinaryCodec
{
public static string encode(string ascii)
{
if (ascii == null)
{
return null;
}
else
{
char[] arrChars = ascii.ToCharArray();
string binary = "";
string divider = ".";
foreach (char ch in arrChars)
{
binary += Convert.ToString(Convert.ToInt32(ch), 2) + divider;
}
return binary;
}
}
public static string decode(string binary)
{
if (binary == null)
{
return null;
}
else
{
try
{
string[] arrStrings = binary.Trim('.').Split('.');
string ascii = "";
foreach (string s in arrStrings)
{
ascii += Convert.ToChar(Convert.ToInt32(s, 2));
}
return ascii;
}
catch (FormatException)
{
throw new FormatException("SECURITY ALERT! You cannot access a page by entering its URL.");
}
}
}
}
Here's an extension function:
public static string ToBinary(this string data, bool formatBits = false)
{
char[] buffer = new char[(((data.Length * 8) + (formatBits ? (data.Length - 1) : 0)))];
int index = 0;
for (int i = 0; i < data.Length; i++)
{
string binary = Convert.ToString(data[i], 2).PadLeft(8, '0');
for (int j = 0; j < 8; j++)
{
buffer[index] = binary[j];
index++;
}
if (formatBits && i < (data.Length - 1))
{
buffer[index] = ' ';
index++;
}
}
return new string(buffer);
}
You can use it like:
Console.WriteLine("Testing".ToBinary());
which outputs:
01010100011001010111001101110100011010010110111001100111
and if you add 'true' as a parameter, it will automatically separate each binary sequence.

Categories