Link to home
Start Free TrialLog in
Avatar of introlux
introluxFlag for United Kingdom of Great Britain and Northern Ireland

asked on

How to check if username exits then errorr

In alot of cases, I am creating username or project id numbers. I would like to check if project id exists then display error in label.

I have added registration code in my snippet.

Summary Problem:

If username exists, then display error message, user already exists
else add user.

I am using MS Access to store data as it is not a major big project where i need mysql etc...

Thanks,

introlux
=======================================================================
Behind Code (CS)
=======================================================================
 
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Security.Cryptography;
 
public partial class Registration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    void addUser()
    {
        string sqlCmd;
        sqlCmd = "INSERT INTO Users (Username, Salt, Pass, Email) VALUES (@Username, @Salt, @Pass, @Email)";
        OleDbConnection objConn = new OleDbConnection ("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("Data/ProCom.mdb"));
        OleDbCommand objCmd = new OleDbCommand(sqlCmd, objConn);
        RNGCryptoServiceProvider objRng = new RNGCryptoServiceProvider();
        int intSaltSize = 16;
 
        objCmd.Parameters.Add("@Username", txtUsername.Text);
        byte[] objByte = new byte[intSaltSize];
        objRng.GetBytes(objByte);
        string strSalt = Convert.ToBase64String(objByte);
        objCmd.Parameters.Add("@Salt", strSalt);
        objCmd.Parameters.Add("@Pass", FormsAuthentication.HashPasswordForStoringInConfigFile(strSalt + txtPassword.Text, "SHA1"));
        objCmd.Parameters.Add("@Email", txtEmail.Text);
 
        objConn.Open();
        objCmd.ExecuteNonQuery();
        objConn.Close();
    }
    protected void AddCredentials_Click(object sender, EventArgs e)
    {
        addUser();
        Response.Redirect("default.aspx");
    }
}
 
=====================================================================
ASPX
=====================================================================
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Registration.aspx.cs" Inherits="Registration" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Web.Security" %>
<%@ Import Namespace="System.Security.Cryptography" %>
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>PCS Registration</title>
<script runat="server" language="C#">
</script>
</head>
<body>
    <a href="javascript:history.back(-1)">Go Back</a><br />
<div style="margin-left:auto; margin-right:auto; width:30%;">
<table cellpadding="5" cellspacing="0" border="0" width="100%">
<tr>
<td>
<form id="Form1" runat="server">
    <h2 style="text-align: center">
        PCS Registration</h2>
    <br />
    <br />
Username:<br /> 
<asp:TextBox id="txtUsername" runat="server" /><br />
Password:<br /> 
<asp:TextBox id="txtPassword" runat="server" TextMode="Password" /><br />
Email:<br /> 
<asp:TextBox id="txtEmail" runat="server" /><br /><br />
<asp:Button id="btnReg" runat="server" Text="Register" onClick="AddCredentials_Click" />
</form>
</td>
</tr>
</table>
</div>
</body>
</html>

Open in new window

Avatar of stevbe
stevbe

There are two approaches I can think of ...

1. If you create a unique index on the Username field in your Access database I think your objCmd.ExecuteNonQuery(); will throw an error so I would wrap that in a try / catch so you can handle as appropriate.

2. You could create a *lookup* query in the Access app that only returns an ID (or some other non-sensitive field) based on passing in the Username as a parameter. If you do get a return record then you know it already exist and then you can messge as appropriate.

Steve
Avatar of introlux

ASKER

I have seen some sample code. I have started programming and have come up with the following so far:

But im getting an error:

Compiler Error Message: CS0117: 'System.Data.OleDb.OleDbConnection' does not contain a definition for 'ExecuteReader'

Source Error:

 

Line 49:         bool bUserExists = false;
Line 50:         objConn.Open();
Line 51:         aReader = objConn.ExecuteReader();
Line 52:         try
Line 53:         {
 
Any idea guys??

Thanks,

introlux
    protected bool Check(string username)
    {
        string sqlCmd;
        sqlCmd = "SELECT tblProCom Username=@Username WHERE Username=@Username";
        OleDbDataReader aReader;
        OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("Data/ProCom.mdb"));
        OleDbCommand objCmd = new OleDbCommand(sqlCmd, objConn);
 
        bool bUserExists = false;
        objConn.Open();
        aReader = objConn.ExecuteReader();
 
        try
        {
            aReader.Read();
            if (aReader.GetInt32(0) != 0)
            {
                bUserExists = true;
            }
        }
        catch (Exception e)
        {
            Console.Write(e);
        }
        finally
        {
            aReader.Close();
            objConn.Close();
        }
    }

Open in new window

I have now come up with the following code:

Which seems to be ok but is not working. I get the following error:

Exception Details: System.Data.OleDb.OleDbException: No value given for one or more required parameters.

Source Error:


Line 59:         bool bUserExists = false;
Line 60:         objConn.Open();
Line 61:         aReader = objCmd.ExecuteReader();
Line 62:
Line 63:         try
 
Any idea??
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Security.Cryptography;
 
