Authentication form with a XML file - c#

I need help with this authentication form.
This is the xml file:
<USER_LIST>
<user>
<name>giulio</name>
<password>prova</password>
</user>
<user>
<name>giulia</name>
<password>prova1</password>
</user>
<user>
<name>renato</name>
<password>zero</password>
</user>
</USER_LIST>
and this is the code i wrote:
private void button4_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load("dati.txt");
foreach (XmlNode node in doc.SelectNodes("//user"))
{
String User = node.SelectSingleNode("name").InnerText;
String Pass = node.SelectSingleNode("password").InnerText;
if (User == textBox1.Text && Pass == textBox2.Text)
{
button1.Visible = true;
dlt_btn.Visible = true;
button3.Visible = true;
button3.Visible = true;
button5.Visible = true;
return;
}
else
{
MessageBox.Show("Invalid Username or Password!");
}
}
}
But like this, for example, if i login with the name "renato" and password "zero"
it give me back two times the message box "Invalid Username or Password!" and the third time it show the button needed. I know why but i can't think another way to do it. This is my very first project and i started coding like yesterday, so i'm sorry if ask you a stupid thing like this.
Thank you for your help in advance!

I suppose it's just for learning purpose or an assignment which should be kept as simple, otherwise it's not secure at all.
You don't need to use a loop. Currently your loop loop checks all nodes one by one and for each node which doesn't match with given user/pass, shows the message box, that's why you see the message box until the loop reaches to the correct user/pass.
Without using a loop, you can check if the given user/pass exists in your xml file easily this way:
var userName = userNameTextBox.Text;
var password = passwordTextBox.Text;
var match = System.Xml.Linq.XElement.Load(#"d:\users.xml")
.Elements("user")
.Where(x => x.Element("name")?.Value == userName &&
x.Element("password")?.Value == password)
.Any();
Then if the match is not true, you can show message box.

The issue is that the message box will display each time you check an entry in the XML that doesn't match.
The simplest way to do this with minimal changes to your code is like this:
private void button4_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load("dati.txt");
bool found = false;
foreach (XmlNode node in doc.SelectNodes("//user"))
{
String User = node.SelectSingleNode("name").InnerText;
String Pass = node.SelectSingleNode("password").InnerText;
if (User == textBox1.Text && Pass == textBox2.Text)
{
found = true;
break;
}
}
if (found)
{
button1.Visible = true;
dlt_btn.Visible = true;
button3.Visible = true;
button3.Visible = true;
button5.Visible = true;
}
else
{
MessageBox.Show("Invalid Username or Password!");
}
}
We create a variable called found and set it to false. This is to ensure that if the XML is empty or there are no matches that we fail the check.
Then we loop over the results and we set found = true if a match is found. We call break to break out of the loop.
Once the loop is complete we check to see if our local variable is true:
if (found)
This is shorthand for if (found == true)
If it's true then we enable your buttons as before. If it's not true then we display the error message.
It will only display the error message once.

this is a solution, that works:
private void button4_Click(object sender, EventArgs e)
{
string username;
string password;
string CurrentUser = "";
string CurrentPwd = "";
bool LoginStatus = false;
username = textBox1.Text;
password = textBox2.Text;
XmlDocument xmxdoc = new XmlDocument();
xmxdoc.Load("dati.txt");
XmlNodeList xmlnodelist = xmxdoc.GetElementsByTagName("user");
foreach (XmlNode xn in xmlnodelist)
{
XmlNodeList xmlnl = xn.ChildNodes;
foreach (XmlNode xmln in xmlnl)
{
if (xmln.Name == "name")
{
if (xmln.InnerText == username)
{
CurrentUser = username;
}
}
if (xmln.Name == "password")
{
if (xmln.InnerText == password)
{
CurrentPwd = password;
}
}
}
if ((CurrentUser != "") & (CurrentPwd != ""))
{
LoginStatus = true;
}
}
if (LoginStatus == true)
{
button1.Visible = true;
dlt_btn.Visible = true;
button3.Visible = true;
button3.Visible = true;
button5.Visible = true;
return;
}
else
{
MessageBox.Show("Invalid Username or Password!");
}
}

