This question already has answers here:
How can I run both of these methods 'at the same time' in .NET 4.5?
(5 answers)
Closed 4 years ago.
I'm trying to make a log in which has two validation methods to check who logged in. Now I have a problem where I need to call two methods at the same time. The code for now is like this, any help is appreciated.
public void Log()
{
Login loginAccount = new Login();
Console.WriteLine("Enter username: \n");
loginAccount.Username = Console.ReadLine();
Console.WriteLine("Enter password: \n");
loginAccount.Password = Console.ReadLine();
List<Login> UserLog = new List<Login>()
{
loginAccount
};
loginAccount.CheckUser(loginAccount.Username);
loginAccount.CheckAdmin(loginAccount.Username);
}
You may looking for something like this
Task.Run(() => loginAccount.CheckUser(loginAccount.Username));
Task.Run(() => loginAccount.CheckAdmin(loginAccount.Username));
Related
This question already has answers here:
Use a variable from another method in C#
(2 answers)
Closed 1 year ago.
Hey I'm very very new to c# coding and OOP, I'm currently working on a system that allows users to create login details, and then login with said details, however when I get to the part where I verify the users details I am having issues getting it to recognize my object, AccName, credentialCheck() can't successfully get the information from accountCreation(), I know this is a very basic thing to know but I have tried so many things and none of them have worked, or I haven't been doing them properly. My code is shown below and any guidance that could be provided would be greatly appreciated.
static void accountCreation()
{
Console.Write("Username: ");
string userNameInput = Console.ReadLine();
Console.Write("Email: ");
string userEmailInput = Console.ReadLine();
Console.Write("Password: ");
string userPasswordInput = Console.ReadLine();
Account AccName = new Account($"{userNameInput}", $"{userEmailInput}", $"{userPasswordInput}");
Console.Write($"{userNameInput} Registered successfully");
Console.WriteLine();
}
static void credentialCheck()
{
Console.Write("Email: ");
string userEmailCheck = Console.ReadLine();
Console.Write("Password: ");
string userPasswordCheck = Console.ReadLine();
if (userEmailCheck == AccName.userEmail )
{
Console.WriteLine();
Console.WriteLine("Success");
}
I suppose you are calling credentialCheck() just after accountCreation() and in the same thread. That out of the way, I supposed you have accName as a static variable and your class overall looks like this:
class Login {
protected static Account accName;
static void accountCreation()
{
// ...
accName = new Account(userNameInput, userEmailInput, userPasswordInput);
}
}
This means the variable accName remains as far as the execution context is concerned and not immediately destroyed after accountCreation() returns.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I've been working on a basic ATM-like application for my Intro to Programming course at my High School. I am trying to match a list of pre-existing "PIN codes" so that a user adding themselves to the database cannot use the same PIN as an existing user, but the following code is always resulting in a 'false' output.
newName01 = txtFirstName.Text;
newName02 = txtLastName.Text;
newPin = Convert.ToInt32(txtCreatePin.Text);
confirmPin = Convert.ToInt32(txtConfirmPin.Text);
float E = float.Parse(txtDepositInt.Text, CultureInfo.InvariantCulture.NumberFormat);
for (var i = 0; i < lstinfo.Count; i++)
{
if(newPin == lstinfo[i].pin)
{
active = false;
}
else
{
active = true;
}
}
if(active == true)
{
lstinfo.Add(new AccountInfo(newName01, newName02, newPin, E));
Submit_info();
}
You're looping through all the pins without ever breaking, so you're only ever getting the result of the last comparison. You should add a break; where you set active = false;
Instead, set active to true initially, then loop through your items. If you find a match, set active to false and exit the loop.
Here's an example using your code above:
active = true;
// Set active to false if we find a match (and exit the loop at that point)
for (var i = 0; i < lstinfo.Count; i++)
{
if (newPin == lstinfo[i].pin)
{
active = false;
break;
}
}
But with a List of objects the System.Linq extension method Any, the code can be made even simpler:
bool active = !lstinfo.Any(item => item.pin == newPin);
You mentioned in the comments that this wasn't working, so I guess you'll need to provide some sample data and the code you're using to show what's happening (edit your original question above).
Here's a code sample that shows how this method could be used:
public class Account
{
public string Pin { get; set; }
public Account(string pin) { Pin = pin; }
}
static void Main()
{
// Sample data of existing account pins
var accounts = new List<Account>
{
new Account("12345"),
new Account("40597"),
new Account("30894"),
new Account("30498"),
new Account("02467")
};
// Get new pin from user
string newPin;
while (true)
{
Console.Write("Enter a numeric pin: ");
newPin = Console.ReadLine();
// Ensure the string is all numbers
if (!newPin.All(char.IsNumber))
{
WriteColorLine("Error - must be numeric digits only\n", ConsoleColor.Red);
continue;
}
// Ensure that the pin is unique
if (accounts.Any(account => account.Pin == newPin))
{
WriteColorLine("Error - pin already exists\n", ConsoleColor.Red);
continue;
}
// If we got this far, the pin is all numbers and
// doesn't exist so we can break out of the loop
break;
}
// Create new account
var userAccount = new Account(newPin);
accounts.Add(userAccount);
WriteColorLine("\nCongratulations, you have a new pin", ConsoleColor.Green);
GetKeyFromUser("\nDone! Press any key to exit...");
}
Output
Rufus L is right, you need to break if you find the pin is used by someone else, you can use LINQ to get a shorter version of this, try this instead:
if(lstinfo.Any(p => p.pin == newPin))
{
return;
}
lstinfo.Add(new AccountInfo(newName01, newName02, newPin, E));
Submit_info();
This way you only will be adding new accounts if the pin is new.
This question already has answers here:
What's does the dollar sign ($"string") do? [duplicate]
(2 answers)
Closed 4 years ago.
this might be a trivial question for the experienced programmers, however I came across this line of code and want to understand what it does.
please see the code below where we are adding the in the entries list and also incrementing the count as well.
public class Journal
{
private readonly List<string> entries = new List<string>();
private static int count = 0;
public int AddEntry(string text)
{
entries.Add($"{++count}: {text}"); // my question is about this line of code
return count;
}
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
what is the purpose of doller sign in the mentioned line.
it is used for string interpolation,
with it you can write something like:
Console.WriteLine($"Test, this is your message: {message}");
instead of using the older command and syntax:
Console.WriteLine(String.Format("Test, this is your message: {0}", message));
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
Why, when I am running this code, does the question from the 2nd method repeat?
using System;
namespace mdisafmidf
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello world!");
CallMethod0();
Console.WriteLine(CallMethod0());
Console.ReadKey();
}
public static string CallMethod0()
{
string x;
Console.WriteLine("Do you agree this is a good day?");
Console.WriteLine("a)Yes b)No");
x = Console.ReadLine();
if (x == "Yes")
{
return ("Of course this is a good day");
}
else
{
return ("Oh, try and stay more positive!");
}
}
}
}
You're calling the method twice, so it's running twice.
CallMethod0();
Console.WriteLine(CallMethod0());
When you run CallMethod0, it returns a string. You need to store the result to a string variable, and then Console.Write the variable. Since you have the method call in there twice, it is running twice.
In other words, change it to:
public static void Main(string[] args)
{
Console.WriteLine("Hello world!");
string result = CallMethod0(); // store the result like this
Console.WriteLine(result); // print the result - don't call the method again
Console.ReadKey();
}
Just modify your code to be like this:
var message = CallMethod0();
Console.WriteLine(message);
You are using CallMethod0() twice.
Above you have CallMethod0(); and Console.WriteLine(callMethod0());
If you remove CallMethod0(); it works fine.
I have a simple console application, which is executed via Task Scheduler twice a day. When it runs like this, the default input for the Main() method will be the current month and current year.
However, sometimes this task needs to be executed manually outside the schedule; in such a case, it should prompt the user for Year and month separately.
I know how to send the arguments while executing the application like this:
myapplication.exe 2013 1
I can check for the number of arguments and code accordingly. But I want to prompt the user to enter month and year. How can we do this? Thank you for the help.
Please suggest a better title for this post.
You could introduce a special command line argument that would be only used when the app is executed via scheduler. If this argument is present, you would use current date, otherwise, you would prompt the user to enter the date for you.
E.g.
private static void Main(string[] args)
{
var yourFirstMagicNumber = -1;
var yourSecondMagicNumber = -1;
// Let's use the third argument as indicator that you need user input
if (args.Length > 2 && "true".Equals(args[2]))
{
Console.WriteLine("enter magic nr 1: ");
var firstArgument = Console.ReadLine();
yourFirstMagicNumber = Int32.Parse(firstArgument);
Console.WriteLine("enter magic nr 2: ");
var secondArgument = Console.ReadLine();
yourSecondMagicNumber = Int32.Parse(secondArgument);
}
else
{
yourFirstMagicNumber = Int32.Parse(args[0]);
yourSecondMagicNumber = Int32.Parse(args[1]);
}
}