public partial class Registration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    void addUser()
    {
        string sqlCmd;
 
        if (Check(txtUsername.Text))
        {
            lblError.Text = "username already exists";
        }
        else
        {
 
            sqlCmd = "INSERT INTO Users (Username, Salt, Pass, Email) VALUES (@Username, @Salt, @Pass, @Email)";
            OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("Data/ProCom.mdb"));
            OleDbCommand objCmd = new OleDbCommand(sqlCmd, objConn);
            RNGCryptoServiceProvider objRng = new RNGCryptoServiceProvider();
            int intSaltSize = 16;
 
            objCmd.Parameters.Add("@Username", txtUsername.Text);
            byte[] objByte = new byte[intSaltSize];
            objRng.GetBytes(objByte);
            string strSalt = Convert.ToBase64String(objByte);
            objCmd.Parameters.Add("@Salt", strSalt);
            objCmd.Parameters.Add("@Pass", FormsAuthentication.HashPasswordForStoringInConfigFile(strSalt + txtPassword.Text, "SHA1"));
            objCmd.Parameters.Add("@Email", txtEmail.Text);
 
            objConn.Open();
            objCmd.ExecuteNonQuery();
            objConn.Close();
        }
    }
 
    protected bool Check(string username)
    {
        string sqlCmd;
        sqlCmd = "SELECT count(*) FROM tblProCom WHERE Username=" + txtUsername.Text;
        OleDbDataReader aReader;
        OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("Data/ProCom.mdb"));
        OleDbCommand objCmd = new OleDbCommand(sqlCmd, objConn);
 
        bool bUserExists = false;
        objConn.Open();
        aReader = objCmd.ExecuteReader();
 
        try
        {
            aReader.Read();
            if (aReader.GetInt32(0) != 0)
            {
                bUserExists = true;
            }
        }
        catch (Exception e)
        {
            Console.Write(e);
        }
        finally
        {
            aReader.Close();
            objConn.Close();
        }
        return bUserExists;
    }
 
    protected void AddCredentials_Click(object sender, EventArgs e)
    {
        addUser();
        Response.Redirect("default.aspx");
    }
}

Open in new window

?????????
If you want to check of a user exists before trying to create a new user then you just need to do something like this.

             //select information based on username
            OdbcConnection conn = new OdbcConnection(connString);
            OdbcCommand cmd = new OdbcCommand("SELECT  userName FROM tblName" +
                "WHERE userName = ?", conn);
            cmd.Parameters.Add("@userName", OdbcType.VarChar, 255).Value = username;
 
            //create temp user information and reader
            MembershipUser usr = null;
            OdbcDataReader rdr = null;
 
            //get information
            try
            {
                conn.Open();
                rdr = cmd.ExecuteReader();
 
                //see if user retruned
                if (rdr.HasRows)
                {
                    //user already exists
                } 
                else
                {
                    //user doesn't exist so make an insert command 
                }
            }

Open in new window

I have just seen the code, does this need to be added in the AddUser button. I have attached my full back code.

So I will not need a function called check. Is that correct?
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Security.Cryptography;
 
public partial class Registration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    void addUser()
    {
        string sqlCmd;
 
        if (Check(txtUsername.Text))
        {
            lblError.Text = "username already exists";
        }
        else
        {
 
            sqlCmd = "INSERT INTO Users (Username, Salt, Pass, Email) VALUES (@Username, @Salt, @Pass, @Email)";
            OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("Data/ProCom.mdb"));
            OleDbCommand objCmd = new OleDbCommand(sqlCmd, objConn);
            RNGCryptoServiceProvider objRng = new RNGCryptoServiceProvider();
            int intSaltSize = 16;
 
            objCmd.Parameters.Add("@Username", txtUsername.Text);
            byte[] objByte = new byte[intSaltSize];
            objRng.GetBytes(objByte);
            string strSalt = Convert.ToBase64String(objByte);
            objCmd.Parameters.Add("@Salt", strSalt);
            objCmd.Parameters.Add("@Pass", FormsAuthentication.HashPasswordForStoringInConfigFile(strSalt + txtPassword.Text, "SHA1"));
            objCmd.Parameters.Add("@Email", txtEmail.Text);
 
            objConn.Open();
            objCmd.ExecuteNonQuery();
            objConn.Close();
        }
    }
 
    protected bool Check(string username)
    {
        string sqlCmd;
        sqlCmd = "SELECT count(*) FROM tblProCom WHERE Username=" + txtUsername.Text;
        OleDbDataReader aReader;
        OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("Data/ProCom.mdb"));
        OleDbCommand objCmd = new OleDbCommand(sqlCmd, objConn);
 
        bool bUserExists = false;
        objConn.Open();
        aReader = objCmd.ExecuteReader();
 
        try
        {
            aReader.Read();
            if (aReader.GetInt32(0) != 0)
            {
                bUserExists = true;
            }
        }
        catch (Exception e)
        {
            Console.Write(e);
        }
        finally
        {
            aReader.Close();
            objConn.Close();
        }
        return bUserExists;
    }
 
    protected void AddCredentials_Click(object sender, EventArgs e)
    {
        addUser();
        Response.Redirect("default.aspx");
    }
}

