hello all,
i am creating an online aptitude testing system in C# using ASP.NET. for this what i want to know is that when a registered user enters his login id and password, it should be compared with those already present in the database and it matches with tht in the database, the user shud be logged in and itf it doesnt the user shud receive an error message.. how can i do it??
anyone who can help me..
many thanks..
ariez88 -4 Light Poster
sknake 1,622 Senior Poster Featured Poster
This is the C#.NET forum for windows form applications not ASP.NET, that is another forum: http://www.daniweb.com/forums/forum18.html
Here is some code I mocked up for a form application but the concepts are the same in ASP.NET except for calling the textbox's focus. I believe there is a LoginControl template page or class in ASP.NET for handling user logins and session but I don't use them. I like to re-invent the wheel my way ;)
Here is how to do it in winforms:
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
namespace daniweb
{
public partial class frmLogin : Form
{
/// <summary>
/// Key for the crypto provider
/// </summary>
private static readonly byte[] _key = { 0xA1, 0xF1, 0xA6, 0xBB, 0xA2, 0x5A, 0x37, 0x6F, 0x81, 0x2E, 0x17, 0x41, 0x72, 0x2C, 0x43, 0x27 };
/// <summary>
/// Initialization vector for the crypto provider
/// </summary>
private static readonly byte[] _initVector = { 0xE1, 0xF1, 0xA6, 0xBB, 0xA9, 0x5B, 0x31, 0x2F, 0x81, 0x2E, 0x17, 0x4C, 0xA2, 0x81, 0x53, 0x61 };
public frmLogin()
{
InitializeComponent();
}
#if (DEBUG) //Only compile this method for local debugging.
/// <summary>
/// Decrypt a string
/// </summary>
/// <param name="Value"></param>
/// <returns></returns>
private static string Decrypt(string Value)
{
SymmetricAlgorithm mCSP;
ICryptoTransform ct = null;
MemoryStream ms = null;
CryptoStream cs = null;
byte[] byt;
byte[] _result;
mCSP = new RijndaelManaged();
try
{
mCSP.Key = _key;
mCSP.IV = _initVector;
ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
byt = Convert.FromBase64String(Value);
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
_result = ms.ToArray();
}
catch
{
_result = null;
}
finally
{
if (ct != null)
ct.Dispose();
if (ms != null)
ms.Dispose();
if (cs != null)
cs.Dispose();
}
return ASCIIEncoding.UTF8.GetString(_result);
}
#endif
/// <summary>
/// Encrypt a string
/// </summary>
/// <param name="Password"></param>
/// <returns></returns>
private static string Encrypt(string Password)
{
if (string.IsNullOrEmpty(Password))
return string.Empty;
byte[] Value = Encoding.UTF8.GetBytes(Password);
SymmetricAlgorithm mCSP = new RijndaelManaged();
mCSP.Key = _key;
mCSP.IV = _initVector;
using (ICryptoTransform ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV))
{
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write))
{
cs.Write(Value, 0, Value.Length);
cs.FlushFinalBlock();
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
}
}
}
/// <summary>
/// Looks up the users password crypto string in the database
/// </summary>
/// <param name="Username"></param>
/// <returns></returns>
private static DataTable LookupUser(string Username)
{
/*
* The reason I return a datatable here is so you can also bring back the user's full
* name, email address, security rights in the application, etc. I have a "User" class
* where I defined meta information for users.
*/
const string connStr = "Data Source=apex2006sql;Initial Catalog=Leather;Integrated Security=True;";
const string query = "Select Password From UserTable (NOLOCK) Where UserName = @UserName";
DataTable result = new DataTable();
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = Username;
using (SqlDataReader dr = cmd.ExecuteReader())
{
result.Load(dr);
}
}
}
return result;
}
/// <summary>
/// Obviously the .Focus() code doesn't apply to ASP.NET
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonLogin_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxUsername.Text))
{
//Focus box before showing a message
textBoxUsername.Focus();
MessageBox.Show("Enter your username", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
//Focus again afterwards, sometimes people double click message boxes and select another control accidentally
textBoxUsername.Focus();
return;
}
else if (string.IsNullOrEmpty(textBoxPassword.Text))
{
textBoxPassword.Focus();
MessageBox.Show("Enter your password", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
textBoxPassword.Focus();
return;
}
//OK they enter a user and pass, lets see if they can authenticate
using (DataTable dt = LookupUser(textBoxUsername.Text))
{
if (dt.Rows.Count == 0)
{
textBoxUsername.Focus();
MessageBox.Show("Invalid username.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
textBoxUsername.Focus();
return;
}
else
{
//Always compare the resulting crypto string or hash value, never the decrypted value
//By doing that you never make a call to Decrypt() and the application is harder to
//reverse engineer. I included the Decrypt() method here for informational purposes
//only. I do not recommend shipping an assembly with Decrypt() methods.
string dbPassword = Convert.ToString(dt.Rows[0]["Password"]);
string appPassword = Encrypt(textBoxPassword.Text); //we store the password as encrypted in the DB
if (string.Compare(dbPassword, appPassword) == 0)
{
//Logged in
}
else
{
//You may want to use the same error message so they can't tell which field they got wrong
textBoxPassword.Focus();
MessageBox.Show("Invalid Password", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
textBoxPassword.Focus();
return;
}
}
}
}
}
}
ariez88 -4 Light Poster
thankyou very much for ur reply.. i think i sud have mentioned tht i m new to programming.. ur program, i guess is of higher level than i m at now... umm i did understand the bottom half portion but cudnt really get the upper half portion of the code..
here is the code tht i hv written for comparison of textbox's value with the database's value.. but m unable to run it and the error i m getting is of "unassigned local variable "var" "..
protected void loginButton_Click1(object sender, EventArgs e)
{
DataSet temp = new DataSet();
temp = conn.retrieve("select * from candidate_info");
int a = temp.Tables[0].Rows.Count;
object[] obj;
for (int i = 0; i < a; )
{
obj = temp.Tables[0].Rows[i].ItemArray;
{
if (this.idTextBox.Text != obj[0].ToString() && this.passTextBox.Text != obj[1].ToString())
i++;
}
Response.Write("<script>alert('Logged In')</script>");
}
Response.Write("<script>alert('ERROR')</script>");
}
sknake 1,622 Senior Poster Featured Poster
Can you upload your project so I have a chance to review it and make code modifications?
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.