Validation for the data input c# - c#

I am trying to make a login window for users and admin using XML files, so my issue is how to validate that the username and pwd field if the password is incorrect, my code only validate for admin but for the user, the form shows and it gives error as well.
It will be better if I can make it up with errorProvider.
Thank you in advance.
private void btnlogin_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
string file = #"../../../data/UsersDatabase.Xml";
doc.Load(file);
foreach (XmlNode node in doc.SelectNodes("//User"))
{
username = node.SelectSingleNode("id").InnerText;
pwd = node.SelectSingleNode("pass").InnerText;
}
if (username.Equals(txtusername.Text) && pwd.Equals(txtpwd.Text))
{
purchase fpur = new purchase();
fpur.Show();
}
foreach (XmlNode node in doc.SelectNodes("//Admin"))
{
username = node.SelectSingleNode("id").InnerText;
pwd = node.SelectSingleNode("pass").InnerText;
}
if (username.Equals(txtusername.Text) && pwd.Equals(txtpwd.Text))
{
Adminpanel fadmin = new Adminpanel();
fadmin.Show();
}
else
{
MessageBox.Show("Sorry, username and password are incorrect",
"Login Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

According your xml and your description, you would like to show different forms when we
input the correct userid and password.
I make the following code and it works well.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
User user = new User();
Admin admin = new Admin();
string path = "D:\\test.xml";
XDocument doc = XDocument.Load(path);
var user1 = doc.Descendants("User");
foreach (XElement item in user1)
{
if (txtUserName.Text==item.Element("id").Value&& txtPWD.Text == item.Element("pass").Value)
{
user.Show();
}
}
var admin1= doc.Descendants("Admin");
foreach (XElement item in admin1)
{
if (txtUserName.Text == item.Element("id").Value && txtPWD.Text == item.Element("pass").Value)
{
admin.Show();
}
}
}
}
Besides, you need to use using System.Xml.Linq;;
The next is the tested xml.
<?xml version="1.0" encoding="utf-8"?>
<Loginlist>
<Admin>
<FirstName>Administrator</FirstName>
<LastName>A</LastName>
<EmailAddress>admin#ge.com</EmailAddress>
<PhoneNumber>1</PhoneNumber>
<id>admin</id>
<pass>admin</pass>
</Admin>
<User>
<FirstName>Ab</FirstName>
<LastName>Mo</LastName>
<EmailAddress>ab#ge.com</EmailAddress>
<PhoneNumber>1</PhoneNumber>
<id>user</id>
<pass>user</pass>
</User>
</Loginlist>
The tested result:

