I'm trying to make a username and login system to validate if the username and password passed by an user by input matches the username and password in an array of objects. I did using Array.Find() but when I run the program, the user and password are asked twice and I have to put them twice correct so I can advance which does not make sense...
Utilizador[] usersIniciais = utilizadoresDefault.UtilizadoresDefault(utilizadoresDefault.GenerateID());
PersonalTrainer[] ptsIniciais = ptsDefault.PTsDefault(utilizadoresDefault.GenerateID());
int option = novoLogin.LoginInicial();
Tuple<string, string> strings = novoLogin.DadosLogin(option);
string username = strings.Item1;
string password = strings.Item2;
novoLogin.ValidacaoDados(username, password, usersIniciais);
Console.ReadLine();
}
}
namespace RSGymPT.Classes
{
internal class Login
{
public static void Log(string Username)
{
Console.WriteLine($"User Logged: {Username}");
}
public int LoginInicial()
{
int option;
do
{
Console.Clear();
Console.WriteLine("Seleciona a opção pretendida: \n");
Console.WriteLine("1. Login");
Console.WriteLine("2. Sair\n");
Console.Write("A tua opção: ");
Int32.TryParse(Console.ReadLine(), out option);
} while (option != 1 && option != 2);
return option;
}
public Tuple<string, string> DadosLogin(int option)
{
if (option == 1)
{
Console.Clear();
Console.WriteLine("Please insert your Login data: \n");
Console.Write("User: ");
Username = Console.ReadLine();
Console.Write("Password: ");
Password = Console.ReadLine();
return Tuple.Create(Username, Password);
}
else if (option == 2)
{
Console.Clear();
Console.WriteLine("See you soon.\n");
Console.ReadKey();
Environment.Exit(0);
}
return Tuple.Create(Username, Password);
}
public void ValidacaoDados(string user, string password, Utilizador[] utilizadores)
{
Utilizador utilizador = Array.Find(utilizadores, element => element.NomeUtilizador == user);
do
{
Console.Clear();
Console.Write("User: ");
Username = Console.ReadLine();
Console.Write("Password: ");
Password = Console.ReadLine();
if (utilizador != null && utilizador.Password.Equals(password))
{
Console.WriteLine("Login correct");
}
else
{
Console.WriteLine("Bye");
Console.ReadKey();
Console.WriteLine();
Environment.Exit(0);
}
} while (Username == null || Password == null);
}
}
namespace RSGymPT.Classes
{
internal class Utilizador
{
public Utilizador[] UtilizadoresDefault(int id)
{
Utilizador[] usersInicial = new Utilizador[]
{
new Utilizador {Id = GenerateID(), Nome = "user1", NomeUtilizador = "user1user", Password = "user1234"},
new Utilizador {Id = GenerateID(), Nome = "user2", NomeUtilizador = "user2user", Password = "user1234"},
};
return usersInicial;
}
#endregion
}
}
I tried a lot of different approaches life foreach loop and array.firstOrDefault() but I keep with the same thing. Can someone kindly help me to find my mistake?
Related
so I have made my code and it works and everything but... now it says that I have to save it to a file. Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Case3Password
{
internal class Program
{
static void Main(string[] args)
{
bool que = false;
while (que == false)
{
Console.WriteLine("Choose whether to login, make or change");
string command = Console.ReadLine();
if (command == "make" && !MadeAccount)
{
MakeAccount();
}
else if (command == "change" && MadeAccount)
{
ChangePassword();
}
else if (command == "login" & MadeAccount)
{
Login();
}
else
{
Console.WriteLine("incorrect choice, type either 'login', 'make' or 'change'");
}
}
}
static bool MadeAccount = false;
static void MakeAccount()
{
Console.WriteLine("Input your username");
string Username = Console.ReadLine();
Console.WriteLine("Input your password");
string password = Console.ReadLine();
if (ContainsUpperAndLower(password) == true && ContainsNumbersAndSpecialCharacters(password) == true && ContainsNoNumbersAtStartOrEnd(password) == true && ContainNoSpace(password) == true && UsernamePasswordTrue(Username, password) == true)
{
string folder = #"C:\Temp\";
string fileName = "Dokumenter.txt";
string fullPath = fileName;
string[] lines = { Username, password };
File.WriteAllLines(fullPath, lines);
MadeAccount = true;
Console.WriteLine("Account succesfully created");
}
else
{
Console.WriteLine("Sorry this password doesn't meet the requirements");
}
}
static void ChangePassword()
{
Console.WriteLine("Input your username");
string username = Console.ReadLine();
Console.WriteLine("Input your password");
string password = Console.ReadLine();
string folder = #"C:\Temp\";
string fileName = "CSharpCornerAuthors.txt";
string fullPath = folder + fileName;
string[] text = File.ReadAllLines(fullPath);
string PreviousUsername = text[0];
string PreviousPassword = text[1];
if (username == PreviousUsername && password == PreviousPassword)
{
Console.WriteLine("What do you want to change your password to?");
string NewPassword = Console.ReadLine();
if (PreviousPassword != NewPassword)
{
if (ContainsUpperAndLower(password) == true && ContainsNumbersAndSpecialCharacters(password) == true && ContainsNoNumbersAtStartOrEnd(password) == true && ContainNoSpace(password) == true && UsernamePasswordTrue(username, password) == true)
{
string[] lines = { username, NewPassword };
File.WriteAllLines(fullPath, lines);
Console.WriteLine("Password succesfully changed");
}
else
{
Console.WriteLine("Sorry this password doesn't meet the requirements");
}
}
}
}
static void Login()
{
Console.WriteLine("Input your username");
string username = Console.ReadLine();
Console.WriteLine("Input your password");
string password = Console.ReadLine();
string folder = #"C:\Temp\";
string fileName = "CSharpCornerAuthors.txt";
string fullPath = folder + fileName;
string[] text = File.ReadAllLines(fullPath);
string PreviousUsername = text[0];
string PreviousPassword = text[1];
if (username == PreviousUsername && password == PreviousPassword)
{
Console.WriteLine("Succesfully logged in");
}
else
{
Console.WriteLine("Sorry either your username or password was incorrect");
}
//6 metoder stillet op --->
//Første metode har jeg kaldet LengthCheck og her har jeg lavet en if/else statement
}
public static bool LengthCheck(string password)
{
if (password.Length >= 12) //Hvis password er større end/lig med 12 tegn så returnere den en true værdi
{
return true;
}
else //En else statement hvis nu den password er mindre end 12
{
return false; //Hvis den er ´mindre end 12 tegn så kommer den tilbage false
}
}
//2. metode hvor jeg siger at password SKAL anvende både store og små bogstaver
public static bool ContainsUpperAndLower(string password)
{
int i = 0; //det her er tælleren som bliver brugt senere i koden
//2 booleans som begge er sat til at være false
bool ContainsUpperCase = false;
bool ContainsLowerCase = false;
//Jeg har brugt en while-loop her som siger at password-længde er større end i
//og UpperCase && LowerCase
while (i < password.Length && !(ContainsUpperCase && ContainsLowerCase))
{
char letter = password[i]; //jeg har sat char letter = password[i]; altså indivduelle bogstaver siden at jeg skal tjekke alle bogstaverne igennem
if (ContainsUpperCase == false)
{
ContainsUpperCase = Char.IsUpper(letter);
}
if (ContainsLowerCase == false)
{
ContainsLowerCase = Char.IsLower(letter);
}
i = i + 1; //Man kan også bruge i++ her. Det præcist det samme
}
return ContainsUpperCase && ContainsLowerCase;
}
public static bool ContainsNumbersAndSpecialCharacters(string password)
{
int i = 0;
bool Numbers = false;
bool SpecialCharacters = false;
while (i < password.Length && !(Numbers && SpecialCharacters))
{
char letter = password[i];
if (Numbers == false)
{
Numbers = Char.IsDigit(letter);
}
if (SpecialCharacters == false)
{
SpecialCharacters = !Char.IsLetterOrDigit(letter);
}
i = i + 1;
}
return Numbers && SpecialCharacters;
}
public static bool ContainsNoNumbersAtStartOrEnd(string password)
{
if (Char.IsDigit(password[0]) == false & Char.IsDigit(password[password.Length - 1]) == false)
{
return true;
}
else
{
return false;
}
}
public static bool ContainNoSpace(string password)
{
int i = 0;
bool NoSpace = false;
while (i < password.Length && !(NoSpace))
{
if (NoSpace == false)
{
NoSpace = Char.IsWhiteSpace(password[i]);
}
i = i + 1;
}
NoSpace = !NoSpace;
return NoSpace;
}
public static bool UsernamePasswordTrue(string password, string Username)
{
if (Username.ToLower() != password.ToLower())
{
return true;
}
else
{
return false;
}
}
}
}
I have tried to look up videos and look up online but I don't really see how I can apply either of what i've seen to my code so i'm hoping someone can help me in here. I've been stuck on this project for so long just because of this whole file thing. I've never really grasped or understood it. Basically I have to save the input from the user when they for example make an account/login/change password etc stuff like that.
Basically I need to Save login and password in clear text in
a text file. Which can again be loaded when logging in or when changing the code.
I'm currently having issue on editing an existing username and password that i stored in a list.
Declarations:
public static Administrator Cadmin = new Administrator("", "", "", "");
public static Staff Cstaff = new Staff("", "", "", "");
public static Administrator Ladmin = new Administrator("", "", "", "");
public static Staff Lstaff = new Staff("", "", "", "");
public static string NCName;
public static string NCPassword;
List<User> UserList = new List<User>();
Executing code:
Console.WriteLine("Which user would you like to edit?");
string ruser = Console.ReadLine();
bool Ustop = false;
while (!Ustop)
{
foreach (User u in UserList)
{
if (ruser == Cadmin.CName)
{
Console.WriteLine("Please key in the existing password of the selected username");
string epass = Console.ReadLine();
if (epass == Cadmin.CPassword)
{
Console.WriteLine("Create new Administrator Username:");
NCName = Console.ReadLine();
Console.WriteLine("\nCreate new Administrator Password: ");
NCPassword = Console.ReadLine();
ruser.Replace(ruser, NCName);
epass.Replace(epass, NCPassword);
}
else
{
Console.WriteLine("Password that you key in is invalid!");
}
}
else
{
Console.WriteLine("Username that you key in did not exist!");
Console.WriteLine("Please key in a valid username");
}
}
}
I understood that you have issues on storing data in currently filled List, so here are one solution, use for instead if foreach, and then you can edit the specific member of the list, using it's index (I considered that CAdmin is inherited from User and User class has properties for CName and CPassword):
bool Ustop = false;
while (!Ustop)
{
for (var i = 0; i< UserList.Count ; i++ )
{
User u = UserList[i];
if (ruser == u.CName)
{
Console.WriteLine("Please key in the existing password of the selected username");
string epass = Console.ReadLine();
if (epass == u.CPassword)
{
Console.WriteLine("Create new Administrator Username:");
NCName = Console.ReadLine();
Console.WriteLine("\nCreate new Administrator Password: ");
NCPassword = Console.ReadLine();
u.CName = NCName;
u.CPassword = NCPassword;
}
else
{
Console.WriteLine("Password that you key in is invalid!");
}
}
else
{
Console.WriteLine("Username that you key in did not exist!");
Console.WriteLine("Please key in a valid username");
}
}
}
I'm wondering how to change this code to get first name and last name. My friend and I develop this code but I need to alter this code. There is Customer class as well where I set their properties. So looking for suggestion to alter this:
//Getting No: Of Customers for user wish to enter data.
do
{
needToGetInputFromUser = false;
Console.WriteLine("Please enter customer name");
customerName = Console.ReadLine();
if (customerName.Length < 5 || customerName.Length > 20)
{
Console.WriteLine("Invalid name length, must be between 5 and 20 characters");
Console.WriteLine("Please try again.");
Console.WriteLine(" ");
needToGetInputFromUser = true;
}
else
{
isUserEnteredValidInputData = true;
}
} while (needToGetInputFromUser);
//Getting Account number
My approach is slightly different from everyone else's, Where I ask for first name first, then last name. Here is the Customer class:
class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get { return FirstName + " " + LastName; } }
}
Basically I create a Customer object then set the FirstName and LastName based on user input individually like so:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var customer = new Customer();
customer.FirstName = GetStringValueFromConsole("Customer First Name");
customer.LastName = GetStringValueFromConsole("Customer Last Name");
Console.WriteLine("New Customers name: " + customer.FullName);
Console.WriteLine("Finished");
Console.ReadLine();
}
private static string GetStringValueFromConsole(string valueToAskFor)
{
var needToGetInputFromUser = false;
var stringValue = string.Empty;
do
{
Console.WriteLine("Please enter " + valueToAskFor);
stringValue = Console.ReadLine();
if (stringValue.Length < 5 || stringValue.Length > 20)
{
Console.WriteLine("Invalid \"" + valueToAskFor + "\", must be between 5 and 20 characters");
Console.WriteLine("Please try again.");
Console.WriteLine(" ");
needToGetInputFromUser = true;
}
else
{
needToGetInputFromUser = false;
}
} while (needToGetInputFromUser);
return stringValue;
}
}
}
List<Customer> ListOfCustomer = new List<Customer> ();
do
{
needToGetInputFromUser = false;
Console.WriteLine("Please enter customer name");
customerName = Console.ReadLine();
if (customerName.Length < 5 || customerName.Length > 20)
{
Console.WriteLine("Invalid name length, must be between 5 and 20 characters");
Console.WriteLine("Please try again.");
Console.WriteLine(" ");
needToGetInputFromUser = true;
}
else
{
Customer c = new Customer();
c.Name = customerName;
ListOfCustomer.Add(c);
isUserEnteredValidInputData = true;
}
} while (needToGetInputFromUser);
int CustomerCount = ListOfCustomer.Count;
I assume you get a string like:
Brian Mains
And you want to split by the " " between Brian and Mains, storing it in first/last name in the Customer object right? I think you are trying to do something like:
Customer c = new Customer();
if (customerName.Contains(" ")) {
var terms = customerName.Split(' ');
if (terms.Length == 2) {
c.FirstName = terms[0];
c.LastName = terms[1];
}
else {
//TBD
}
}
I need to create a program that will take the users name and "password". If they match the program will say you are in if not, that you're out. I wrote it for 1 user, but I don't know how to make multiple users in one program. My code is below. Thanks for your help :)
Console.WriteLine("Enter your Name");
Console.WriteLine("Enter your Pswrd");
string name = Console.ReadLine();
string pswrd = Console.ReadLine();
string myname = "John";
string mypswrd = "123456";
if (name == myname & pswrd == mypswrd)
{
Console.WriteLine("You are logged in");
}
else
{
Console.WriteLine("Incorrect name or pswrd");
}
Console.ReadLine();
//building the user "database" each pair is <user,password>
Dictionary<string, string> users = new Dictionary<string, string>();
users.Add("John", "123456");
//Here you should add more users in the same way...
//But i would advise reading them from out side the code (SQL database for example).
Console.Writeline("Enter your Name");
string name = Console.ReadLine();
Console.WriteLine("Enter your Passward");
string password = Console.ReadLine();
if (users.ContainsKey(name) && users[name] == password)
{
Console.WriteLine("You are logged in");
}
else
{
Console.WriteLine("Incorrect name or password");
}
Console.ReadLine();
This should work (contains no checks to see if the entered values are correct or not, you should add this kind of safety yourself :)):
Dictionary<string, string> namesToCheck = new Dictionary<string, string>
{
{"John", "123456"},
{"Harry", "someotherpassword"}
};
Console.WriteLine("Enter your Name");
string name = Console.ReadLine();
Console.WriteLine("Enter your Pswrd");
string pswrd = Console.ReadLine();
if (namesToCheck.ContainsKey(name) && namesToCheck[name] == pswrd)
{
Console.WriteLine("You are logged in");
}
else
{
Console.WriteLine("Incorrect name or pswrd");
}
Console.ReadLine();
Why not use arrays?
Console.WriteLine("Enter your Name");
Console.WriteLine("Enter your Pswrd");
string name = Console.ReadLine();
string pswrd = Console.ReadLine();
string[] names = "James,John,Jude".Split(Convert.ToChar(","));
string[] passes = "Pass1, Word2, Password3".Split(Convert.ToChar(","));
for (int i = 0; i<names.Length, i++)
{
if (names[i] == name && passes[i] == pswrd)
{
Console.WriteLine("You are logged in");
}
else
{
Console.WriteLine("Incorrect name or pswrd");
}
}
This will work with the following name/pswrd combinations:
James/Pass1, John/Word2, Jude/Password3
For a bigger list I suggest you use external text file and read lines in each.
Hi I would like to make a login screen wherein the user will input a username and password.but how do I validate it using an array? please help thank you
int[] username = { 807301, 992032, 123144 ,123432};
string[] password = {"Miami", "LosAngeles" ,"NewYork" ,"Dallas"};
if (username[0].ToString() == password[0])
{
MessageBox.Show("equal");
}
else
{
MessageBox.Show("not equal");
}
You need to find the index of the username first from your array username. Then based on that index compare the password from password array.
int[] username = { 807301, 992032, 123144, 123432 };
string[] password = { "Miami", "LosAngeles", "NewYork", "Dallas" };
int enteredUserName = 123144;
string enteredPassword = "NewYork";
//find the index from the username array
var indexResult = username.Select((r, i) => new { Value = r, Index = i })
.FirstOrDefault(r => r.Value == enteredUserName);
if (indexResult == null)
{
Console.WriteLine("Invalid user name");
return;
}
int indexOfUserName = indexResult.Index;
//Compare the password from that index.
if (indexOfUserName < password.Length && password[indexOfUserName] == enteredPassword)
{
Console.WriteLine("User authenticated");
}
else
{
Console.WriteLine("Invalid password");
}
Why do you not use a dictionary? A dictionary is some kind of array but it combines matching keys and values. TryGetValue will try to look up the username. If no username is found, the function will return false otherwise it will return true and the matching password. This password can be used to validate the password entered by the user.
Dictionary<int, string> userCredentials = new Dictionary<int, string>
{
{807301, "Miami"},
{992032, "LosAngeles"},
{123144, "NewYork"},
{123432 , "Dallas"},
};
int userName = ...;
string password = ...;
string foundPassword;
if (userCredentials.TryGetValue(userName, out foundPassword) && (foundPassword == password))
{
Console.WriteLine("User authenticated");
}
else
{
Console.WriteLine("Invalid password");
}