Related

c# ignoring else if statement

I am trying to make a winforms application so when something is clicked it checks a webpage for it's response.
I have tested the web page to see if it is a PHP error but it works fine from that side.
It is completely ignoring the else if statement and skips to the else statement below it even though the response is "Unassigned".
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://fms.psrpc.co.uk/apiconfirmD.php?" + ApiKey);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (response)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
if (reader.ReadToEnd() == "Changed")
{
label2.Visible = false;
button1.Enabled = false;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
button8.Enabled = true;
timer1.Enabled = true;
}
else if (reader.ReadToEnd() == "Unassigned")
{
string message = "Error Code: B66794O37945O46791K##Error booking on.#Please make sure you have been assigned to a vehicle.##If this error persists please contact K.McCrudden.";
message = message.Replace("#", "" + System.Environment.NewLine);
string title = "Error!";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
}
else
{
string message = "Error Code: B002875O46883O84655K##Error booking on.#Please make sure you have booked a shift and have been assigned.##If this error persists please contact K.McCrudden.";
message = message.Replace("#", "" + System.Environment.NewLine);
string title = "Error!";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
}
}
}
No, it is not being ignored. You are reading all the data in your first if block by calling reader.ReadToEnd(). This way, there is no further data available to read in your else if statement; it returns empty string. Thus condition does not match and final else block gets executed.
Modify the code something like below. Notice the temporary data variable in below code.
StreamReader reader = new StreamReader(response.GetResponseStream());
string data = reader.ReadToEnd();//Read the data in temp variable.
//Use this variable to check the conditions further.
if (data == "Changed")
{
//Your code here
}
else if (data == "Unassigned")
{
//Your code here
}
else
{
//Your code here
}
You have an error in your general logic. When you enter the first if statement, you're reading to the end of the stream with the code reader.ReadToEnd(). In the next statement (the else), you're reading the stream again, but it has already been read, so it will return an empty string, thus the last else statement will effectively be hit.
You can also read about this on MSDN: StreamReader.ReadToEnd() Method.
Definition of the return value:
The rest of the stream as a string, from the current position to the end. If the current position is at the end of the stream, returns an empty string ("").
Your code should look like this:
StreamReader reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
if(result == "Changed")
{
label2.Visible = false;
button1.Enabled = false;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
button8.Enabled = true;
timer1.Enabled = true;
}
else if(result == "Unassigned")
{
string message = "Error Code: B66794O37945O46791K##Error booking on.#Please make sure you have been assigned to a vehicle.##If this error persists please contact K.McCrudden.";
message = message.Replace("#", "" + System.Environment.NewLine);
string title = "Error!";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
}
else
{
string message = "Error Code: B002875O46883O84655K##Error booking on.#Please make sure you have booked a shift and have been assigned.##If this error persists please contact K.McCrudden.";
message = message.Replace("#", "" + System.Environment.NewLine);
string title = "Error!";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
}

Xamarin.Forms setting IsVisible doesn't trigger before function is done.

In my Xamarin.Forms project I have a login form that logs in the user and then redirects them to another page. I want to show an ActivityIndicator while it attempts to login, but setting IsVisible to true doesn't actually take effect before the login function is done. My code looks like this:
void OnLoginButtonClicked(object sender, EventArgs e)
{
LoadingIndicator.IsVisible = true;
Login();
}
public void Login()
{
var user = new User
{
Email = usernameEntry.Text,
Password = passwordEntry.Text
};
User validUser = AreCredentialsCorrect(user);
if (validUser != null)
{
Navigation.PushAsync(new ProfilePage());
}
else
{
messageLabel.Text = "Login failed";
passwordEntry.Text = string.Empty;
//It will only show the LoadingIndicator at this point.
}
}
If the user is correct, it never shows the LoadingIndicator because it navigates to another page before it can show it.
If the user is invalid, it will only show the LoadingIndicator after it hits the else clause and shows the "Login failed". Can anyone figure why that is, and what I can do to fix it?
Use Async calls and await the main block of operations. If anything you want to update/change in UI, do it using BeginInvokeOnMainThread.
void OnLoginButtonClicked(object sender, EventArgs e)
{
LoadingIndicator.IsVisible = true;
await Login();
}
public async void Login()
{
await Task.Run(() => {
var user = new User
{
Email = usernameEntry.Text,
Password = passwordEntry.Text
};
User validUser = AreCredentialsCorrect(user);
}).ContinueWith((a) => SomeMethod(validUser));
}
public void SomeMethod()
{
Device.BeginInvokeOnMainThread(() =>
if (validUser != null)
{
Navigation.PushAsync(new ProfilePage());
}
else
{
messageLabel.Text = "Login failed";
passwordEntry.Text = string.Empty;
//It will only show the LoadingIndicator at this point.
}
}
}
Try using async/await. Allow the UI to update while also navigating.
async void OnLoginButtonClicked(object sender, EventArgs e)
{
LoadingIndicator.IsVisible = true;
await Login();
}
public async Task Login()
{
var user = new User
{
Email = usernameEntry.Text,
Password = passwordEntry.Text
};
User validUser = AreCredentialsCorrect(user);
if (validUser != null)
{
await Navigation.PushAsync(new ProfilePage());
}
else
{
messageLabel.Text = "Login failed";
passwordEntry.Text = string.Empty;
//It will only show the LoadingIndicator at this point.
}
}
Two possible explanations here one it could be redirecting so fast that it doesn't have time to display the loadingindicator, I have experienced this problem before. We had a really nice loading symbol and animation but then we switched to Aurelia framework and it logs in so fast it just doesn't have time to display it even though it was actually working. As for code changes I would try to add it into the login function as well at least for right now to give some clarity to if its actually just logging in so fast its not displayed or its just not displaying at all. Her is my suggestion.
void OnLoginButtonClicked(object sender, EventArgs e)
{
LoadingIndicator.IsVisible = true;
Login(LoadingIndicator.IsVisible);
}
public void Login(Bool IsVisible)<--- might have type wrong not familiar with you custom defines types I would expect it to be a bool though.
IsVisible = true;
{
var user = new User
{
IsVisible = true;
Email = usernameEntry.Text,
Password = passwordEntry.Text
};
User validUser = AreCredentialsCorrect(user);
if (validUser != null)
{
IsVisible = true;
Navigation.PushAsync(new ProfilePage());
}
else
{
IsVisible = true;
messageLabel.Text = "Login failed";
passwordEntry.Text = string.Empty;
//It will only show the LoadingIndicator at this point.
}
}
If nothing else this might help clarify why it isn't being displayed. Also don't forget to use the web debugger f12 by default on most browsers and look for the element that will contain the Indicator.
Hope this helps! If not let me know and I'll remove the answer(I had to use an answer because I can't comment under 50 rep) Cheers!

Why URL address is repeating?

I have website hosted over here: but when I login then the url into the address bar keeps repeating and getting longer like: this and here if you click on to the left side menu then you can see into the address bar that the URL keeps getting bigger and bigger. Please suggest me on the above why the URL is getting bigger like this?
please find the website credential as below:
username: int123
password: 123
Here is code sample:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["type"] == "logout")
{
Session.Clear();
Response.Cookies.Clear();
//FormsAuthentication.SignOut();
Response.Redirect("http://103.252.236.33/plesk-site-preview/2wayglobal.com/103.252.236.33/login.aspx");
}
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
string username = string.Empty;
string userid = string.Empty;
string address = string.Empty;
string company = string.Empty;
if ((txtUsername.Value.Trim() == string.Empty || txtUsername.Value.Trim() == "Username") && (txtPassword.Value.Trim() == string.Empty || txtPassword.Value.Trim() == "Password"))
{
//divError.Visible = true;
lblError.Text = "Please type the correct username and password";
ResetFields();
}
else if (txtUsername.Value.Trim() == string.Empty || txtUsername.Value.Trim() == "Username")
{
//divError.Visible = true;
lblError.Text = "User name is incorrect.";
ResetFields();
}
else if (txtPassword.Value.Trim() == string.Empty || txtPassword.Value.Trim() == "Password")
{
//divError.Visible = true;
lblError.Text = "Password is incorrect.";
ResetFields();
}
else
{
DataTable dtuserLogin = db.GetLoginDetails(txtUsername.Value.Trim(), txtPassword.Value.Trim());
try
{
if (dtuserLogin.Rows.Count > 0)
{
userid = Convert.ToString(dtuserLogin.Rows[0]["srno"]).Trim();
username = Convert.ToString(dtuserLogin.Rows[0]["username"]).Trim();
company = Convert.ToString(dtuserLogin.Rows[0]["company"]).Trim();
address = Convert.ToString(dtuserLogin.Rows[0]["address"]).Trim();
//FormsAuthentication.SetAuthCookie(username + ";" + company + ";" + address, true);
}
}
catch (Exception ex)
{
throw new Exception("Error in btnLogin_Click()" + ex.Message);
}
if (username == "admin")
{
Response.Redirect("http://103.252.236.33/plesk-site-preview/2wayglobal.com/103.252.236.33/Admin/Default.aspx", true);
}
else
{
Response.Redirect("http://103.252.236.33/plesk-site-preview/2wayglobal.com/103.252.236.33/User/Default.aspx", true);
}
}
}
private void ResetFields()
{
txtUsername.Value = "Username";
txtPassword.Value = "Password";
}
It is just the code at the end of the btn click event that redirects you to that url:
if (username == "admin")
{
Response.Redirect("http://103.252.236.33/plesk-site-preview/2wayglobal.com/103.252.236.33/Admin/Default.aspx", true);
}
else
{
Response.Redirect("http://103.252.236.33/plesk-site-preview/2wayglobal.com/103.252.236.33/User/Default.aspx", true);
}
I can't see the code that is causing the issue, but I will bet $1 you are calling Redirect and passing what you think is an absolute URL but is actually a relative URL. The browser is seeing the redirect as relative and simply adding on the path to the end of the URL that is already in the address bar. It will do this over and over until the URL overflows its buffer and you get a Bad Request error.
Instead of
Response.Redirect("AbsolutePath/PageName.aspx") //This is a relative URL!
you should use
Response.Redirect("~/AbsolutePath/PageName.aspx")
or
Response.Redirect("/AbsolutePath/PageName.aspx")
or
Response.Redirect("https://ServerName.com/AbsolutePath/PageName.aspx")
...depending on what you are trying to accomplish.

Set focus to text box from code behind after validation the inputs in asp.net web application

What I want to do is to validate the given input by the user and then set a focus on the invalid input in text box.
My save button function is given below.
protected void btnSave_OnClick(object sender, EventArgs e)
{
try
{
if (ValidateForm())
{
Users objUser = new Users();
objUser.Username = this.txtUsername.Text;
objUser.Password = this.txtPassword.Text;
objUser.Add();
this.labelMessage.Text = "User has been saved successfully";
}
}
catch (Exception ex)
{
Monitoring.WriteException(ex);
}
}
Validation function to validate the given input is not null or empty.
private bool ValidateForm()
{
bool isvalidate = true;
try
{
string username = this.txtUsername.Text;
string password = this.txtPassword.Text;
if (username == "" || username == string.Empty)
{
this.labelMessage.Text = "Please enter username";
this.txtUsername.Focus();
isvalidate = false;
}
else if (password == "" || password == string.Empty)
{
this.labelMessage.Text = "Please enter password";
this.txtPassword.Focus();
isvalidate = false;
}
}
catch (Exception ex)
{
Monitoring.WriteException(ex);
}
return isvalidate;
}
The problem is the I am unable to set focus to any textbox after validation.
Anyone know where I am wrong?
Or there is any other better way?
I have searched a lot but most of them setting the focus on Page load (Post back). I want to do it from code behind.
Try the following Code. Use this code in your code behind. And pass your textbox id to SetFocus function. It will surely solve your problem.
Replace this code
this.txtUsername.Focus();
With this code
ScriptManager.GetCurrent(this.Page).SetFocus(this.txtUsername);
Given below is a tested code.
private bool ValidateForm()
{
bool isvalidate = true;
try
{
string username = this.txtUsername.Text;
string password = this.txtPassword.Text;
if (username == "" || username == string.Empty)
{
this.labelMessage.Text = "Please enter username";
ScriptManager.GetCurrent(this.Page).SetFocus(this.txtUsername);
isvalidate = false;
}
else if (password == "" || password == string.Empty)
{
this.labelMessage.Text = "Please enter password";
ScriptManager.GetCurrent(this.Page).SetFocus(this.txtPassword);
isvalidate = false;
}
}
catch (Exception ex)
{
Monitoring.WriteException(ex);
}
return isvalidate;
}

if else with checkbox and string

could someone help me figure out what I am doing wrong. I have tried so many ways and can't get it to work in all cases at same time.
Our symbol devices have multiple firmware versions that cause issues with the wireless card in the device. if the firmware version is 86.09.0000 it will work fine. If the firmware version if anything else "01.09.000" it will cause issues so i have it dump a cab file with factory firmware and reboot device.
Thanks for help, below is working code.
if (checkBox1.Checked && myString == "86.09.0000")
{
//check box checked and correct string
}
else if ((checkBox1.Checked == false) && (myString == "86.09.0000"))
{
//check box not checked and correct string
}
else
{
// string doesn't match
}
I would assume you mean if myString isn't 86.09.0000... Is your final else in the wrong 'if' statement?
if (checkBox1.Checked && myString == "86.09.0000")
{
wipefiles();
}
else if ((checkBox1.Checked == false) && (myString == "86.09.0000"))
{
if (myThread == null)
{
label4.Visible = false;
pictureBox1.Enabled = false;
SystemIdleTimerReset();
menuItem1.Enabled = false;
myThread = new Thread(MyWorkerThread);
myThread.IsBackground = true;
myThread.Start();
}
}
else
{
MessageBox.Show("Install firmware");
}
Is this possibly what you were trying to accomplish?
Private void menuItem1_Click(object sender, EventArgs e)
{
String oemVersion = oemver.getOEMVersion();
String myVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
if (myVersion.Equals(oemVersion))
{
if (checkBox1.Checked)
wipefiles();
else
{
if (myThread == null)
{
label4.Visible = false;
pictureBox1.Enabled = false;
SystemIdleTimerReset();
menuItem1.Enabled = false;
myThread = new Thread(MyWorkerThread);
myThread.IsBackground = true;
myThread.Start();
}
}
}
else
{
MessageBox.Show("Install firmware");
}
}
Simply add another "OR" || condition in your if statement .See below
if (checkBox1.Checked && (myString == "86.09.0000"***||myString="01.09.000"***))
{
wipefiles();
}
else if ((checkBox1.Checked == false) && (myString == "86.09.0000"***||myString="01.09.000"***))
{
if (myThread == null)
{
label4.Visible = false;
pictureBox1.Enabled = false;
SystemIdleTimerReset();
menuItem1.Enabled = false;
myThread = new Thread(MyWorkerThread);
myThread.IsBackground = true;
myThread.Start();
}
}
else
{
MessageBox.Show("Install firmware");
}
Now It's working for you ! But it's not good .Because it's maay be going to lot of "OR" condition . So Please assign the mystring value from when code running!

Categories

Resources