If not called. c# [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
incorrectly checks the response c#
I have a code:
Match match = regex.Match(responseFromServer);
if (match.Success)
{
var input = responseFromServer;
var split = input.Split(':');
var final = split[3];
ProcessStartInfo mcStartInfo = new Shitocode;
Process.Start(mcStartInfo);
this.Close();
}
else if (responseFromServer == " Bad Login")
{
MessageBox.Show("Uncorrect login/password!");
}
else if (responseFromServer == " Old version")
{
MessageBox.Show("Launcher is old!");
}
Why there is no message box showing in the last two inspections?
I have tried to do things differently:
if (match.Success)
{
var input = responseFromServer;
var split = input.Split(':');
var final = split[3];
ProcessStartInfo mcStartInfo = new Shitocode;
Process.Start(mcStartInfo);
this.Close();
}
else if (responseFromServer.Equals("Bad Login"))
{
MessageBox.Show("Uncorrect login/password!");
}
else if (responseFromServer.Equals("Old Version"))
{
MessageBox.Show("Launcher is old!");
}
I enter the wrong password, but does not open the messagebox

string s = instxtbox.Text;
string[] s1 = new string[3];
s1[0] = " ";
s1[1] = " ";
s1[2] = " ";
string[] portion = s.Split(s1, StringSplitOptions.RemoveEmptyEntries);
int val = Convert.ToInt32(portion[2]);
string reg = portion[1];
if (reg == "ax")
axtxtbox.Text = portion[2];
else if (reg == "bx")
bxtxtbox.Text = portion[2];
else if (reg == "cx")
cxtxtbox.Text = portion[2];
else if (reg == "dx")
dxtxtbox.Text = portion[2];

Probably your responseFromServer does not match the values you are checking (Bad Login, and Old Version).
Try to add another else at the end of the if sequence and look what you've got.
if (match.Success)
{
//your code
}
else if (responseFromServer.Equals("Bad Login"))
{
MessageBox.Show("Uncorrect login/password!");
}
else if (responseFromServer.Equals("Old Version"))
{
MessageBox.Show("Launcher is old!");
}
else
{
MessageBox.Show("Cannot login, unknown response: " + responseFromServer)
}
EDIT after comment
If you do not the exact message, but you know that it has to contain some exact string, you could change the two responseFromServer.Equals() to responseFromServer.Contains()

Just set a breakingpoint, go through the code and check the Value of responseFromServer Copy this in the two cases and compare it in your code, i noticed you have whitespaces in the 1st code part before " Bad Login", but im not sure its the reason anyway.

Related

Cleaning up nested if statements to be more readable?

