how would i go back to option 1 when option 2 is completed(Regitration is completed then go to the login part of the code).
if (options == 1)
{
Console.WriteLine("Please enter username and password");
Console.Write("Username: ");
string username = Console.ReadLine();
Console.Write("Password: ");
string password = Console.ReadLine();
if (Login.login(username, password)) Console.WriteLine(username + " Succesfully logged in");
else if (!Login.login(username, password)) Console.WriteLine("Login failed");
}
// Register user
else if (options == 2)
{
Console.WriteLine("Please create a userbame and password");
Console.Write("Create Userame: ");
string newUsername = Console.ReadLine();
Console.Write("Create a Password: ");
string newPassword = Console.ReadLine();
string toWrite = newUsername + "|" + newPassword + "\n";
File.AppendAllText(fileName, toWrite);
}
try this
do
{
if (options == 1)
{
..... your code
options = 0;
}
// Register user
else if (options == 2)
{
... your code
options = 1;
}
} while (options > 0);
Here is a slightly different version:
while (options < 3)
{
if (options == 1)
{
Console.Clear();
Console.WriteLine("Please enter username and password");
Console.Write("Username: ");
string username = Console.ReadLine();
Console.Write("Password: ");
string password = Console.ReadLine();
if (Login.login(username, password))
{
Console.WriteLine(username + " Succesfully logged in");
options = 3;
}
else if (!Login.login(username, password))
{
Console.WriteLine("Login failed");
options = 3;
}
}
// Register user
else if (options == 2)
{
Console.WriteLine("Please create a userbame and password");
Console.Write("Create Userame: ");
string newUsername = Console.ReadLine();
Console.Write("Create a Password: ");
string newPassword = Console.ReadLine();
string toWrite = newUsername + "|" + newPassword + "\n";
//File.AppendAllText(fileName, toWrite);
options = options - 1;
}
}
Related
So baiscally my first registered username and password in my text file when i login is able to pass through the validation however my next pair gets past the .contains but fails at checking password, not giving me the message and closing the console.
Example of text file-
Elliot|Benten67Fred|Payne
It will be able to check Elliot and Benten67. However can locate Fred but not able to check if the password is right? Any help would be great
public void Register()
{
string filePath = #"/Users/elliot/Documents/Film Libary Software/Film-Libary/Film-Libary/bin/Debug/netcoreapp3.1/UserInfo.txt";
Console.WriteLine("Create A Username which contains A Upper Case character");
Username = Console.ReadLine();
bool usernameIsUpper = Username.Any(char.IsUpper);
if (usernameIsUpper)
{
Console.WriteLine("Please enter a password: ");
Password = Console.ReadLine();
string toWrite = Username + "|" + Password;
File.AppendAllText(filePath, toWrite);
Login();
}
else
{
Console.WriteLine("Invalid Username: Please try again!");
Register();
}
}
public void Login()
{
string fileName = #"/Users/elliot/Documents/Film Libary Software/Film-Libary/Film-Libary/bin/Debug/netcoreapp3.1/UserInfo.txt";
using (StreamReader reader = new StreamReader(fileName))
{
string line;
Console.WriteLine("Enter your username");
string loginUsername = Console.ReadLine();
while ((line = reader.ReadLine()) != null)
{
if (line.Contains(loginUsername))
{
int indexOfDelimiter = line.IndexOf('|');
string usernameFromFile = loginUsername;
string passwordFromFile = line.Substring(indexOfDelimiter + 1, line.Length - (indexOfDelimiter + 1));
Console.WriteLine("Please enter your password");
string enteredPassword = Console.ReadLine();
if (enteredPassword == passwordFromFile)
{
Console.WriteLine("Elliot well done");
}
}
}
}
}
Your reading code requires the each user be on a separate line, but you are not writing new lines, you can see that here
Elliot|Benten67Fred|Payne
you need
Elliot|Benten67
Fred|Payne
The error is here
string toWrite = Username + "|" + Password;
File.AppendAllText(filePath, toWrite);
you need
string toWrite = Username + "|" + Password + "\n";
File.AppendAllText(filePath, toWrite);
I have an existing .txt file that I would like to use to store my data, but when using this code I get an error at line 39 at switch case 1.
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
public static List<Pw> Site = new List<Pw>();
static void Main(string[] args)
{
string file = #"C: \Users\james\Documents\DataFolder\Vault.txt";
string command = "";
while (command != "exit")
{
Console.Clear();
Console.WriteLine("Please enter a command: ");
command = Console.ReadLine().ToLower();
switch (command)
{
case "1":
AddPw();
File.AppendAllLines(file, Pw.Site);
break;
case "2":
if (File.Exists(file))
{
// Read all the content in one string
// and display the string
string str = File.ReadAllText(file);
Console.WriteLine(str);
}
break;
}
}
}
private static void AddPw()
{
Pw pw = new Pw();
Console.Write("Enter the Username/Email: ");
pw.Username = Console.ReadLine();
Console.Write("Enter Full Name: ");
pw.FullName = Console.ReadLine();
Console.Write("Enter Phone Number: ");
pw.PhoneNumber = Console.ReadLine();
Console.Write("Enter Your Password: ");
string password = Console.ReadLine();
pw.Password = password;
Site.Add(pw);
}
private static void PrintPw(Pw pw)
{
Console.WriteLine("Username/Email: " + pw.Username);
Console.WriteLine("Full Name: " + pw.FullName);
Console.WriteLine("Phone Number: " + pw.PhoneNumber);
Console.WriteLine("Password: " + pw.Password[0]);
Console.WriteLine("-------------------------------------------");
}
private static void ListPw()
{
if (Site.Count == 0)
{
Console.WriteLine("Your address book is empty. Press any key to continue.");
Console.ReadKey();
return;
}
Console.WriteLine("Here are the current people in your address book:\n");
foreach (var pw in Site)
{
PrintPw(pw);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
public class Pw
{
public string Username { get; set; }
public string FullName { get; set; }
public string PhoneNumber { get; set; }
public string Password { get; set; }
}
I have updated your existing function.
using this function you can add and append data in existing file.
private static void AddPw(string filePath)
{
try
{
Pw pw = new Pw();
if (!File.Exists(filePath))
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath))
{
Console.Write("Enter the Username/Email: ");
pw.Username = Console.ReadLine();
sw.WriteLine(pw.Username);
Console.Write("Enter Full Name: ");
pw.FullName = Console.ReadLine();
sw.WriteLine(pw.FullName);
Console.Write("Enter Phone Number: ");
pw.PhoneNumber = Console.ReadLine();
sw.WriteLine(pw.PhoneNumber);
Console.Write("Enter Your Password: ");
pw.Password = Console.ReadLine();
sw.WriteLine(pw.Password);
}
}
else
{
using (StreamWriter sw = File.AppendText(filePath))
{
Console.Write("Enter the Username/Email: ");
pw.Username = Console.ReadLine();
sw.WriteLine(pw.Username);
Console.Write("Enter Full Name: ");
pw.FullName = Console.ReadLine();
sw.WriteLine(pw.FullName);
Console.Write("Enter Phone Number: ");
pw.PhoneNumber = Console.ReadLine();
sw.WriteLine(pw.PhoneNumber);
Console.Write("Enter Your Password: ");
pw.Password = Console.ReadLine();
sw.WriteLine(pw.Password);
}
}
}
catch (Exception ex)
{
}
}
File.AppendAllLines(file, Pw.Site);
In this line, you need to pass an IEnumerable for AppendAllLines to work. You can easily convert Site (which is List<Pw>) to an IEnumerable<string> using the ConvertAll method. Here's one way of achieving this:
Replace that line with this:
File.AppendAllLines(file, Site.ConvertAll<string>(
(p) => string.Format("{0} | {1} | {2} | {3}\n",
p.Username,
p.FullName,
p.PhoneNumber,
p.Password
))
);
This "lambda" basically takes your Pw object and converts it into a string inline.
For clarification I'm using Microsoft visual studio and trying to turn the cmd format into a cute little interactive terminal. I'm a bare basics beginner and I'm aware this may be an ambitious project for someone of my skill. The only thing I'm confused about at the moment is how to tell the program that I want it to start itself over within the constraints of an else if statement.
static void Main(string[] args)
{
Console.WriteLine("What's your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
Console.WriteLine("What's your age?");
string age = Console.ReadLine();
Console.WriteLine("Your name is " + name + " and you are " + age + " years old, Correct?");
string val = Console.ReadLine();
if (val == "yes")
{
Console.WriteLine("Data confirmed, thank you for your cooperation!");
}
else if (val == "no")
{ //I would like to restart the code if this condition is met
Console.WriteLine("Incorrect data provided, please try again");
}
else
{ //The issue with this line is that I want it to just ask if the data is correct again
Console.WriteLine("That is not a valid response, try answering with a yes or no");
}
Try something like this. Basically, you're wrapping your code in a loop (in this case, a "do...while" loop, and adding a flag indicating whether or not the program should "start over."
static void Main(string[] args)
{
bool finished;
do
{
finished = true;
Console.WriteLine("What's your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
Console.WriteLine("What's your age?");
string age = Console.ReadLine();
Console.WriteLine("Your name is " + name + " and you are " + age + " years old, Correct?");
string val = Console.ReadLine();
while(val != "yes" && val != "no") {
Console.WriteLine("That is not a valid response, try answering with a yes or no");
val = Console.ReadLine();
}
if (val == "yes") {
Console.WriteLine("Data confirmed, thank you for your cooperation!");
}
else if (val == "no") {
Console.WriteLine("Incorrect data provided, please try again");
finished = false;
}
} while(!finished);
}
You can break your code out into a separate method, and call it from your Main() method. Then, in your else statement, you can have your new method call itself so that it executes again. (Disclaimer: It's been a long time since I've written C#.)
static void Main(string[] args) {
askName();
}
static void askName() {
Console.WriteLine("What's your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
Console.WriteLine("What's your age?");
string age = Console.ReadLine();
Console.WriteLine("Your name is " + name + " and you are " + age + " years old, Correct?");
string val = Console.ReadLine();
if (val == "yes") {
Console.WriteLine("Data confirmed, thank you for your cooperation!");
} else if (val == "no") {
askName();
} else {
//The issue with this line is that I want it to just ask if the data is correct again
Console.WriteLine("That is not a valid response, try answering with a yes or no");
}
}
So basically I'm trying to write a console application where it asks the user for a password and will continue to ask for it only three times and then stop with the use of a 'while' loop, but it keeps on looping and asking me for the password even if the correct password was used and after I entered it more that 3 times.
const string pass = "Password";
string attempt;
do
{
Console.Write("Please enter password: ");
attempt = Console.ReadLine();
if (attempt == pass)
{
Console.WriteLine("Access granted.");
}
else
{
Console.WriteLine("Access denied.");
}
} while (true);
const string pass = "Password";
string attempt;
int n = 0;
do
{
Console.Write("Please enter password: ");
attempt = Console.ReadLine();
if (attempt == pass)
{
Console.WriteLine("Access granted.");
break;
}
else
{
Console.WriteLine("Access denied.");
n++;
}
} while (n<=3);
So you want to ask user password three time until correct one entered and stop asking if user enter correct on. You can do it by for loop
const string pass = "Password";
string attempt;
for(int i=0;i<3;i++)
{
Console.Write("Please enter password: ");
attempt = Console.ReadLine();
if (attempt == pass)
{
Console.WriteLine("Access granted.");
i = 4;
}
else
{
Console.WriteLine("Access denied.");
}
};
You can do the following:
const string pass = "Password";
string attempt;
int attempt = 0;
do
{
Console.Write("Please enter password: ");
attempt = Console.ReadLine();
if (attempt == pass)
{
Console.WriteLine("Access granted.");
}
else
{
Console.WriteLine("Access denied.");
attempt++;
}
} while (attempt <= 3 && attempt != pass);
string pass = "";
while (pass != "password")
{
Console.WriteLine("enter your password here");
pass = Convert.ToString(Console.ReadLine());
if (pass == "password")
{
Console.WriteLine("your password is correct");
}
}
Console.ReadKey();
Hi I would like to prevent users from entering nothing in the input field.
I've tried using an if else but the console keeps crashing when there's no input. (for both user input and ldap address input ==> I want it to show "No input detected." and allow the user to re-enter the username)
And if I used (results == " "), I would get a error:
"Operator '==' cannot be applied to operands of type
'System.DirectoryServices.SearchResult' and 'string'"
Is there any way for me to resolve this? The codes are as shown below.
Affected codes from line 16 onwards (for the top block of codes)
if (results != null)
{
//Check is account activated
bool isAccountActived = IsActive(results.GetDirectoryEntry());
if (isAccountActived)
Console.WriteLine(targetUserName + "'s account is active.");
else
Console.WriteLine(targetUserName + "'s account is inactive.");
//Check is account expired or locked
bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());
if (isAccountLocked)
Console.WriteLine(targetUserName + "'s account is locked or has expired.");
else
Console.WriteLine(targetUserName + "'s account is not locked or expired.");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n\n");
}
else if (results == " ")
{
//no user entered
Console.WriteLine("No input detected!");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n");
}
else
{
//user does not exist
Console.WriteLine("User not found!");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n");
}
If it helps, I've attached the whole code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Data.SqlClient;
namespace ConsoleApplication2
{
class Program
{
const String serviceAccountUserName = "mobileuser1";
const String serviceAccountPassword = "password123$";
const int UF_LOCKOUT = 0x0010;
const int UF_PASSWORD_EXPIRED = 0x800000;
static void Main(string[] args)
{
string line;
Console.WriteLine("Welcome to account validator V1.0.\n"+"Please enter the ldap address to proceed.");
Console.Write("\nEnter address: ");
String ldapAddress = Console.ReadLine();
try
{
if (ldapAddress != null)
{
Console.WriteLine("\nQuerying for users in " + ldapAddress);
//start of do-while
do
{
Console.WriteLine("\nPlease enter the user's account name to proceed.");
Console.Write("\nUsername: ");
String targetUserName = Console.ReadLine();
bool isValid = false;
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ldapAddress))
{
// validate the credentials
isValid = pc.ValidateCredentials(serviceAccountUserName, serviceAccountPassword);
// search AD data
DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapAddress, serviceAccountUserName, serviceAccountPassword);
//create instance fo the directory searcher
DirectorySearcher desearch = new DirectorySearcher(entry);
//set the search filter
desearch.Filter = "(&(sAMAccountName=" + targetUserName + ")(objectcategory=user))";
//find the first instance
SearchResult results = desearch.FindOne();
if (results != null)
{
//Check is account activated
bool isAccountActived = IsActive(results.GetDirectoryEntry());
if (isAccountActived) Console.WriteLine(targetUserName + "'s account is active.");
else Console.WriteLine(targetUserName + "'s account is inactive.");
//Check is account expired or locked
bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());
if (isAccountLocked) Console.WriteLine(targetUserName + "'s account is locked or has expired.");
else Console.WriteLine(targetUserName + "'s account is not locked or expired.");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n\n");
}
else if (results == " ")
{
//no user entered
Console.WriteLine("No input detected!");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n");
}
else
{
//user does not exist
Console.WriteLine("User not found!");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n");
}
}//end of using
}//end of do
//leave console when 'bye' is entered
while ((line = Console.ReadLine()) != "bye");
}//end of if for ldap statement
else if (ldapAddress == " ")
{
Console.WriteLine("No input detected.");
Console.ReadLine();
Console.WriteLine("\nEnter bye to exit.");
Console.ReadLine();
Console.WriteLine("Press any key to continue.\n");
Console.ReadLine();
}
else
{
Console.WriteLine("Address not found!");
Console.ReadLine();
Console.WriteLine("\nEnter bye to exit.");
Console.ReadLine();
Console.WriteLine("Press any key to continue.\n");
Console.ReadLine();
}
}//end of try
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
} //end of main void
static private bool IsActive(DirectoryEntry de)
{
if (de.NativeGuid == null) return false;
int flags = (int)de.Properties["userAccountControl"].Value;
return !Convert.ToBoolean(flags & 0x0002);
}
static private bool IsAccountLockOrExpired(DirectoryEntry de)
{
string attribName = "msDS-User-Account-Control-Computed";
de.RefreshCache(new string[] { attribName });
int userFlags = (int)de.Properties[attribName].Value;
return userFlags == UF_LOCKOUT || userFlags == UF_PASSWORD_EXPIRED;
}
}
}
You should put the ReadLine in a loop.
string UserName = "";
do {
Console.Write("Username: ");
UserName = Console.ReadLine();
if (!string.IsNullOrEmpty(UserName)) {
Console.WriteLine("OK");
} else {
Console.WriteLine("Empty input, please try again");
}
} while (string.IsNullOrEmpty(UserName));
You basically repeat the prompt over and over until the string entered by the user is no longer null or empty.
Best method would probably be to create a new function to get a non empty input:
private static string GetInput(string Prompt)
{
string Result = "";
do {
Console.Write(Prompt + ": ");
Result = Console.ReadLine();
if (string.IsNullOrEmpty(Result)) {
Console.WriteLine("Empty input, please try again");
}
} while (string.IsNullOrEmpty(Result));
return Result;
}
You can then just use the function to get your inputs like:
static void Main(string[] args)
{
GetInput("Username");
GetInput("Password");
}
Result:
Try using the code :
(!string.IsNullOrEmpty(input));
This is user first name and last name string
//Make container for the user first name and last name
string myFirstName = "";
string myLastName = "";
//Do while loop
do
{
//Welcomes user to the app and asks for first name then asks for last name
Console.WriteLine("Welcome");
Console.WriteLine("Enter first name: ");
//Takes users first name and last name and saves it in myFirstName and myLastName
myFirstName = Console.ReadLine();
Console.Write("Enter Last name: ");
myLastName = Console.ReadLine();
Console.WriteLine();
//If the first AND (&&) last name is not empty because the user entered first name and last name then display the hello message
if (!string.IsNullOrEmpty(myFirstName) && !string.IsNullOrEmpty(myLastName))
{
Console.WriteLine("Hello " + myFirstName + " " + myLastName + " hope you enjoy your day");
}
else //Else the first name or last name is left empty then display the error message
{
Console.WriteLine("Please enter your first name and last name");
Console.WriteLine();
}
//While if either the first name OR (||) last name is empty then keep asking the user for input
} while (string.IsNullOrEmpty(myFirstName) ||
string.IsNullOrEmpty(myLastName));
Console.ReadLine();
Output: