I am creating a program to allow users of different types to login in
using the three login options done in C#.
Usertype
Username
Password
The database connection string and the query are working. I have done the login and added data without the USERTYPE variable to check connection issues. However, I'm having a problem with this snippet of code:
private void button1_Click(object sender, EventArgs e)
{
string usernamedt, passworddt;
usernamedt = username.Text;
passworddt = password.Text;
try
{
string query = "SELECT * FROM log_data WHERE username = '" + username.Text.Trim() + "' AND password = '" + password.Text.Trim() + "' ";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlco);
DataTable dt = new DataTable();
sda.Fill(dt);
string usertype = user_type.SelectedItem.ToString();
if (dt.Rows.Count > 0)
{
// state rows in table
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["usertype"].ToString() == usertype)
{
MessageBox.Show("You are logged in as " + dt.Rows[i][2]);
if (user_type.SelectedIndex == 0)
{
customer customer1 = new customer();
customer1.Show();
this.Hide();
}
else if (user_type.SelectedIndex == 1)
{
Staff staff1 = new Staff();
staff1.Show();
this.Hide();
}
else if (user_type.SelectedIndex == 2)
{
Trainer trainer1 = new Trainer();
trainer1.Show();
this.Hide();
} // end nested if*/
} //end check for user type
}// end for loop
}// end row count
else
{
MessageBox.Show("The username or password is incorrect,Try Again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
} // end try block
catch
{
MessageBox.Show("Error ");
}
finally
{
sqlco.Close();
}
} // end button LOG IN CLICK
Related
I'm student and I have one project, to make a program and database for Coffee shop.
I have login window and it's connected with mysql database. You have only textbox for enter password and when you enter correct password(password is in database) you are logged on, and move to another form(main interface). Now I want to only display name of logged user and I don't know how to...
This is the code, I'm from Croatia so some of words are Croatian.
public void button_1_Click(object sender, EventArgs e)
{
string upit = "SELECT * FROM zaposlenik WHERE sifra_z = '" + textbox_prijava.Text+"'";
string manager = "SELECT * FROM manager WHERE sifra_m = '" + textbox_prijava.Text + "'";
MySqlDataAdapter sda = new MySqlDataAdapter(upit, connection);
DataTable tablica = new DataTable();
sda.Fill(tablica);
MySqlDataAdapter sda2 = new MySqlDataAdapter(manager, connection);
DataTable tablica2 = new DataTable();
sda2.Fill(tablica2);
if (tablica.Rows.Count >= 1 || tablica2.Rows.Count >= 1)
{
GlavnoSučelje x = new GlavnoSučelje();
x.Show();
this.Hide();
}
else if (textbox_prijava.Text == "")
{
MessageBox.Show("Niste upisali šifru!", "Greška", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Kriva šifra konobara!", "Greška", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
textbox_prijava.Clear();
This is what I would do.
Have a static class to save user details:
public class UserDetails
{
private static string _username;
public static string Username
{
get
{
return _username;
}
set
{
_username = value;
}
}
}
Here we are logging in and saving user details.
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
//Login Button
private void loginBtn(object sender, EventArgs e)
{
//MySQL connection to retrieve user details into a class on successful log in
using (var conn = new MySqlConnection(ConnectionString.ConnString))
{
conn.Open();
//Get count, username
using (var cmd = new MySqlCommand("select count(*), username from users where username = #username and password = MD5(#password)", conn))
{
cmd.Parameters.AddWithValue("#username", usernameTextBox.Text);
cmd.Parameters.AddWithValue("#password", passwordTextBox.Text);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
//Check whether user exists
if (dt.Rows[0][0].ToString() == "1")
{
//If the user exist - allow to log in
//Store the information from the query to UserDetails class to be used in other forms
UserDetails.Username = dt.Rows[0][1].ToString();
//Hide this form and open the main Dashboard Form
this.Hide();
var dashboard = new Dashboard();
dashboard.Closed += (s, args) => this.Close();
dashboard.Show();
}
//If failed login - show message
else
{
MessageBox.Show("Login failed", "Technical - Login Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
}
To use the username.. just simply use UserDetails.Username
I'm currently making a windows form login system and I've worked out how to set up a general everyone can see the main page system but for the admin i want it to open a new form (form3) which will contain customer orders.
i need it to open up from Login Button.Click just like form2 opens to show the store page for generalised users. i don't have a column in my table for user roles either.
I've tried if else statements and run into issues with bools not excepting strings etc.
using System;
using System.Data;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace Aliena_Store
{
public partial class Form1 : Form
{
//string ConnectionState = "";
public Form1()
{
InitializeComponent();
}
MySqlConnection connection = new MySqlConnection("server=localhost;user=root;database=Aliena_Store;port=3306;password=Blackie");
MySqlDataAdapter adapter;
DataTable table = new DataTable();
private void UsernameLogin_TextChanged(object sender, EventArgs e)
{
}
private void PasswordLogin_TextChanged(object sender, EventArgs e)
{
}
private void LoginButton_Click(object sender, EventArgs e)
{
adapter = new MySqlDataAdapter("SELECT `username`, `password` FROM `User_Details` WHERE `username` = '" + UsernameLogin.Text + "' AND `password` = '" + PasswordLogin.Text + "'", connection);
adapter.Fill(table);
var usernameSaved = UsernameLogin.Text;
var passwordSaved = PasswordLogin.Text;
Panel panel1 = new Panel();
if (table.Rows.Count <= 0)
{
panel1.Height = 0;
var result = MessageBox.Show("Username/Password Are Invalid or does not exist. Please sign up or retry your details");
}
else
{
panel1.Height = 0;
this.Hide();
if (table.Rows.Count >= 0)
{
Form nextForm;
var result = MessageBox.Show("Login successful...Now logging in");
this.Hide();
object user = UsernameLogin.Text;
object password = PasswordLogin.Text;
if (user = "root" & password = "Pa$$w0rd")
{
nextForm = new Form3();
}
else
{
nextForm = new Form2();
}
nextForm.ShowDialog();
}
//Form2 f2 = new Form2();
//f2.ShowDialog();
//if login is successful needs to lead to another screen - if matches my account standard store screen or make root account just for the admin page
}
table.Clear();
}
private void EmailSignUp_TextChanged(object sender, EventArgs e)
{
}
private void UsernameSignUp_TextChanged(object sender, EventArgs e)
{
}
private void PasswordSignUp_TextChanged(object sender, EventArgs e)
{
}
private void SignUpButton_Click(object sender, EventArgs e)
{
//connection.Open();
string Query = "insert into User_Details (Email,Username,Password) values('" + this.EmailSignUp.Text + "', '" + this.UsernameSignUp.Text + "','" + this.PasswordSignUp.Text + "');";
//string insertQuery = "INSERT INTO User_Details(Email,Username,Password)VALUES('" + EmailSignUp.Text + "','" + UsernameSignUp.Text + "'," + PasswordSignUp.Text + ")";
MySqlCommand command = new MySqlCommand(Query,connection);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("Data Inserted");
connection.Close();
}
else
{
MessageBox.Show("Data Not Inserted");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
}
}
}
A couple of things.
You need a User object in your application that stores user properties. This object can have an IsAdmin property that you can use later in your code.
Alternately, if you don't want to create and maintain a User object, you make another call to the database to see whether or not the user is an admin and store the result local to your method.
You then instantiate Form3 instead of Form2 based on whether or not the user is an admin.
Form nextForm;
var result = MessageBox.Show("Login successful...Now logging in");
this.Hide();
if (user.IsAdmin) {
nextForm = new Form3();
} else {
nextForm = new Form2();
}
nextForm.ShowDialog();
PS: I hope you are not storing passwords in plain text in your database like it seems you are.
I have multiple session variables, which both won't accept any values given to them by other variables. I have tried to debug and have found nothing. Here is the function I am using...
public void logIn(object sender, EventArgs e) //triggers when login button is clicked
{
db_connection(); //connects to database using above function
string emailAddress = email.Text.ToString();
string passwordR = password.Text.ToString(); //email and password are converted to variables
DataTable table = new DataTable();
MySqlCommand select = new MySqlCommand("SELECT personID, address_addressID from person WHERE email='" + emailAddress + "' and password = '" + passwordR + "'", connect); //brings back the person ID if user details are correct
using (MySqlDataAdapter adapter = new MySqlDataAdapter(select))
{
adapter.Fill(table);
string sessionVar = table.Rows[0]["personID"].ToString();
Session["personID"] ="";
Session["personID"] = sessionVar;
int sessionVarAddress = Int32.Parse(table.Rows[0]["address_addressID"].ToString());
Session["address_addressId"] = sessionVarAddress;
if (table.Rows.Count != 0)
{
if (Session["personID"] != null) //if the person ID is present do this following statement
{
hideDiv.Visible = false;
}
Response.Redirect("myAccount.aspx"); // if user logs in successfully redirect to my account pag
}
else
{
Response.Redirect("index.aspx"); //if login fails, home page is returned
}
connect.Close();
}
}
I looked around here on stackoverflow, as well Google, but was not able to find an answer that pertained to my problem, so i'm posting it here.
I have a login page where the user is directed to input their username and password, which are both stored in a MySQL database. The username is stored as plain text and the password is hashed (using the CrackStation - https://crackstation.net/hashing-security.htm#aspsourcecode) and the hash is stored in the database. I am able to successfully have the user login one time using the username and password, but I would like to use SESSION so that the user can navigate around the website and not have to login each time they go to a different page. I was easily able to use SESSION in my test environment because the password was stored as plain text, but now with the password being hashed i'm not able to get the Session to work in my code. So I wanted to know what can I do to get the password to validate in SESSION.
My code that I am using on my login page is the following:
protected void Page_Load(object sender, EventArgs e)
{
try
{
admin = Convert.ToInt16(Request.QueryString["Admin"]);
Instructor = Convert.ToInt16(Request.QueryString["Inst"]);
if (Session["username"] == null || (string)(Session["username"]) == "")
{
token = Request.QueryString["tokenNumber"];
lblUsername.Visible = true;
txtUsername.Visible = true;
lblPassword.Visible = true;
txtPassword.Visible = true;
btnlogin.Visible = true;
}
else if (Session["username"] != null || (string)(Session["username"]) != "")
{
username = (string)Session["username"];
userType = (string)Session["userType"];
pass = (string)Session["password"];
if (userType == "Participant")
{
Response.Redirect("/srls/StudentUser");
}
else if (userType == "Coordinator")
{
Response.Redirect("/srls/CoordinatorUser");
}
else if (userType == "Instructor")
{
Response.Redirect("/srls/InstructorUser");
}
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
protected void btnlogin_Click(object sender, System.EventArgs e)
{
char activation;
if (Request.QueryString["tokenNum"] != null)
{
using (OdbcConnection dbConnection = new OdbcConnection(srlsConnStr))
{
dbConnection.Open();
{
OdbcCommand dbCommand = new OdbcCommand();
dbCommand.Connection = dbConnection;
dbCommand.CommandText = #"SELECT tokenNum FROM srlslogin WHERE user_email_pk = ?";
dbCommand.Parameters.AddWithValue("#user_email_pk", txtUsername.Text);
dbCommand.ExecuteNonQuery();
OdbcDataReader dataReader = dbCommand.ExecuteReader();
while (dataReader.Read())
{
if (token == dataReader["tokenNum"].ToString())
{
updateActivationStatus(txtUsername.Text);
LoginWithPasswordHashFunction();
}
else
{
test.Text = "You are not authorized to login! Please activate your account following the activation link sent to your email " + txtUsername.Text + " !";
}
}
}
dbConnection.Close();
}
}
else if (Request.QueryString["tokenNum"] == null)
{
using (OdbcConnection dbConnection = new OdbcConnection(srlsConnStr))
{
dbConnection.Open();
{
OdbcCommand dbCommand1 = new OdbcCommand();
dbCommand1.Connection = dbConnection;
dbCommand1.CommandText = #"SELECT * FROM srlslogin WHERE user_email_pk = ?;";
dbCommand1.Parameters.AddWithValue("#user_email_pk", txtUsername.Text);
dbCommand1.ExecuteNonQuery();
OdbcDataReader dataReader1 = dbCommand1.ExecuteReader();
if (dataReader1.Read())
{
activation = Convert.ToChar(dataReader1["activation_status"]);
if (activation == 'Y')
{
activation status, activation == Y";
LoginWithPasswordHashFunction();
}
else
{
lblMessage.Text = "Please activate your account following the Activation link emailed to you at <i>" + txtUsername.Text + "</i> to Continue!";
}
}
else
{
lblMessage.Text = "Invalid Username or Password";
}
dataReader1.Close();
}
dbConnection.Close();
}
}
}
private void LoginWithPasswordHashFunction()
{
List<string> salthashList = null;
List<string> usernameList = null;
try
{
using (OdbcConnection dbConnection = new OdbcConnection(srlsConnStr))
{
dbConnection.Open();
{
OdbcCommand dbCommand = new OdbcCommand();
dbCommand.Connection = dbConnection;
dbCommand.CommandText = #"SELECT slowhashsalt, user_email_pk FROM srlslogin WHERE user_email_pk = ?;";
dbCommand.Parameters.AddWithValue(#"user_email_pk", txtUsername.Text);
OdbcDataReader dataReader = dbCommand.ExecuteReader();
while (dataReader.HasRows && dataReader.Read())
{
if (salthashList == null)
{
salthashList = new List<string>();
usernameList = new List<string>();
}
string saltHashes = dataReader.GetString(dataReader.GetOrdinal("slowhashsalt"));
salthashList.Add(saltHashes);
string userInfo = dataReader.GetString(dataReader.GetOrdinal("user_email_pk"));
usernameList.Add(userInfo);
}
dataReader.Close();
if (salthashList != null)
{
for (int i = 0; i < salthashList.Count; i++)
{
bool validUser = PasswordHash.ValidatePassword(txtPassword.Text, salthashList[i]);
if (validUser == true)
{
Session["user_email_pk"] = usernameList[i];
OdbcCommand dbCommand1 = new OdbcCommand();
dbCommand1.Connection = dbConnection;
dbCommand1.CommandText = #"SELECT user_status FROM srlslogin WHERE user_email_pk = ?;";
dbCommand1.Parameters.AddWithValue("#user_email_pk", txtUsername.Text);
dbCommand1.ExecuteNonQuery();
OdbcDataReader dataReader1 = dbCommand1.ExecuteReader();
while (dataReader1.Read())
{
user_status = dataReader1["user_status"].ToString();
Session["userType"] = user_status;
}
Response.BufferOutput = true;
if (user_status == "Participant")
{
Response.Redirect("/srls/StudentUser", false);
}
else if (user_status == "Coordinator")
{
Response.Redirect("/srls/CoordinatorUser", false);
}
else if (user_status == "Instructor")
{
Response.Redirect("/srls/InstructorUser", false);
}
dataReader1.Close();
Response.Redirect(/srls/StudentUser) - Goes to Login Page";
}
else
{
lblMessage.Text = "Invalid Username or Password! Please Try Again!";
}
}
}
}
dbConnection.Close();
}
}
catch (Exception ex)
{
}
You should not store the username and password in the session. You should store the 'fact' that the user has been successfully logged in. But actually you shouldn't even be doing that yourself. ASP.NET comes with various authentication methods. Please have a look at http://www.asp.net/identity to get started.
That is not so good solution. Don't store username's login, password, type, so on, in your sessions. Once user is logging in your system, just store his ID. I use next way: I have login page, and I have MasterPage and all my web-forms are inherited from MasterPage. And in the MasterPage on Page_Init I do something like:
string users_role = MyClass.GetUsersRoleById(Session["id"].ToString());
I have user's role in the database, so by ID I may exclude user's role. And, for example, you have by one folder for every role. You may do something like:
if (String.IsNullOrEmpty(users_role)) //if null it means that user have no any role or you didn't checked for authorization first
Response.Redirect(users_role); //redirect to role's page: e.g. Admin, User, Student, Teacher, so on.
I am working in a simple registration page where the user can't enter the same user name or email, I made a code that prevent the user from entering the username and it worked but when I tried to prevent the user from entring the same username or email it didn't work.
and my question is, "How can I add another condition where the user can't enter email that already exists?"
I tried to do it in this code, but it did't work:
protected void Button_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection( ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString );
SqlCommand cmd1 = new SqlCommand("select 1 from Table where Name =#UserName", con);
SqlCommand cmd2 = new SqlCommand("select 1 from Table where Email=#UserEmail", con);
con.Open();
cmd1.Parameters.AddWithValue("#UserName", Name_id.Text);
cmd2.Parameters.AddWithValue("#UserEmail", Email_id.Text);
using (var dr1 = cmd1.ExecuteReader())
{
if (dr1.HasRows)
{
Label1.Text = "user name already exists";
}
using (var dr2 = cmd2.ExecuteReader())
{
if (dr2.HasRows)
{
Label1.Text = "email already exists";
}
else
{
dr1.Close();
dr2.Close();
//add new users
con.Close();
}
}
}
}
but i get this error:
There is already an open DataReader associated with this Command which must be closed first.
Like I said in my comment your design is bad !
First you should have Data Access Layer. This should be project in big solutions but in your case you can put it like new directory. In this directory you create SqlManager class here is the code:
public class SqlManager
{
public static string ConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings["DevConnString"].ConnectionString;
}
}
public static SqlConnection GetSqlConnection(SqlCommand cmd)
{
if (cmd.Connection == null)
{
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
cmd.Connection = conn;
return conn;
}
return cmd.Connection;
}
public static int ExecuteNonQuery(SqlCommand cmd)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
return cmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
public static object ExecuteScalar(SqlCommand cmd)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
return cmd.ExecuteScalar();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
public static DataSet GetDataSet(SqlCommand cmd)
{
return GetDataSet(cmd, "Table");
}
public static DataSet GetDataSet(SqlCommand cmd, string defaultTable)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
DataSet resultDst = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}
return resultDst;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
public static DataRow GetDataRow(SqlCommand cmd)
{
return GetDataRow(cmd, "Table");
}
public static DataRow GetDataRow(SqlCommand cmd, string defaultTable)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
DataSet resultDst = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}
if (resultDst.Tables.Count > 0 && resultDst.Tables[0].Rows.Count > 0)
{
return resultDst.Tables[0].Rows[0];
}
else
{
return null;
}
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
}
After that you should have Business Object Layer. In bigger solution is project in your case directory. If you are in the page TaxesEdit.aspx, you should add Tax.cs class in the BO(business object).
Example of methods for the class, for your first button:
public DataSet GetTaxesByUserName(string userName)
{
SqlCommand cmd = new SqlCommand(#"
select 1 from Table where Name =#UserName");
cmd.Parameters.AddWithValue("#UserName", userName);
return DA.SqlManager.GetDataSet(cmd);
}
You fetch all the needed data in datasets. After that you make checks like taxesDst.Tables[0].Rows.Count > 0 (or == 0)
For Insert you can have method like this:
public virtual void Insert(params object[] colValues)
{
if (colValues == null || colValues.Length % 2 != 0)
throw new ArgumentException("Invalid column values passed in. Expects pairs (ColumnName, ColumnValue).");
SqlCommand cmd = new SqlCommand("INSERT INTO " + TableName + " ( {0} ) VALUES ( {1} )");
string insertCols = string.Empty;
string insertParams = string.Empty;
for (int i = 0; i < colValues.Length; i += 2)
{
string separator = ", ";
if (i == colValues.Length - 2)
separator = "";
string param = "#P" + i;
insertCols += colValues[i] + separator;
insertParams += param + separator;
cmd.Parameters.AddWithValue(param, colValues[i + 1]);
}
cmd.CommandText = string.Format(cmd.CommandText, insertCols, insertParams);
DA.SqlManager.ExecuteNonQuery(cmd);
}
For this you need to have property TableName in the current BO class.
In this case this methods can be used everywhere and you need only one line of code to invoke them and no problems like yours will happen.
You have opened another DataReader inside the First and thats causing the problem. Here I have re-arranged your code a bit
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd1 = new SqlCommand("select 1 from Table where Name =#UserName", con),
cmd2 = new SqlCommand("select 1 from Table where Email=#UserEmail", con);
con.Open();
cmd1.Parameters.AddWithValue("#UserName", Name_id.Text);
cmd2.Parameters.AddWithValue("#UserEmail", Email_id.Text);
bool userExists = false, mailExists = false;
using (var dr1 = cmd1.ExecuteReader())
if (userExists = dr1.HasRows) Label1.Text = "user name already exists";
using (var dr2 = cmd2.ExecuteReader())
if (mailExists = dr2.HasRows) Label1.Text = "email already exists";
if (!(userExists || mailExists)) {
// can add User
}
You need to close one datareader before opening the other one. Although it's not how I'd do it, but you can deal with the runtime error by closing the datareader after each IF:
using (var dr1 = cmd1.ExecuteReader())
{
if (dr1.HasRows)
{
string Text = "user name already exists";
}
dr1.Close();
}
using (var dr2 = cmd2.ExecuteReader())
{
if (dr2.HasRows)
{
string ext = "email already exists";
}
else
{
//add new users
}
dr2.Close();
}
con.Close();
This may work, although there are a few things I would do differently...
protected void Button_Click(object sender, EventArgs e)
{
bool inputIsValid = true;
var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
var userNameCmd = new SqlCommand("SELECT 1 FROM Table WHERE Name = #UserName", con);
var emailCmd = new SqlCommand("SELECT 1 FROM Table WHERE Email = #UserEmail", con);
con.Open();
userNameCmd.Parameters.AddWithValue("#UserName", Name_id.Text);
emailCmd.Parameters.AddWithValue("#UserEmail", Email_id.Text);
using (var userNameReader = userNameCmd.ExecuteReader())
{
if (userNameReader.HasRows)
{
inputIsValid = false;
Label1.Text = "User name already exists";
}
}
using (var emailReader = emailCmd.ExecuteReader())
{
if (emailReader.HasRows)
{
inputIsValid = false;
Label1.Text = "Email address already exists";
}
}
if (inputIsValid)
{
// Insert code goes here
}
con.Close();
}
Why don't you do something like this:
[Flags]
public enum ValidationStatus
{
Valid = 0 ,
UserNameInUse = 1 ,
EmailInUse = 2 ,
}
public ValidationStatus ValidateUser( string userName , string emailAddr )
{
ValidationStatus status ;
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString ;
using ( SqlConnection con = new SqlConnection( connectionString ) )
using ( SqlCommand cmd = con.CreateCommand() )
{
cmd.CommandText + #"
select status = coalesce( ( select 1 from dbo.myTable t where t.UserName = #UserName ) , 0 )
+ coalesce( ( select 2 from dbo.myTable t where t.UserEmail = #UserEmail ) , 0 )
" ;
cmd.Parameters.AddWithValue( "#UserName" , userName ) ;
cmd.Parameters.AddWithValue( "#emailAddr" , emailAddr ) ;
int value = (int) cmd.ExecuteScalar() ;
status = (ValidationStatus) value ;
}
return status ;
}
Aside from anything else, hitting the DB twice for something like this is silly. And this more clearly expresses intent.
Then you can use it in your button click handler, something like this:
protected void Button_Click( object sender , EventArgs e )
{
string userName = Name_id.Text ;
string emailAddr = Email_id.Text ;
ValidationStatus status = ValidateUser( userName , emailAddr ) ;
switch ( status )
{
case ValidationStatus.Valid :
Label1.Text = "" ;
break ;
case ValidationStatus.EmailInUse :
Label1.Text = "Email address in use" ;
break ;
case ValidationStatus.UserNameInUse :
Label1.Text = "User name in use" ;
break ;
case ValidationStatus.EmailInUse|ValidationStatus.UserNameInUse:
Label1.Text = "Both user name and email address in use." ;
break ;
default :
throw new InvalidOperationException() ;
}
if ( status == ValidationStatus.Valid )
{
CreateNewUser() ;
}
}