I'm writing a project, and the part I'm doing now is getting arrow shaped real fast. How can I remove the nested if statements, but still have the same behaviour?
The code below might not look so bad now, but I'm planning on refactoring to include more methods.
public async Task FirstDiffTestAsync()
{
string folderDir = "../../../";
string correctReportDir = folderDir + "Reports To Compare/Testing - Copy.pdf";
string OptyNumber = "122906";
//Making a POST call to generate report
string result = ReportGeneration(OptyNumber).Result;
Response reportResponse = JsonConvert.DeserializeObject<Response>(result);
string newURL = reportResponse.documentUrl;
//Logging the Response to a text file for tracking purposes
await File.WriteAllTextAsync(Context.TestRunDirectory + "/REST_Response.txt", result);
using (StreamWriter w = File.AppendText(Context.TestDir + "/../log.txt"))
{
//Checking if the Integration failed
if (reportResponse.Error == null)
{
//now we have the url, reading in the pdf reports
List<string> Files = new List<string> { correctReportDir, newURL };
List<string> parsedText = PdfToParsedText(Files);
DiffPaneModel diff = InlineDiffBuilder.Diff(parsedText[0], parsedText[1]);
// DiffReport is a customised object
DiffReport diffReport = new DiffReport(correctReportDir, newURL);
diffReport.RunDiffReport(diff);
//In-test Logging
string indent = "\n - ";
string logMsg = $"{indent}Opty Number: {OptyNumber}{indent}Activity Number: {reportResponse.ActivityNumber}{indent}File Name: {reportResponse.FileName}";
if (diffReport.totalDiff != 0)
{
await File.WriteAllTextAsync(Context.TestRunDirectory + "/DiffReport.html", diffReport.htmlDiffHeader + diffReport.htmlDiffBody);
logMsg += $"{indent}Different lines: {diffReport.insertCounter} Inserted, {diffReport.deleteCounter} Deleted";
}
LogTesting(logMsg, w);
//Writing HTML report conditionally
if (diffReport.totalDiff != 0)
{
await File.WriteAllTextAsync(Context.TestRunDirectory + "/DiffReport.html", diffReport.htmlDiffHeader + diffReport.htmlDiffBody);
}
Assert.IsTrue(diffReport.insertCounter + diffReport.deleteCounter == 0);
}
else
{
LogTesting($" Integration Failed: {reportResponse.Error}", w);
Assert.IsNull(reportResponse.Error);
}
}
}
As mentioned in the comment, the indentation level is fine for now, but its always better to minimize when possible, especially when you are repeating same blocks of code.
The best way to do this is to write a separate function that contains that block of code and then call that function instead of the nested if statements.
In your case it would be something like this:
private async void checkTotalDiff(diffReport) {
...
}
You could pass anything you might need in the parameters. This way in your main code, you could replace the if statements with checkTotalDiff(diffReport) and save the return (if any) to a variable.
Also note I used void for return but you could change the type depending on what the function returns.
I wouldn't consider this as having an excessive amount of nested if-statements. It is fine as is. Otherwise you could do the following (also suggested by #Caius Jard):
public async Task FirstDiffTestAsync()
{
string folderDir = "../../../";
string correctReportDir = folderDir + "Reports To Compare/Testing - Copy.pdf";
string OptyNumber = "122906";
//Making a POST call to generate report
string result = ReportGeneration(OptyNumber).Result;
Response reportResponse = JsonConvert.DeserializeObject<Response>(result);
//Checking if the Integration failed
if (reportResponse.Error != null)
{
LogTesting($" Integration Failed: {reportResponse.Error}", w);
Assert.IsNull(reportResponse.Error);
return;
}
string newURL = reportResponse.documentUrl;
//Logging the Response to a text file for tracking purposes
await File.WriteAllTextAsync(Context.TestRunDirectory + "/REST_Response.txt", result);
using (StreamWriter w = File.AppendText(Context.TestDir + "/../log.txt"))
{
//now we have the url, reading in the pdf reports
List<string> Files = new List<string> { correctReportDir, newURL };
List<string> parsedText = PdfToParsedText(Files);
DiffPaneModel diff = InlineDiffBuilder.Diff(parsedText[0], parsedText[1]);
// DiffReport is a customised object
DiffReport diffReport = new DiffReport(correctReportDir, newURL);
diffReport.RunDiffReport(diff);
//In-test Logging
string indent = "\n - ";
string logMsg = $"{indent}Opty Number: {OptyNumber}{indent}Activity Number: {reportResponse.ActivityNumber}{indent}File Name: {reportResponse.FileName}";
if (diffReport.totalDiff != 0)
{
await File.WriteAllTextAsync(Context.TestRunDirectory + "/DiffReport.html", diffReport.htmlDiffHeader + diffReport.htmlDiffBody);
logMsg += $"{indent}Different lines: {diffReport.insertCounter} Inserted, {diffReport.deleteCounter} Deleted";
}
LogTesting(logMsg, w);
//Writing HTML report conditionally
if (diffReport.totalDiff != 0)
{
await File.WriteAllTextAsync(Context.TestRunDirectory + "/DiffReport.html", diffReport.htmlDiffHeader + diffReport.htmlDiffBody);
}
Assert.IsTrue(diffReport.insertCounter + diffReport.deleteCounter == 0);
}
}

Writing a certain amount of lines in a file C#