Couple of points -
Your code is not making differentation between the admin and the user validation - For istance - once the user code is validated as mentioned below -
if (username.Equals(txtusername.Text) && pwd.Equals(txtpwd.Text))
{
purchase fpur = new purchase();
fpur.Show();
}
The admin code is still running in the background and as the XML wont validate the admin
at that time it is giving error as you mentioned -
When you pass admin related XML it will only validate the admin code as it is at the end of code so admin related code is working fine.
If you want validate both then you may have differentiate them whether the input is
admin or user in that way your conditional statements will run accordingly. Aso I
removed couple of duplicate code and the code below is one way of doing it and place this code in your btnlogin_Click event code-
XmlDocument doc = new XmlDocument();
string file = #"../../../data/UsersDatabase.Xml";
doc.Load(file);
bool isUser = false;
bool isAdmin = false;
//User
foreach (XmlNode node in doc.SelectNodes("//User"))
{
isUser = true;
username = node.SelectSingleNode("id").InnerText;
pwd = node.SelectSingleNode("pass").InnerText;
}
//Admin
foreach (XmlNode node in doc.SelectNodes("//Admin"))
{
isAdmin = true;
username = node.SelectSingleNode("id").InnerText;
pwd = node.SelectSingleNode("pass").InnerText;
}
if (username.Equals(txtusername.Text) && pwd.Equals(txtpwd.Text))
{
if (isAdmin)
{
Adminpanel fadmin = new Adminpanel();
fadmin.Show();
}
else if(isUser)
{
purchase fpur = new purchase();
fpur.Show();
}
}
else
{
MessageBox.Show("Sorry, username and password are incorrect",
"Login Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

Related

Why doesn't my validation for checking if an array (values from text file) contains a specific string

So I have used this way of validating an array with values from a text file in another class which works flawlessly. I tried a bunch of different ways but it just keeps on writing the data to the text file even though a username already exists. Every solution I have researched does not work. It's as if the program just skips the if condition containing the username exists. I really do not understand why it does not work. I have tried foreach loops and nothing. I have tried a bunch of different built in array functions with linq and just straight up default functions. The code for the working class is here:
string username = textBox1.Text;
string password = textBox2.Text;
UserCredentials myUserLogin = new UserCredentials();
FileHandler myFileHandler = new FileHandler();
DataHandler myDataHandler = new DataHandler();
myUserLogin.UserDetails(username, password);
string[] lines = myFileHandler.ReadFromFile();
Login_Form form1 = new Login_Form();
Register_Form form3 = new Register_Form();
Main_Form form2 = new Main_Form();
bool usernameExists = Array.Exists(lines, element => element == myUserLogin.Username);
bool passwordExists = Array.Exists(lines, element => element == myUserLogin.Password);
if (usernameExists && passwordExists) // this works
{
form2.Show();
}
else if (!usernameExists || !passwordExists)
{
if (MessageBox.Show("User not found or password incorrect. Register new user?", "Error", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
form3.Show();
}
else{}
}
```
string username = txtRegisterUsername.Text;
string password = txtRegisterPassword.Text;
DataHandler dataHandler = new DataHandler();
FileHandler FileHandler = new FileHandler();
UserCredentials myUserRegister = new UserCredentials();
myUserRegister.UserDetails(username, password);
string[] lines = FileHandler.ReadFromFile();
bool usernameExists = Array.Exists(lines, element => element == myUserRegister.Username);
if (usernameExists) //this does not work
{
MessageBox.Show("Username already exists, please enter another one");
}
else if (!usernameExists)
{
string userDetailString = myUserRegister.Username + ' ' + myUserRegister.Password;
List<string> userDetailList = new List<string>();
userDetailList.Add(userDetailString);
FileHandler.WriteToFile(userDetailList.ToArray());
Register_Form.ActiveForm.Close();
}
}

foreach isn't reading well through .descendants and goes to else statement before if

I'm still learning in terms of C#
I'm currently working on a filter system and have an if statement list that prevents user to from performing any actions. Now is it that whenever the user submits an ID, my foreach is supposed to run through the list of already submitted ID's checking whether they exist already or not.
The bug is that when the user submits an already existing ID, it will not see the existing ID in the first run so it will create and fill in a node, but in the second run it does so it sends an error message & breaks the session.
My code:
private async void btnAddId_Click(object sender, RoutedEventArgs e)
{
XmlDocument Xdoc = new XmlDocument();
Xdoc.Load(xmldoc);
XmlNode NodeEl = Xdoc.SelectSingleNode("root/filter/filter_item");
XmlNode NodeList = Xdoc.SelectSingleNode("root/filter");
var root = XDocument.Load(xmldoc).Root;
var filter = root.Element("filter");
int parsedValue;
foreach (var f in filter.Descendants())
{
if (f.Value == tbAddId.Text)
{
MessageBox.Show("Value already exists in the orderlist!");
}
else if (!int.TryParse(tbAddId.Text, out parsedValue))
{
MessageBox.Show("Input isn't numeric!");
}
else if (tbAddId.Text == "")
{
MessageBox.Show("No value was given!");
}
else if (tbAddId.Text == "Add ID")
{
MessageBox.Show("No value was given!");
}
else if (NodeList.InnerText == "")
{
NodeEl.InnerText = tbAddId.Text;
tbAddId.Text = "Add ID";
tbAddId.Foreground = Brushes.Gray;
await api.config_Load();
await api.Page_Load();
}
else
{
XmlNode filterItem = Xdoc.CreateElement("filter_item");
NodeList.AppendChild(filterItem);
filterItem.InnerText = tbAddId.Text;
}
tbOrderDisplay.Text += f.Value + " ";
}
Xdoc.Save(xmldoc);
}
XML content
<?xml version="1.0"?>
<root>
<bol_client_id></bol_client_id>
<!--- this is the client id-->
<bol_client_secret></bol_client_secret>
<!-- this is the client secret -->
<customer_id></customer_id>
<company_phone></company_phone>
<auth_token_url></auth_token_url>
<bol_orders_url></bol_orders_url>
<debug_mode>true</debug_mode>
<filter>
<filter_item>1172828940</filter_item>
<filter_item>1173700637</filter_item>
</filter>
</root>
Check whether value exists before you try to insert it:
private async void btnAddId_Click(object sender, RoutedEventArgs e)
{
XmlDocument Xdoc = new XmlDocument();
Xdoc.Load(xmldoc);
XmlNode NodeEl = Xdoc.SelectSingleNode("root/filter/filter_item");
XmlNode NodeList = Xdoc.SelectSingleNode("root/filter");
var root = XDocument.Load(xmldoc).Root;
var filter = root.Element("filter");
int parsedValue;
//1. Check for duplicates
foreach (var f in filter.Descendants())
{
if (f.Value == tbAddId.Text)
{
MessageBox.Show("Value already exists in the orderlist!");
tbOrderDisplay.Text += f.Value + " ";
return;
}
}
//2. Validate and insert
if (!int.TryParse(tbAddId.Text, out parsedValue))
{
MessageBox.Show("Input isn't numeric!");
}
else if (tbAddId.Text == "")
{
MessageBox.Show("No value was given!");
}
else if (tbAddId.Text == "Add ID")
{
MessageBox.Show("No value was given!");
}
else if (NodeList.InnerText == "")
{
NodeEl.InnerText = tbAddId.Text;
tbAddId.Text = "Add ID";
tbAddId.Foreground = Brushes.Gray;
await api.config_Load();
await api.Page_Load();
}
else
{
XmlNode filterItem = Xdoc.CreateElement("filter_item");
NodeList.AppendChild(filterItem);
filterItem.InnerText = tbAddId.Text;
}
Xdoc.Save(xmldoc);
}

Log in through active directory

I want to create LogIn button through Active Directory.
So i have an idea to take Name logged user(Windows) from his Domain:
string Name = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
and then take Group for Login above:
string Group = System.Security.Principal.WindowsIdentity.GetCurrent().Groups.ToString(); // <---I think this is wrong ?
string allowedGroup = "Admins";
then something like:
if(Name == string.Empty)
{
MessageBox.Show("Your Name in domain doesn't exist");
}
if(Group.ToString() != allowedGroup)
{
MessageBox.Show("You don't have permissions to log in");
}
else
{
MessageBox.Show("Hello");
}
I think my 'getting group' is wrong. How can I do it? I don't know how to exactly search for one or two groups where User is assigned.
What about when user is assigned to many Groups?
Here is the point to use windows identity to authorize login.
1) Get the windows identity of user.
2) Use Windows identity object to get the other information like name and group.
use group name to validate user request.
Hope this will help you. Please write in comment in you have any questions.
System.Security.Principal.WindowsIdentity WI = System.Security.Principal.WindowsIdentity.GetCurrent();
string sUserName = WI.Name;
bool bAuthorized = false;
string allowedGroup = "Admins";
IdentityReferenceCollection irc = WI.Groups;
foreach (IdentityReference ir in irc)
{
if(ir.Translate(typeof(NTAccount)).Value == allowedGroup)
{
bAuthorized = true;
break;
}
}
if(string.IsNullOrEmpty(sUserName))
{
MessageBox.Show("Your Name in domain doesn't exist");
}
if(bAuthorized == false)
{
MessageBox.Show("You don't have permissions to log in");
}
else
{
MessageBox.Show("Hello");
}
Ok, i got this. Thanks for Pankaj.
System.Security.Principal.WindowsIdentity WI = System.Security.Principal.WindowsIdentity.GetCurrent();
string sUserName = WI.Name;
bool bAuthorized = false;
string allowedGroup = "Admins";
IdentityReferenceCollection irc = WI.Groups;
foreach (IdentityReference ir in irc)
{
NTAccount accInfo = (NTAccount)ir.Translate(typeof(NTAccount));
if (accInfo.Value == allowedGroup)
{
bAuthorized = true;
break;
}
}
if(string.IsNullOrEmpty(sUserName))
{
MessageBox.Show("Your Name in domain doesn't exist");
}
if(bAuthorized == false)
{
MessageBox.Show("You don't have permissions to log in");
}
else
{
MessageBox.Show("Hello");
}

Application returns error in autofill function on textbox_Leave(); using c#

In my application I store customers of a company. The user will be able to add customer number, name, address etc. These informations are stored in an xml file. And on the first tab of tabControl the user can type in the customer number in a textbox and then it autofills the surname and forename. And if the customer number is not available it appears a message box.
Well that sounds okay. But I got an issue with Visual Studio. I got this code:
private void txtKNrNew_Leave(object sender, EventArgs e)
{
XDocument xdoc = XDocument.Load(path + "\\save.xml");
int CustNos;
if (Int32.TryParse(txtKNrNew.Text, out CustNos))
{
var xmlNodeExist = "Buchhaltung/Customers/CustNo";
var existingCustNo = xdoc.XPathSelectElements(xmlNodeExist).FirstOrDefault(x => (int)x == CustNos);
if (existingCustNo == null)
{
MessageBox.Show("Diese Kundennummer ist nicht vorhanden!", "Kundennummer nicht vorhanden", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path + "\\save.xml");
var CustNoExist = String.Format("//Customers[CustNo/text() = {0}]/", CustNos);
var SurnameNode = xmlDoc.SelectNodes(CustNoExist + "Surname");
var ForenameNode = xmlDoc.SelectNodes(CustNoExist + "Forename");
string surname = SurnameNode[0].InnerText;
string forename = ForenameNode[0].InnerText;
if (CustNoExist != null)
{
txtSurnameNew.Text = surname;
txtForenameNew.Text = forename;
}
else
{
MessageBox.Show("aaaaaaaaaaa");
}
}
}
If I type in a customer number which does not exist it appears a messagebox to say that this customer number is not defined. But then Visual Studio interrupt the application and return an error:
Object reference not set to an instance of an object
If someone could give me a hint why this happen I'd be very pleased.
Like #adrianbanks said in the comments, you need to return, exit, stop processing, etc. after you find that the customer number does not exist.
To do that you return out of the method like so:
if (existingCustNo == null)
{
MessageBox.Show("Diese Kundennummer ist nicht vorhanden!", "Kundennummer nicht vorhanden", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}

How to validate password when TextMode="Password"

I'm building a web application using the default master template in VS2010 - very new to doing this. I'm also using the Login.aspx page, but instead of using the built in user validation, my user info is in a database table. So Following instructions I found, I'm doing something wery similar to this:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
Boolean bauthenticated = false;
bauthenticated = isValidUser(Login1.UserName, Login1.Password);
if (bauthenticated)
{
e.Authenticated = true;
}
else
{
e.Authenticated = false;
}
}
The problem is that I put the method isValidUser in a .dll so it could be used elsewhere, and it is not receiving the password because the default behaivor is to blank it out. I even tried to set a string variable to Login1.Password, and pass the variable without success. I understand why this is happening, but can't find any info as to how to do this correctly. Do I need to put the user name and password into an object and pass that to my class constructor? I really don't want to connect to my database from every Login.aspx page I create to avoid sending the password over http.
Try to use the following code.
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
dtUserDetails = new DataTable();
if (UserRepositoryBL.ValidateUser(LoginUser.UserName.Trim(), LoginUser.Password.Trim(), out dtUserDetails))
{
AuthUser au = new AuthUser();
if (dtUserDetails.Rows.Count > 0)
{
DataRow DR = dtUserDetails.Rows[0];
au.UserID = Convert.ToInt32(DR["UserID"].ToString());
au.UserNo = DR["UserNo"].ToString();
au.UserName = DR["UserName"].ToString();
au.Password = DR["Password"].ToString();
}
string userData = au.ToString();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Version number
LoginUser.UserName.Trim(), // Username
DateTime.Now, // Issue date
DateTime.Now.AddMinutes(60), // Expiration date
false, // Persistent?
userData // User data
);
string eticket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie
(FormsAuthentication.FormsCookieName, eticket);
Response.Cookies.Add(cookie);
BasePage.ActivityLog("User Login", LoginUser.UserName.Trim(), true, Request.RawUrl);
string url = FormsAuthentication.GetRedirectUrl(LoginUser.UserName, false);
Response.Redirect(url);
// FormsAuthentication.RedirectFromLoginPage(LoginUser.UserName, false);
}
else
{
LoginUser.FailureText = "Your login attempt was not successful. Please try again.";
}
}
catch (Exception ex)
{
throw ex;
}
}
dtUserDetails is a out parameter which contains the user details like password,username,etc.. on successful login.datatable returns empty if invalid login.with in userData string all those information will be available.then u can retrieve those from any page using User Authenticated Ticket

Categories

Resources