What is specific purpose of console.readline in this code?
String username = Console.Readline();
String password = Console.Readline();
String Valid = (username = "Kmp" && password = "Kmp")? "Valid user": "Invalid User";
Console.Writeline(Valid);
I am noob player ;), i need your help as much as you can give.
The code above is partially invalid. To address your primary question, Console.ReadLine() will read input from a user in the console window.
string username = Console.ReadLine();
username will be a memory reference of the user input. Also the type defined is as follows:
A string is a sequential collection of characters that is used to
represent text. A String object is a sequential collection of
System.Char objects that represent a string; a System.Char object
corresponds to a UTF-16 code unit. The value of the String object is
the content of the sequential collection of System.Char objects, and
that value is immutable (that is, it is read-only). For more
information about the immutability of strings, see the Immutability
and the StringBuilder class section later in this topic. The maximum
size of a String object in memory is 2GB, or about 1 billion
characters.
Now to address this logic:
String Valid = (username = "Kmp" && password = "Kmp")? "Valid user": "Invalid User";
You have a big issue in that line.
You do not use == which is for equality comparison.
I would likely do the following:
public string Authenticate(string username, string password)
{
if(String.Compare(username, "Example", false) == 0 && String.Compare(password, "Example", false) == 0)
return "Authenticated.";
return "Invalid credentials.";
}
Then where you have Valid you would simply have: string valid = Authenticate(username, password);. But instead of returning a string and consuming a message you could write back to the user directly with Write or WriteLine.
Other conditional approaches you could have done:
(username == "..." && password == "...") ? "..." : "..."
if(username == "..." && password == "...")
{
// True
}
Several approaches, but remember to use == for equality, single is for assigning values.
Console.ReadLine() is used to read input from console store input into string.
Here in your code, username and password is reading from console and storing it into respective variables
String username = Console.Readline(); //Reads input from console and store string value to username variable
String password = Console.Readline(); //Reads input from console and store string value to password variable
From MSDN
Reads the next line of characters from the standard input stream.
Console.ReadLine Method
Related
I have this code(heavily modified for your comfort):
string password = Console.ReadLine();
var checker = new Predicate<string>[] { (s) => s == password };
string password2 = CompareStringAgainstPredicatesAndReturn(checker);
The predicate's purpose is to verify that password2 is the same as password. Yet I am getting the following error message:
CS1628: Cannot use ref, out, or in parameter 'password' inside an anonymous method, lambda expression, query expression, or local function
I don't know how to parse a variable to the predicate. So how would I go about doing this?
Gonna point out one more time that this is not the actual code. The question is only regarding the actual predicate situation.
As I was afraid, the lack of a complete code caused confusion and understandable misunderstandings. Therefore, here is the full code
string password = BInput.GetPredicateString(
new string[] { "Choose your password" },
"Password: ", //Simply a prompt
"Your password needs to be between 8 to 30 characters long, contain at least 2 numbers and at least one special character", // Error message
new Predicate<string>[] {
(s) => s.Length > 8,
(s) => s.Length < 30,
(s) => s == password,
(s) => Verificator.ContainsSpecialCharacter(s) //Not native
}
);
BInput.GetPredicateString will confirm that the returned string fulfills all requirements within the predicate. This is why the Predicate is an array.
Hoping this brings more clarity, but it's fully possible it doesn't as I've been programming now for 14 hours and brain is like a soggy sponge.
Best regards,
Since you updated the question with more info, here is how I would check with a predicate array:
string? password = Console.ReadLine();
string? password2 = Console.ReadLine();
Predicate<string>[] checker = new Predicate<string>[] {
(s) => s.Length > 8,
(s) => s.Length < 30,
(s) => s == password
};
//when validated, this line can be used inside your GetPredicateString method
//password2 can be passed as parameter to GetPredicateString method.
var isPasswordValid = checker.All(predicate => predicate(password2));
Here I use All method to check all predicates are true.
So if I pass
password 123456789 and password2 123456789 => will be true
password 123456789 and password2 123456788 => will be false
password 1234567 and password2 1234567 => will be false
password 123456789012345678901234567890 and password2 123456789012345678901234567890 => will be false
One thing more to mention. In your variable String password... it contains also a conditions == password, this will fail because the variable name and variable input can not have the same name.
So you need to change String password =.. to String passwordPredicated =.. or something like that.
Original Answer
I am not sure why you are using array in predicted, but if you need to check one input against the other input, by using a predicate, you can do something like this:
string? password = Console.ReadLine();
string? password2 = Console.ReadLine();
Predicate<string> checker = new Predicate<string>(s => s == password);
bool isEqual = checker(password2);
Make 2 equal inputs and you get True else it will be false.
The class Predicate is a generic one.
You can create a class that encapsulates both passwords and use it with Predicate class.
class BothPasswords {
public string Password1 { get; set; }
public string Password2 { get; set; }
}
So, in the main method you will have, for example:
string password1 = "test";
string password2 = "test";
Predicate<BothPasswords> isUpper = objParam => objParam.Password1.Equals(objParam.Password2.ToUpper());
bool result = isUpper(new BothPasswords { Password1 = password1, Password2 = password2 });
I doubt you can use ref, out etc. Inside a lambda body.
Use a temp variable to store ref or
Use a simple extension methods and chain them for this case.
public static class PasswordValidator ...
public static bool HasValidLength(this string password)
{
[condition to check]
}
I am trying to store the hashed password in the database. Like given below.
Md5Encrypt.Md5EncryptPassword(viewModel.User.PasswordHash);
Textual Password : TestBasant1900
And it get stored in my Database table in sql server like this after passing this into Md5Encrypt : zb??"??8?(Y???0z
When I am trying to check the password in Database and current user logged in password :
public bool Login(string userName, string password)
{
try
{
using (var db1 = new DBEnitityObj)
{
var user = (from u in db1.ftUsers
where (u.UserName == userName && u.IsApproved == true)
select u).First();
var PasswordHash1 = user.PasswordHash;
var encoded = Md5Encrypt.Md5EncryptPassword(password);
// It fails in the below condition
return user.PasswordHash.Equals(encoded);
}
}
catch
{
return false;
}
}
It fails in the below condition since the hashed password over here will return this : zb��"��8�(Y���0z
I am using this for md5 Hashing
public static string Md5EncryptPassword(string data)
{
var encoding = new ASCIIEncoding();
var bytes = encoding.GetBytes(data);
var hashed = MD5.Create().ComputeHash(bytes);
return Encoding.UTF8.GetString(hashed);
}
Can any one please tell me what is hashed password is not getting matched with password which I enter on the user interface
zb��"��8�(Y���0z is not equal to zb??"??8?(Y???0z
Can some one guide me what to do guys. Thanks in advance.
You store the data as VARCHAR, which is a string (text). MD5 gives you bytes. It is not guaranteed that these bytes are convertible to a string (text). The � character is the Unicode replacement character and means that there was an illegal character.
You either want to store the result as binary data (BLOB) or you want to ensure that it becomes simple text by encoding it in Base64 or hex for example.
I have a username|password file, where username is separated by a pipeline from the password and each line has such username/password combination
While knowing the username, I would like to be able to get the corresponding password
string text = System.IO.File.ReadAllText(#"C:\userPass.txt");
string username = "Johnny";
If you use ReadAllLines or ReadLines instead, you will get an array of lines from the file that you can search, splitting each line on the | character. The first part of the split (at index 0) will be the user name, and the second part (index '1') will be the password.
In the code below, we use StartsWith to find the first line that begins with the username and a "|" character, then return the password portion of that string. It will return null if the username is not found:
static string GetPassword(string userName, string filePath = #"C:\userPass.txt")
{
if (userName == null) throw new ArgumentNullException(nameof(userName));
if (!File.Exists(filePath))
throw new FileNotFoundException("Cannot find specified file", filePath);
return File.ReadLines(filePath)
.Where(fileLine => fileLine.StartsWith(userName + "|"))
.Select(fileLine => fileLine.Split('|')[1])
.FirstOrDefault();
}
Note that this does a case-sensitive comparison on the username. If you want to allow case-insensitivity, you can use:
.Where(fileLine => fileLine.StartsWith(userName + "|", StringComparison.OrdinalIgnoreCase))
Usage
string username = "Johnny";
string password = GetPassword(username);
// If the password is null at this point, then either it
// wasn't set or the username was not found in the file
I am having an issue with this block of code.
Console.WriteLine("What is your name?");
string PlayerName = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(PlayerName);
What I'm trying to do is get the computer to read the name you input, and ask you if that is your name. Directly after I type my name though there is an exception. Convert.ToInt32 isn't what I'm supposed to use, and I guess my question is what do I put there instead.
I am new to programming and I'm not even sure if it's called unicode. Sorry.
Console.ReadLine() will return a string, no need to do any conversions:
Console.WriteLine("What is your name?");
string PlayerName = Console.ReadLine();
Console.WriteLine(PlayerName);
Convert.ToInt32() throw casting error if you do not pass valid integer value inside it. So, you need to check it gracefully and get interger value. For that, you can Int32.TryParse(input, out val) and get integer value.
Ex :
int value;
if(Int32.TryParse(your_input, out value))
{
// if pass condition, then your input is integer and can use accordingly
}
So, your program will be like this if you want to print integer value only :
Console.WriteLine("What is your name?");
var value = Console.ReadLine();
int intVal;
if(Int32.TryParse(value, out intVal))
{
Console.WriteLine(intVal);
}
If you want only to print what you've got from ReadLine method, you can just have :
Console.WriteLine("What is your name?");
Console.WriteLine(Console.ReadLine());
Convert.ToInt32(String) "Converts the specified string representation of a number to an equivalent 32-bit signed integer". You are getting an error because you are not typing in an integer value in your console.
Your PlayerName variable is of type string, and the return value of Console.ReadLine() is already a string, so you don't need any conversion.
If you’re dealing with Unicode characters, you might have to set proper encoding like so
Console.InputEncoding = Encoding.Unicode;
Console.OutputEncoding = Encoding.Unicode;
Console.WriteLine("What is your name?");
string PlayerName = Console.ReadLine();
Console.WriteLine(PlayerName);
How do you get the message from the following inputs
Input is formated by field name separated by comma, followed by a colon, space and then the error message.
<FieldName1>, <FieldName2>, <FieldName3>: <ErrorMessage>"
Input Example
"ConsumerSecret, ConsumerKey: Invalid application credentials"
"Password: Invalid Must contain at least one alpha, one numeric, and one special character"
Method
string Message GetErrorByField (string FieldName, string InputString);
1
ErrorMessage = GetErrorByField("ConsumerSecret", "ConsumerSecret, ConsumerKey: Invalid application credentials");
ErrorMessage should now equal
"Invalid application credentials".
2
ErrorMessage = GetErrorByField("ConsumerKey", "ConsumerSecret, ConsumerKey: Invalid application credentials");
ErrorMessage should now equal
"Invalid application credentials".
3
ErrorMessage = GetErrorByField("Password", "Password: Invalid Must contain at least one alpha, one numeric, and one special character");
ErrorMessage should now equal
"Invalid Must contain at least one alpha, one numeric, and one special character".
Split the InputString i.e., second parameter in GetErrorByField() method by : then you will get the result by considering the splitted string with index 1
string Message = InputString.Split(':')[1].Trim();
You can simply use the Split method of the string class, and get the appropriate value:
GetErrorByField(string str)
{
var splited = str.Split(":".ToCharArray());
if (splited != null && splited.Length == 2)
return splited[1].TrimStart().TrimEnd();
return string.Empty;
}