I am currently writing a program that takes in a file, loops through all of the lines.
The file contains a lot of variables + values in this format:
Message =
"alfjawejf1ij4l2jr183fhaalfjawejf1ij4l2jr183fhahalfjawejf1ij4l2jr183fhahalfjawejf1ij4l2jr183fhahalfjawejf1ij4l2jr183fhahh" //the string will encompass multiple
lines of length
Answer = ?
My program will modify the value within message and write it in a new file.
How do I store multiple lines of the value into one string (so I can modify it)?
I need it so that it recognizes "message", starts storing the next few lines, detects "answer" and stops.
For the string holding the message value, I believe some sort of concatenation will be used (concatenating multiple lines).
string[] file = System.IO.File.ReadAllLines(#path); //file is read
string pathNew = Path.GetDirectoryName(path) + "\\completed_" + Path.GetFileName(path);
using (StreamWriter writer = File.CreateText(#pathNew))
{
foreach (string line in file)
{
for (int i = 0; i < line.Length; i++)
{
if (line.Substring(0,6).Equals("Msg = "))
{
foreach (string msg in file)
{
}
}
}
}
}
You could create it pretty easily, if you would provide a method that returns an IEnumerable<string>, and then use the File.WriteAllLines( string, IEnumerable<string> ) utility method
A way you could do it could be
private IEnumerable<string> ReturnAllMessages( IEnumerable<string> lines )
{
bool isMessage = false;
foreach (var line in lines)
{
if (line.StartsWith('Msg ='))
{
isMessage = true;
// set a flag that the next lines are part of the message
// this would exclude the rest of the line from the results
// if you want it, you could use:
// yield return line.Substring('Msg ='.Length));
continue;
}
if (line.StartsWith('Answer ='))
{
// remove the flag
isMessage = false;
continue;
}
if (isMessage)
{
// yield a line that is a message
yield return line;
}
}
}
and then use the method in the following way
File.WriteAllLines( #newPath, ReturnAllMessages( File.ReadAllLines( #path ) ) );
(didn't really test the code though, so just use it as a reference ;) )
One way to do this would be to read all the text as a single string using File.ReadAllText, and then split it on "Message =" to get all the messages, and then split each message on "Answer = " to get the answer for each message (assuming the format is "Message = some message Answer = some answer Message = some other message Answer = some other answer").
It would be helpful if you included an actual sample from the file, since your code clearly was not written for the sample you've provided (there is no line where line.Substring(0,6).Equals("Msg = ") is true).
I've included a method in my sample below that creates a text file with a multi-line message, and then showed how you can read the message into a variable and display it in the console window.
Hope this helps:
private static void CreateFile(string filePath)
{
if (File.Exists(filePath)) File.Delete(filePath);
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
var fileLines = new List<string>
{
"Message = ",
"I weigh nothing, but you can still see me.",
"If you put me in a bucket, I make the bucket lighter.",
"What am I?",
"Answer = A hole",
"Message = ",
"What’s the difference between",
"a hippo and a Zippo?",
"Answer = ",
"A hippo is really heavy, ",
"and a Zippo is a little lighter."
};
File.WriteAllLines(filePath, fileLines);
}
private static void Main()
{
// Set this to a file that doesn't exist or that you don't care about
var filePath = #"f:\private\temp\temp.txt";
// Create a file with multi-line messages
CreateFile(filePath);
// Read all the file text
var fileText = File.ReadAllText(filePath);
// Split it into the message/answers
var messageAnswers = fileText.Split(new[] {"Message ="},
StringSplitOptions.RemoveEmptyEntries);
// Split each message into a message/answer array
foreach (var messageAnswer in messageAnswers)
{
var parts = messageAnswer.Split(new[] {"Answer ="},
StringSplitOptions.RemoveEmptyEntries);
var message = parts[0].Trim();
var answer = parts.Length > 1 ? parts[1].Trim() : "";
Console.WriteLine(message);
var userResponse = Console.ReadLine().Trim();
if (userResponse.Equals(answer, StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Correct!");
}
else
{
Console.WriteLine("The actual answer is: " + answer);
}
}
GetKeyFromUser("\nDone! Press any key to exit...");
}

StringReader not "exiting"/breaking

I am experiencing a problem with the below code… When I run it the code never exits. I have tried to debug this for about an hour and I am at a complete loss as to what the problem is. OutputDebug(); is essentially like Console.WriteLine();
//Iterate through all lines to find sections
using (StringReader lineReader = new StringReader(Program))
{
int i = 0;
string line = string.Empty;
while (line != null)
{
line = lineReader.ReadLine();
if (line != string.Empty)
{
//If the program is exiting (doExit == true), then break the lööp bröther
if (doExit)
break;
//Iterate through all characters in the line
foreach (char Character in line)
{
i++;
OutputDebug(i.ToString());
if (isOnSameLineAsSectionStart)
{
sectionName += Character;
}
else if (Character == ':' && sectionName == string.Empty)
{
isOnSameLineAsSectionStart = true;
}
else if (Character == ':' && !isOnSameLineAsSectionStart && sectionName != string.Empty)
{
OutputDebug("End of section \"" + sectionName + "\" found");
OutputDebug(linesInSection.Count() + " lines found total in " + sectionName + "\" during section search");
try
{
sections.Add(sectionName, linesInSection);
}
catch (Exception)
{
OutputError("Two/Multiple sections with the same names exist. Ignoring the latest section with the same name");
}
linesInSection = new List<string>();
sectionName = string.Empty;
isOnSameLineAsSectionStart = true;
}
}
if (!isOnSameLineAsSectionStart && sectionName != string.Empty)
{
linesInSection.Add(line);
}
if (isOnSameLineAsSectionStart && sectionName != string.Empty)
{
OutputDebug("Start of section \"" + sectionName + "\" found");
}
if (isOnSameLineAsSectionStart == true)
{
isOnSameLineAsSectionStart = false;
}
}
lineReader.Close();
OutputDebug("In StringReader!" + i);
}
Thanks in advance!
you can use while approach below:
while ((line = reader.ReadLine()) != null)
{
foreach (char Character in line)
{
i++;
OutputDebug(i.ToString());
}
}
Well, if you want to output all the characters line by line. You could split them into an array of strings:
var lines = Regex.Split(input, "\r\n|\r|\n") extracted from here.
Later, using a foreach instead of a while statment you should solve the problem:
foreach(string line in lines)
Also comparing a string to a null value... Doesn't look so fine. Why don't use (in-built) string.IsNullOrEmpty(line) method to check if the current line is null?
If you want to use your approach you should do something like this:
while (!string.IsNullOrEmpty(line = reader.ReadLine()))
{
// Your code...
}
Hope this helps!
Since we're limited to this snippet we can only make assumptions.
lineReader.ReadLine();
if this is a blocking call than the code may never exit as long as no input is given.
if this is a unblocking call, it means that it returns something even though no input is provided. If returned value is empty string in this case then you're in infinite loop.
I believe the key function is ReadLine here.

A Loop unnecessarily requires MessageBox, freezes if removed

I have a C# code that when it runs, it feeds approximately 200 values into separate lines in a multi-line enabled textbox but a messagebox in the middle, which I put just to be sure it's feeding the correct data, now freezes the whole code if removed. I couldn't understand the significance of it, previous textboxes handled heavier loads with little trouble but apparently this one require a short break or at least some sort of human interaction(luckily only pressing the OK button on a messagebox) so I was wondering if there is a solution or a way around it like a similar stop but not requiring my guidance. It's not convenient to press a key 200+ times just to get one group of data out of many.
Below is the code, just in case:
if (listBox3.SelectedIndex < 0 || listBox4.SelectedIndex < 0) {
MessageBox.Show("Select the Chart Parameters(E.g.: BTC-USD)");
}
if (listBox4.GetItemText(listBox4.SelectedItem).Contains(listBox3.GetItemText(listBox3.SelectedItem))) {
MessageBox.Show("Please select seperate pairs.(E.g.: NOT BTC-BTC but e.g.:BTC-USD)");
}
else
{
string url = textBox8.Text + listBox3.GetItemText(listBox3.SelectedItem) + listBox4.GetItemText(listBox4.SelectedItem);
MessageBox.Show(url);
System.Net.WebClient client8 = new System.Net.WebClient();
var html = client8.DownloadString(url);
string s = html.Replace("[[", "[");
string ss = s.Replace("]]", "]");
textBox9.Text = ss;
dynamic obj1 = JsonConvert.DeserializeObject(ss); //ss is the data
var timezz = (Int32)obj1.SelectToken("time");
textBox11.Text = textBox11.Text + timezz;
var data1m = (string)obj1.SelectToken("data1m");
ICollection<string> matches =
Regex.Matches(data1m, #"\[([^]]*)\]", RegexOptions.Multiline)
.Cast<Match>()
.Select(x => x.Groups[1].Value)
.ToList();
foreach (string match in matches) { textBox10.Text += Environment.NewLine + match; }
for (int i = 1; i < textBox10.Lines.Length; i++)
{
string linebyline = textBox10.Lines[i];
var resultString = Regex.Match(linebyline, #"\d+").Value;
//uni_time = resultString;
var yen = linebyline.Replace(resultString, string.Empty);
MessageBox.Show(yen);
/////WHY DOES IT NEEDS TO BE STOPPED BY THIS MSGBOX INORDER2 EXECUTE THE WHOLE CODE???
//////IF I REMOVE IT, IT FREEZES
var resultz = yen.Substring(yen.LastIndexOf(',') + 1);
//uni_vol = resultz;
var ztring = yen.Replace(resultz, string.Empty);
//MessageBox.Show(ztring);
//Regex re = new Regex(#"\d+(\.\d{1,4})?");
ICollection<string> mc = Regex.Matches(ztring, #"\d+(\.\d{1,4})?").Cast<Match>()
.Select(x => x.Groups[0].Value)
.ToList();
foreach (string m in mc)
{
//MessageBox.Show(m);
if (textBox13.Text == string.Empty) { textBox13.Text += m; }
else
{
textBox13.Text += Environment.NewLine + m;
}
}
}
}

Create new user and comparison for two textbox

I have to do a form for new user in my project.
I do not know what is wrong with it.
This is the method:
private void NewUserMethod() {
try {
NewUserTbl newUserTbl = new NewUserTbl();
newUserTbl.FName = txtFName.Text;
newUserTbl.LName = txtLName.Text;
newUserTbl.UserName = txtUserName.Text;
newUserTbl.NewPassword = txtPass.Text;
newUserTbl.ConfirmPassword = txtAgainPass.Text;
txtFName.Text = "";
txtLName.Text = "";
txtUserName.Text = "";
txtPass.Text = "";
txtAgainPass.Text = "";
if (txtPass == txtAgainPass) {
DB_Admin.NewUserTbls.InsertOnSubmit(newUserTbl);
DB_Admin.SubmitChanges();
MessageBox.Show("new user created");
} else {
MessageBox.Show("Wrong Password");
}
} catch (Exception)
{
MessageBox.Show("You entered wrong data");
}
}
I'm new at C# programming.
You were comparing two controls instead of their text property
if (txtPass == txtAgainPass)
{
}
However if you start comparing with it's Text property
like this
if (txtPass.Text == txtAgainPass.Text)
{
}
this won't bring any change because you are making empty
txtPass.Text = "";
txtAgainPass.Text = "";
Try like this
if (newUserTbl.NewPassword == newUserTbl.ConfirmPassword)
{
}
I'm assuming these are textboxes : if (txtPass == txtAgainPass). hence, they are different and not the same ...
try comparing the actual strings in them
to get the text of TextBox for comparison or any thing ,
you should write " .text " after the name
Like txtName.Text

Categories

Resources