When You press "Create user" in your ASP.NET standard CreateUserQizard the OnCreatedUser gets called and redirects you after the user is created. However I need to run some code before the user is created but after the "Create user" button is clicked.
Like this: Click "Create user" -> Run my method -> Create user -> OnCreatedUser
I have made my own method for checking if email already exists, however I don't know how to call it since the Wizard creates the user right away. Is there any way to get in before the user is created and execute my code?
My code:
TextBox EmailTextBox = RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("Email") as TextBox;
String emailParam = EmailTextBox.Text;
using (SqlConnection con = new SqlConnection(strCon))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT Email FROM Memberships WHERE Email=#emailParam";
cmd.Parameters.AddWithValue("#emailParam", emailParam);
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
LabelExists.Text = "This e-mail is already registered";
}
else
{
//execute method that creates user
}
}
}
con.Close();
}
Simply use OnCreatingUser, and set e.Cancel = true; if e-mail is already registered.
If you set requiresUniqueEmail="true" for the membership provider, it does this check for you.
Related
I am developing a login system using ASP.NET 7.0. I have created the login and signup system, by connecting to an SQL database and inserting or querying it for information. Currently, the backend code is able to create accounts, and check to make sure that while making an account, that their is no user with matching email or username. I would like to be able to display some sort of message saying "An account with those details has already been created, Login?". How would I go about this?
Here is my current code:
public void OnPostSignup()
{
System.Diagnostics.Debug.WriteLine("Post Request Received");
// Creating Credentials //
string InputUser = Request.Form["signup-user"];
string InputPassword = Request.Form["signup-pwd"];
string InputEmail = Request.Form["signup-email"];
// Creates a new SQL Connection using the connection string provided - Then runs an SQL Command: NOTHING HAS BEEN RUN YET, ONLY INSTANCIATED //
using (SqlConnection conn = new SqlConnection("Valid Server String Here"))
using (SqlCommand cmd = new SqlCommand("INSERT INTO AccountData ([User], [Password], [Email]) VALUES (#1, #2, #3);", conn))
{
// The Placeholder Values are replaced with the string variables created above containing our account registration data //
cmd.Parameters.AddWithValue("#1", InputUser);
cmd.Parameters.AddWithValue("#2", InputPassword);
cmd.Parameters.AddWithValue("#3", InputEmail);
// Instanciates a new SQL Command that will cehck the database to ensure an account with that infomation hasnt been created already //
using (SqlCommand UserCheck = new SqlCommand("SELECT * FROM AccountData WHERE [User] = #1 AND [Email] = #2", conn))
{
// Adds the inputted data into the UserCheck SQL Command //
UserCheck.Parameters.AddWithValue("#1", InputUser);
UserCheck.Parameters.AddWithValue("#2", InputEmail);
// A connection to our SQL Databasse is opened //
conn.Open();
// Executes a data reader on our SQL Server
SqlDataReader reader= UserCheck.ExecuteReader();
// This logic gate checks if the reader returns any rows with the given infomation - if yes, no account is created, and the connection is closed - if no, the account creation is started //
if(reader.HasRows)
{
// We already have an account with the same email or username //
reader.Close();
conn.Close();
// Display some sort of message to the user saying that their email or username is already in use. //
}
else
{
// We do not have an account with that information - An account can now be created //
// Closes the reader, because we cannot query our SQL databse twice at the same time //
reader.Close();
// Executes the 'cmd' SQL command against our SQL Databse //
cmd.ExecuteNonQuery();
// Closes the connection to our SQL Databse for security - and cost //
conn.Close();
}
}
}
}
// This will run when the user clicks the "Login button, after filling out all the required fourm felids //
public void OnPostLogin()
{
// Takes the data inputted by the user, and stores them as variables to be ran against the SQL Database //
string LoginUser = Request.Form["login-user"];
string LoginPass = Request.Form["login-passwrd"];
// Defines an SQL Connection with our SQL Connection String //
using (SqlConnection conn = new SqlConnection("Valid Connection String Here"))
// Creates a new SQL command that checks the database for a account; notice that '#1' amd '#2' are placeholders //
using (SqlCommand cmd = new SqlCommand("SELECT * FROM AccountData WHERE [User] = #1 AND [Password] = #2", conn))
{
// Replaces the placeholder values in the SQL command with our varaibles that were created from the users input
cmd.Parameters.AddWithValue("#1", LoginUser);
cmd.Parameters.AddWithValue("#2", LoginPass);
// A connection is opened to our SQL Database //
conn.Open();
// Executes the SQL Database reader with the paramaters defined in our SQL Command 'cmd' //
SqlDataReader reader = cmd.ExecuteReader();
// Checks if the SQL reader returned any rows //
if (reader.HasRows)
{
// User Exists //
reader.Close();
System.Diagnostics.Debug.WriteLine("We have found an account");
// Log in the user //
}
else
{
// User Doesnt Exist //
reader.Close();
System.Diagnostics.Debug.WriteLine("No Account Found");
}
// Closes the connection to our SQL Database //
conn.Close();
}
}
I am aware that the code may be vunrable to SQL injection attacks! the website has not been published yet, and security will be added before launch.
I appreciate any help that I receive, if there is anything that doesn't make sense, please let me know!
Thanks for the help everybody! However, i have found a solution to the problem. Inside of the if statement where login details are verified, i added this onto the 'invalid login' return.
ModelState.AddModelError("InvalidLogin", "Invalid login details");
And then, directly below my login form i added the following code
#if (Model.ModelState.ContainsKey("InvalidLogin"))
{
<div class="alert alert-danger">#Model.ModelState["InvalidLogin"].Errors[0].ErrorMessage</div>
System.Diagnostics.Debug.WriteLine("Error message displayed in view");
}
else
{
System.Diagnostics.Debug.WriteLine("No error message to display in view");
}
If you are viewing this post late, looking for an answer, this worked well for me. If you would like help setting this up for your code feel free to # me
I have a very basic program I'm writing to get used to using visual studio. The main window of the program contains a listbox named listBox1, and a rich text box named richTextBox1, as well as several buttons which perform various actions to get data from the table named DocStorage, which has a column named DocumentName that stores any words from richTextBox1 as a new row in the database.
I have managed to get the save feature to work, it takes any text from the richTextBox1 and stores in the database as a row, no problem.
Now I need to code for the DELETE and OPEN buttons. The DELETE button should remove a record from the SQL Server database, which is simple enough, but I can't figure out how to make it based on which item is selected from the listBox1 before the user pushes the DELETE button named BtnDelete.
I also would like to be able to work in reverse and OPEN that stored string back to the richTextBox1 based on which item the user has selected in listBox1 before they push the OPEN button named BtnOpen.
Trying to implement similar examples from the web has proven unsuccessful after many attempts, would appreciate some guidance in the right direction, so I can learn where I'm going wrong with coding these buttons.
I'm a beginner, so please forgive my ignorance and help me get these final two buttons of my first app completed!
Here is a snippet of my code for BtnDelete_Click
if (MessageBow.Show("Are you sure you want to Delete this File?", "Open File", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
con.Open();
SqlConnection con = new SqlConnection(#"...........");
SqlCommand cmd = new SqlCommand("DELETE [DocumentName] from DocStorage where DocumentName=#DocShred", con);
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#DocShred", listBox1.SelectedItem.ToString());
con.Close();
MessageBox.Show("Delete Successful", "File Deleted", MessageBoxButtons.Ok);
}
Thanks in advance.
You're on the right track - just not quite there yet....
Several things:
first, you open the con.Open() and in the next line you create it again - from scratch - that doesn't make any sense.....
you're never executing the query - you're building it up, adding parameter value and all - but you're never actually running the code!
You should use using(....) { .... } blocks to ensure proper disposal of your resources
Try this code:
if (MessageBow.Show("Are you sure you want to Delete this File?", "Open File", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// define connection string (load from config) and query statement
string connStr = ".......";
string qryDelete = "DELETE [DocumentName] FROM DocStorage WHERE DocumentName = #DocShred";
// set up the connection and command
using (SqlConnection con = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand(qryDelete, con))
{
cmd.Parameters.Add(new SqlParameter("#DocShred", listBox1.SelectedItem.ToString());
// open connection, execute query, close connection
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
}
MessageBox.Show("Delete Successful", "File Deleted", MessageBoxButtons.Ok);
}
I ran this slightly modified version...
private void BtnDelete_Click(object sender, EventArgs e)
{
string TrashedDoc = listBox1.SelectedItem.ToString();
if (MessageBox.Show("Are you sure you want to Delete this File?", "Delete File", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
string connStr = #"...............";
string qryDelete = "DELETE FROM [DocStorage] WHERE DocumentName = #DocShred";
using (SqlConnection con = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand(qryDelete, con))
{
cmd.Parameters.Add(new SqlParameter("#DocShred", TrashedDoc));
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
}
/// if the Delete is successful a message box confirms to user
MessageBox.Show("Delete Successful", "File Deleted", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
and although the codes runs fine, for some reason it is not actually deleting the selected item in the listbox from the database, it just gives a Delete Successful message. Refreshing database confirms that it did not delete anything.
I'm having problems with updating a row in the Users table of my Access DB. Here is the code below:
private void SaveProfileInfo()
{
try
{
ChangeForeColorOfStatusMsg(Color.Black);
ChangeTextOfStatusMsg("Saving new profile information...");
const string cmd = #"UPDATE Users SET LastName=#LastName,FirstName=#FirstName,MiddleName=#MiddleName,Add_Num=#Add_Num,Add_Street=#Add_Street,Add_Brgy=#Add_Brgy,Add_City=#Add_City,MobileNumber=#MobileNumber,Gender=#Gender WHERE ID=#ID;";
var dbConn = new OleDbConnection(cs);
var dbCmd = new OleDbCommand(cmd, dbConn);
dbCmd.Parameters.AddWithValue("#ID", UserLoggedIn.ID);
dbCmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
dbCmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
dbCmd.Parameters.AddWithValue("#MiddleName", txtMiddleName.Text);
dbCmd.Parameters.AddWithValue("#Add_Num", txtUnitNum.Text);
dbCmd.Parameters.AddWithValue("#Add_Street", txtStreet.Text);
dbCmd.Parameters.AddWithValue("#Add_Brgy", GetBrgySelectedItem());
dbCmd.Parameters.AddWithValue("#Add_City", GetCitySelectedItem());
dbCmd.Parameters.AddWithValue("#MobileNumber", txtMobileNumber.Text);
dbCmd.Parameters.AddWithValue("#Gender", GetGenderSelectedItem());
dbConn.Open();
dbCmd.ExecuteNonQuery();
dbConn.Close();
ChangeForeColorOfStatusMsg(Color.MediumSeaGreen);
ChangeTextOfStatusMsg("All changes have been saved! This window will close itself after two seconds.");
Thread.Sleep(2000);
CloseForm();
}
catch (Exception)
{
ChangeForeColorOfStatusMsg(Color.Crimson);
ChangeTextOfStatusMsg("Something went wrong while we were connecting to our database. Please try again later.");
hasFinishedEditting = false;
}
}
This method will be done on a separate thread, when the user updates his profile information.
UserLoggedIn is actually a field of a User class (a class that defines a row in my table), which stores all the info of the user who's currently logged in.
When I run this, it does not produce any exceptions or errors. But when I check my table, the values are not updated.
I copy-pasted these codes from the registration form (which works) that I made with this system, and modified it into an UPDATE cmd than an INSERT cmd.
I also made Change Username and Password Forms that use the same cmd as shown below:
public void ChangePass()
{
try
{
ChangeForeColorOfMsg(Color.Silver);
ChangeTextOfMsg("Changing password...");
const string cmd = "update Users set Pass=#Pass where ID=#ID";
var dbConn = new OleDbConnection(cs);
var dbCmd = new OleDbCommand(cmd, dbConn);
dbCmd.Parameters.AddWithValue("#Pass", txtNewPass.Text);
dbCmd.Parameters.AddWithValue("#ID", UserLoggedIn.ID);
dbConn.Open();
dbCmd.ExecuteNonQuery();
dbConn.Close();
ChangeTextOfMsg("Password successfully changed!");
}
catch (Exception)
{
ChangeForeColorOfMsg(Color.Silver);
ChangeTextOfMsg("A problem occurred. Please try again later.");
}
}
And these codes work for me. So I'm really confused right now as to why this update cmd for the profile information isn't working... Is there something I'm not seeing here?
OleDb cannot recognize parameters by their name. It follows a strictly positional order when sending them to your database for updates. In your code above the first parameter is the #ID but this parameter is used last in your query. Thus everything is messed up.
You just need to move the add of the #ID parameter as last in the collection
As a side note, you should be very careful with AddWithValue. It is an handy shortcut, but it has a dark side that could result in wrong queries.
Take a look at
Can we stop using AddWithValue already?
This is a simple login page with 2 panels. Panel for login where user enters user name and password. I validate if username is present and do this:
string query = "SELECT UserName,HashedPassword,SaltString FROM users WHERE UserName='"+txtUserName.Text+"'";
using(SqlConnection con = new SqlConnection(connection))
{
con.Open();
SqlCommand cmd=new SqlCommand(query,con);
SqlDataReader sdr = cmd.ExecuteReader();
if (!sdr.Read())
{
pnlLogin.Visible = false;
pnlRegister.Visible = true;
}
else
{
//validate password and redirect
}
I remember to have done same thing a few times before, although I don't have the code with me. I use form authentication in web.config. Please tell me where I am going wrong. Thanks in advance.
And one if I comment this:
pnlLogin.Visible = false;
the pnlRegister becomes visible.
If pnlRegister is nested in (a child of) pnlLogin, and you hide pnlLogin, pnlRegister will also be invisible.
Since you didn't provide markup, this is a guess based on the behavior you described.
I'm new to C# and have a background in SQL so apologies if this is a very stupid query, but I have been trawling google for about 2 hours now and can't find what I need. If someone knows of an article they can point me to, that would be great.
I have a simple windows forms application, and I'm setting up a login box so that users have to enter their user ID to proceed.
I have a SQL Server DB (SQL 2005) with the following table:
Users
UserID (int); userName nvarchar(50)
I am using Visual Studio 2010
What I'm stymied by is how to check whether their userID exists in my SQL Table (called users...) I'm not going to put any code here because it's been rewritten from scratch so many times that a clean slate is probably best!
Ideally, I want the user to enter their user ID, and click 'login'. When they do this, if their userID is not valid in the DB table then I need it to give an error msgBox; if it is valid then it should log them in, passing their userID and userName (stored in the DB table) to a variable which I can use elsewhere in the application to populate fields.
I hope this makes sense, and I'm sure I've missed the perfect article out there which will explain it all - hopefully one of you kind people can point me in the right direction!
Thank you
You should make a simple SQL query with the userID the user entered, like
SELECT UserID from Users where userID= value. The executeNonQuery() will return the number of matches. If the returned value ==1, means that the userid exists in the database. If the returned value is different from 1, means that the userid not exists or it was registered multiple times. So, if is 1 then you cand call a different form to make different things, else you call anoter form or output a messagebox with an error message
/*table code
* create table login
(
id varchar(25),
pass varchar(25)
)
*
*
*
*
*/
string Connectstring = #"Data Source=DELL-PC;Initial Catalog=stud;Integrated Security=True";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(Connectstring);
cn.Open();
SqlCommand cmd = new SqlCommand("select * from log where id=#a and pass=#b", cn);
cmd.Parameters.AddWithValue("#a", textBox1.Text.ToString().ToUpper());
cmd.Parameters.AddWithValue("#b", textBox2.Text);
SqlDataReader dr = cmd.ExecuteReader();
if ((dr.Read() == true))
{
MessageBox.Show("The user is valid!");
Form2 mainForm = new Form2();
mainForm.Show();
this.Hide();
}
else
{
MessageBox.Show("Invalid username or password!");
}
}
Declare a connection string to Your database
string connString = #"Data Source=.\SQLEXPRESS;Initial Catalog=YourDatabase;Integrated Security=True";
After this You can use a validate method below
private bool ValidateUserById(string connString, int id)
{
using (var conn = new SqlConnection(connString))
{
conn.Open();
var sqlString = string.Format("Select * From Users where Id = {0}", id);
using (var cmd = new SqlCommand(sqlString, conn))
{
return cmd.ExecuteScalar() != null;
}
}
}
Then on button click You can check the user
if (ValidateUserById(connString, Convert.ToInt32(textBox1.Text)))
{
//..
}
else
{
//..
}