Logo

Login Dialog Using and XML File

 

Introduction

The credentials used to authenticate users who need access to a file, a database or an application are usually stored in a list. These credentials are usually a combination of a username and a password. Just like any traditional file, an XML file can be used to store the login credentials. Normally, the XML part is only as flexible as a normal list can be. The advantage that an XML file may offer over a text or binary file is that XML provides a fairly easy way to navigate the list looking for a username or a combination of a username and a password.

 

Using an XML File

To store credentials in an XML file, your first decision may have to do with the structure of the file. You can store the credentials in separate tags of an parent element. For example, you can create an element that would be used for each combination of a username and a password. Here is an example:

<?xml version="1.0" encoding="utf-8">
<logininfo>
    <crendential>
        <username>johnsd</username>
        <password>73DD234j5h</password>
    <crendential>
    <crendential>
        <username>walterg</username>
        <password>2$34Hf37</password>
    <crendential>
</logininfo>

Another solution, which we will use here because it is a little easier (in our opinion of course) consists of creating the credentials as attributes of a tag. This appears to make it easy during validation since each element is considered at a time. Once an element is reached, we can consider its the attributes of its tag as a unit and check the combination.

Practical Learning: Login Authentication With XML

  1. If you want to follow, create a Windows Application named Authenticator1
  2. To add another form, on the main menu, click Project . Add New Item...
  3. In the Templates section, click Windows Form
  4. In the Name box, type MainForm and press Enter
  5. Add a new XML file named credentials.xml and fill it as follows:
     
    <?xml version="1.0" encoding="utf-8"?>
    <logininfo>
      <credential username="pickettw" password="Patrice" />
      <credential username="reddingo" password="Collage" />
      <credential username="carterc" password="drapery" />
      <credential username="brownj" password="musical" />
    </logininfo>
  6. Display the first form and design the form as follows:
     
    Control Name Text Additional Properties
    Label   Username:  
    TextBox txtUsername    
    Label   Password:  
    TextBox txtPassword   PasswordChar: *
    Button btnOK OK  
    Button btnClose Cancel  
    Button btnNewAccount Create New Account  
    Form   Login Authentication FormBorderStyle: FixedDialog
    MinimizeBox: False
    MaximizeBox: False
    ShowInTaskbar: False
    StartPosition: CenterScreen
    AcceptButton: btnOK
    CancelButton: btnClose
  7. Add another form and set its name to NewAccount
  8. Design the form as follows:
     
    Control Name Text Additional Properties
    Label   Username:  
    TextBox txtUsername    
    Label   Password:  
    TextBox txtPassword   PasswordChar: *
    Label   Confirm Password:  
    TextBox txtConfirmPassword   PasswordChar: *
    Button btnOK OK  
    Button btnClose Cancel  
    Form   New Account Creation FormBorderStyle: FixedDialog
    MinimizeBox: False
    MaximizeBox: False
    ShowInTaskbar: False
    StartPosition: CenterParent
  9. Double-click the Cancel button and implement its event as follows:
     
    private: System.Void btnClose_Click(System.Object   sender, System.EventArgs   e)
    	{
    		 Close();
    	 }
  10. Scroll to the top of the file and declare two public string variables named Username and Password:
     
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.Container components = null;
    public string Username;
    public string Password;
    
  11. Double-click the OK button and implement its event as follows:
     
    private: System.Void btnOK_Click(System.Object   sender, System.EventArgs   e)
    	 {
    		 Username = this.txtUsername.Text;
    		 Password = this.txtPassword.Text;
    		 String ConfPass = this.txtConfirmPassword.Text;
    
    		 if( Username.Equals("") == true )
    		 {
     MessageBox.Show("Invalid Username: We don't accept an empty username!");
    			 this.txtUsername.Focus();
    			 return;
    		 }
    		 if( Password.Equals("") == true )
    		 {
     MessageBox.Show("Invalid Password: We don't accept a blank password!");
    			 this.txtPassword.Focus();
    			 return;
    		 }
    		 if( String.Compare(Password, ConfPass) != 0 )
    		 {
    	 MessageBox.Show("The passwords you provided are not the same!");
    			 this.txtPassword.Focus();
    			 return;
    		 }
    
    		 this.DialogResult = DialogResult.OK;
    		 Close();
    	}
  12. Display the first form
  13. Double-click the Create New Account button
  14. Return to the form and double-click the OK button
  15. Return to the form and double-click the Cancel button
  16. Implement the events as follows:
     
    private void btnNewAccount_Click(object sender, System.EventArgs e)
    		{
    			MainForm Acnt = new MainForm();
    			String Username = null, Password = null;
    			String ExistingUsername;
    			bool UniqueUsername = true;
    
    			if( Acnt.ShowDialog() == DialogResult.OK )
    			{
    				Username = Acnt.Username;
    				Password = Acnt.Password;
    				 
    				XmlTextReader xtr = new XmlTextReader("credentials.xml");
    
    				while(xtr.Read() )
    				{
    					switch(xtr.NodeType)
    					{
    						case XmlNodeType.Element:
    							ExistingUsername = xtr.GetAttribute("username");
    
    							if( Username.Equals(ExistingUsername) )
    								UniqueUsername = false;
    
    							break;
    					}
    				}
    			
    				xtr.Close();
    				 
    				if( UniqueUsername == true )
    				{
    					// Declare an XmlDocument that will be used to add a new item
    					XmlDocument XmlDoc = new XmlDocument();
    
    					try 
    					{
    						// Get the XML file and load it in the XmlDocument variable
    						XmlDoc.Load("credentials.xml");
    
    						// Create the new element
    						XmlElement Elm = XmlDoc.CreateElement("credential");
    						// Create its attributes
    						Elm.SetAttribute("username", Username);
    						Elm.SetAttribute("password", Password);
    		
    						// Add the new element to the file...
    						XmlDoc.DocumentElement.AppendChild(Elm);
    						// ... and save the document
    						XmlDoc.Save("credentials.xml");
    
    						MessageBox.Show("The account has been created!" +
    							"\nYou can use your new account to login!");
    					}
    					catch(Exception ex)
    					{
    						MessageBox.Show(ex.Message);
    					}
    				}
    				else
    					MessageBox.Show("The username you provided is already being used!!!");
    			}
    		}
    
    		private void btnOK_Click(object sender, System.EventArgs e)
    		{
    			String strUsername = this.txtUsername.Text;
    			String strPassword = this.txtPassword.Text;
    			String Username, Password;
    
    			bool GoodLogin = false;
    
    			if( strUsername.Equals("") )
    			{
    				MessageBox.Show("Invalid or empty username." +
    					"\nPlease provide a username");
    				this.txtUsername.Focus();
    				return;
    			}
    			if( strPassword.Equals("") )
    			{
    				MessageBox.Show("Invalid or empty password." +
    					"\nPlease type a valid password");
    				this.txtPassword.Focus();
    				return;
    			}
    
    			XmlTextReader xtr = new XmlTextReader("credentials.xml");
    
    			while(xtr.Read() )
    			{
    				switch(xtr.NodeType)
    				{
    					case XmlNodeType.Element:
    						Username = xtr.GetAttribute("username");
    						Password = xtr.GetAttribute("password");
    
    						if( strUsername.Equals(Username) )
    						{
    							if( strPassword.Equals(Password) )
    								GoodLogin = true;
    							else
    								GoodLogin = false;
    						}
    						break;
    				}
    			}
    			
    			if( GoodLogin == true )
    			{
    				MainForm FM = new MainForm();
    				this.Hide();
    				FM.ShowDialog();
    
    				Close();
    			}
    			else
    				MessageBox.Show("Invalid Credential");
    		}
    
    		private void btnCancel_Click(object sender, System.EventArgs e)
    		{
    			Close();
    		}
  17. Test the application

 


Home Copyright © 2004-2010 FunctionX, Inc.