Open in new window

I have tried to follow your example but im leading to errors as its expecting a finally or catch. When I try insert these it still does not like it.
Try moving the conn open and the reader use under the try statement like so:

    protected bool Check(string username)
    {
        string sqlCmd;
        
        sqlCmd = "SELECT count(*) FROM tblProCom WHERE Username=" + txtUsername.Text;
        OleDbDataReader aReader;
        OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("Data/ProCom.mdb"));
        OleDbCommand objCmd = new OleDbCommand(sqlCmd, objConn);
 
        bool bUserExists = false;
 
        try
        {
            objConn.Open();
            aReader = objCmd.ExecuteReader();
            aReader.Read();
            if (aReader.GetInt32(0) != 0)
            {
                bUserExists = true;
            }
        }
        catch (OleDbException e)
        {
            Console.Write(e);
        }
        finally
        {
            aReader.Close();
            objConn.Close();
        }
        return bUserExists;
    }

Open in new window

this one might work was well

    protected bool Check(string username)
    {
        string sqlCmd;
        
        sqlCmd = "SELECT count(*) FROM tblProCom WHERE Username=" + txtUsername.Text;
        OleDbDataReader aReader;
        OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("Data/ProCom.mdb"));
        OleDbCommand objCmd = new OleDbCommand(sqlCmd, objConn);
 
        bool bUserExists = false;
 
        try
        {
            objConn.Open();
            aReader = objCmd.ExecuteReader();
            if (aReader.HasRows)
            {
                bUserExists = true;
            }
        }
        catch (OleDbException e)
        {
            Console.Write(e);
        }
        finally
        {
            aReader.Close();
            objConn.Close();
        }
        return bUserExists;
    }

Open in new window

Im getting the following error:

Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0165: Use of unassigned local variable 'aReader'
Source Error:
Line 75: finally
Line 76: {
Line 77: aReader.Close();
Line 78: objConn.Close();
Line 79: }
I just tried this one and it worked for me.

    public bool Check(string username)
    {
        string sqlCmd = "SELECT count(*) FROM tblProCom WHERE Username=" + txtUsername.Text;
        string connString = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("Data/ProCom.mdb");
 
        OleDbDataReader aReader = null;
        OleDbConnection objConn = new OleDbConnection(connString);
        OleDbCommand objCmd = new OleDbCommand(sqlCmd, objConn);
 
        bool bUserExists = false;
 
        try
        {
            objConn.Open();
            aReader = objCmd.ExecuteReader();
            if (aReader.HasRows)
                bUserExists = true;
        }
        catch (OleDbException e)
        {
            throw e;
        }
        finally
        {
            if (aReader != null) { aReader.Close(); }
            objConn.Close();
        }
        return bUserExists;
    }

Open in new window

I get this error now:

No value given for one or more required parameters.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: No value given for one or more required parameters.
Source Error:

Line 69: catch (OleDbException e)
Line 70: {
Line 71: throw e;
Line 72: }
Line 73: finally
Remove the Count(*) and just select the username column instead.
It compiles, but does not work. Still adds the same username

introlux
There might still be a problem with the sql command. Try something like this:


"SELECT count(*) FROM tblProCom WHERE Username = '" + txtUsername.Text + "'";

Open in new window

Again same problem. It compiles, but allows me to add the same username.
Any idea??
??????
"SELECT Username FROM tblProCom WHERE Username = '" + txtUsername.Text + "'";

Open in new window


"SELECT count(*) FROM tblProCom WHERE Username = '" + txtUsername.Text + "'";

Open in new window

Oh man what a day!

"SELECT Username FROM tblProCom WHERE Username = '" + txtUsername.Text + "'";

Open in new window

Tried the last one and still no luck!
Ok try this and see if it works.

    protected bool Check(string username)
    {
        string sqlCmd = "SELECT count(*) FROM tblProCom WHERE Username=" + username;
        OleDbDataReader aReader = null;
        OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("Data/ProCom.mdb"));
        OleDbCommand objCmd = new OleDbCommand(sqlCmd, objConn);
 
        bool bUserExists = false;
 
        try
        {
            objConn.Open();
            aReader = objCmd.ExecuteReader();
            if (aReader.Read())
            {
                bUserExists = true;
            }
        }
        catch (Exception e)
        {
            Console.Write(e);
        }
        finally
        {
            if (aReader != null) { aReader.Close(); };
            objConn.Close();
        }
        return bUserExists;
    }

Open in new window

does not work............
Email me a copy of the access database, empty preferably. mark@g33kco.com
I have sent you the access file
ASKER CERTIFIED SOLUTION
Avatar of trenduin
trenduin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That worked! I think the problem lied on this code:

    protected void AddCredentials_Click(object sender, EventArgs e)
    {
        addUser();
        //Response.Redirect("default.aspx");
    }

On the button click. Regardless user was taken to default.aspx web page. I have now put the response part in the end part of the adding function.

Thanks for your help!
Top Answer!