i have made a credit request page wherein users can request a value/amount. I have implemented that it should be activated first via email activation before putting the data to the admin page for viewing and approval.
i have made an "Activated" field where it is null until the user has clicked the link on his/her email address and it becomes "1" when user clicks it.
here is the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = "Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True";
string activationCode = !string.IsNullOrEmpty(Request.QueryString["ActivationCode"]) ? Request.QueryString["ActivationCode"] : Guid.Empty.ToString();
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand Activate = new SqlCommand("SELECT UserId FROM CRActivation WHERE ActivationCode = #ActivationCode");
Activate.Parameters.AddWithValue("#ActivationCode", activationCode);
Activate.Connection = con;
con.Open();
string storedUserId = Activate.ExecuteScalar().ToString();
con.Close();
using (SqlCommand cmd = new SqlCommand("DELETE FROM CRActivation WHERE ActivationCode = #ActivationCode"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ActivationCode", activationCode);
cmd.Connection = con;
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
if (rowsAffected == 1)
{
SqlCommand userCmd = new SqlCommand("UPDATE CreditRequests SET Activated = 1 WHERE ID = " + storedUserId);
userCmd.Connection = con;
con.Open();
userCmd.ExecuteNonQuery();
con.Close();
ltMessage.Text = "Credit Request Submitted.";
}
else
{
ltMessage.Text = "Invalid Activation code.";
}
}
}
}
}
what i want to happen is to carry over the "Activated" field and make an if statement that if it is 1, it will be shown in my gridview.
here is the gridview code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["IslandGasAdminFM"] != null)
{
bindgrid();
Label1.Text = "- Finance Manager";
}
else
{
Response.Write("<script>alert('Finance Manager credentials needed'); window.location.href='LogIn.aspx';</script>");
}
}
something like this:
if(Activated==1)
{
bindgrid();
}
any help or tricks will be of great help.
Related
When I'm choosing additional (empty) position on Dropdownlist created by DropDownList.Item.Insert whole application is terminated.
if (!Page.IsPostBack)
{
DropDownList4.Items.Add(new ListItem("", ""));
DropDownList4.AppendDataBoundItems = true;
String strConnString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Projects\projects.accdb";
String strQuery = "select * from projects";
OleDbConnection con = new OleDbConnection(strConnString); ;
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
DropDownList4.DataSource = cmd.ExecuteReader();
DropDownList4.DataTextField = "Project_name";
DropDownList4.DataValueField = "ID";
DropDownList4.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Projects\projects.accdb";
string strQuery = "select * from projects where" + " ID = #ID";
OleDbConnection con = new OleDbConnection(strConnString);
OleDbCommand cmd = new OleDbCommand();
cmd.Parameters.AddWithValue("#ID", DropDownList4.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
OleDbDataReader myreader;
try
{
con.Open();
myreader = cmd.ExecuteReader();
myreader.Read();
TextBox12.Text = myreader["Project_name"].ToString();
TextBox2.Text = myreader["Owner"].ToString();
myreader.Close();
}
finally
{
con.Close();
}
}
As I'm thinking the reason is that the empty value does not exist in DB (but it is just created every time on Page_load by DropDownList4.Items.Add(new ListItem("", ""))). How to exclude from checking in DB first empty position on DropDownList?
Edited:
...
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
DropDownList4.DataSource = cmd.ExecuteReader();
if (DropDownList4.SelectedItem.Value == null || DropDownList4.SelectedItem == null)
{
}
DropDownList4.DataTextField = "Project_name";
DropDownList4.DataValueField = "ID";
DropDownList4.DataBind();
}
Still does not working
Edited:
string selected = DropDownList4.SelectedItem.Text;
if (string.IsNullOrEmpty(selected))
{
}
Now - It's working :)
You need (and want to) add the blank dropdown row AFTER you fill the dropdown.
So, say we have this markup:
<asp:DropDownList ID="DropDownList1" runat="server"
Height="26px" Width="207px" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
DataValueField="ID"
DataTextField="HotelName"
>
</asp:DropDownList>
And I DO suggest that you put the DataValue/Text settings in the control - really no need or advantage to putting that code in code behind.
And we don't need (or want) to re-load or re-insert the extra blank dropdown choice each time - so load the dropdown ONLY one time (the PostBack = false in page load as you attempted is correct).
So, we will select a hotel, and then pull that ONE database row for additional information - shove into a few text boxes as your code example does.
I suggest this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string strSQL =
"SELECT ID, HotelName FROM tblHotels ORDER BY HotelName";
OleDbCommand cmdSQL = new OleDbCommand(strSQL);
DropDownList1.DataSource = MyRstP(cmdSQL);
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("- Select.. -", "0"));
}
}
DataTable MyRstP(OleDbCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.AccessDB))
{
cmdSQL.Connection = conn;
using (cmdSQL)
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string HotelPK = DropDownList1.SelectedItem.Value as string;
string strSQL = "SELECT * FROM tblHotels where ID = #ID";
OleDbCommand cmdSQL = new OleDbCommand(strSQL);
cmdSQL.Parameters.Add("#ID", OleDbType.Integer).Value = HotelPK;
DataTable rstData = MyRstP(cmdSQL);
if (rstData.Rows.Count > 0)
{
DataRow OneRow = rstData.Rows[0];
TextBox1.Text = OneRow["HotelName"].ToString();
txtTaxRate.Text = OneRow["HotelTax"].ToString();
}
}
We also assume and have AutoPostBack = true for the drop list to fire each time we change it.
I can't find my problem. Can anyone help me to check it. I'm new in C#.
public void Btnchange_Click(object sender, EventArgs args)
MySqlConnection con = new MySqlConnection("server=localhost;user id=root;persistsecurityinfo=True;database=user;password=1234");
MySqlDataAdapter sda = new MySqlDataAdapter("select Password from user.register where Password='" + textoldpassword.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count.ToString() == "1")
{
if (textnewpassword.Text == textconfirmpassword.Text)
{
con.Open();
MySqlCommand cmd = new MySqlCommand("update user.register set Password ='" + textconfirmpassword.Text + "' where Password ='" + textoldpassword.Text + "'", con);
cmd.ExecuteNonQuery();
con.Close();
lblmsg.Text = "Succesfully Updated";
lblmsg.ForeColor = Color.Green;
}
else
{
lblmsg.Text = "New password and confirm password should be same!";
}
I expect it can update and change my password.
There are many many (mostly) minor mistakes in your code:
use some kind of Id fields in your sql tables
never do an update like you did (update the field WHERE this field is equals to...)
create your own class and bind the query result to this class
when a class implements IDisposable interface, always use the keyword 'using'
never ever user string concatenation in sql queries!!! SQL INJECTION!!! always use parametrized sql queries
Here's a simple example for your form. Let's suppose your
user.register table has the following columns:
- Id
- Username
- Password
Now let's create your own class (maybe right under your button click
event, so it can be private this time):
private class MyUser
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
Then your button click event should look like this:
private void Btnchange_Click(object sender, EventArgs e) {
if (!textnewpassword.Text.Trim().Equals(textconfirmpassword.Text.Trim()))
{
throw new ArgumentException("New password and confirm password should be same!");
}
List<MyUser> myUsers = new List<MyUser>();
using (MySqlConnection con =
new MySqlConnection(
"server=localhost;user id=root;persistsecurityinfo=True;database=user;password=1234"))
{
using (MySqlCommand cmd = new MySqlCommand("select * from user.register where Username=#user and Password=#pass", con))
{
cmd.Parameters.AddWithValue("#user", textusername.Text.Trim());
cmd.Parameters.AddWithValue("#pass", textoldpassword.Text.Trim());
if (cmd.Connection.State != ConnectionState.Open) cmd.Connection.Open();
using (MySqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
myUsers.Add(new MyUser
{
Id = (int)dr["Id"],
Username = dr["Username"].ToString(),
Password = dr["Password"].ToString()
});
}
}
if (cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close();
}
if (!myUsers.Any())
{
throw new ArgumentException("No users found with the given username/password pair!");
}
if (myUsers.Count != 1)
{
throw new ArgumentException("More than 1 user has the same username and password in the database!");
}
MyUser user = myUsers.First();
user.Password = textnewpassword.Text.Trim();
using (MySqlCommand cmd = new MySqlCommand("update user.register set Password=#pass where Id=#id"))
{
cmd.Parameters.AddWithValue("#pass", user.Password);
cmd.Parameters.AddWithValue("#id", user.Id);
if (cmd.Connection.State != ConnectionState.Open) cmd.Connection.Open();
cmd.ExecuteNonQuery();
if (cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close();
}
} }
...and so on.
I have 2 pages: LogIn page, UpdateInformation page. If the user logIn , he will go to updateInforamtion page to update his information.
My prblem is on (myReader = cmd.ExecuteReader();) : How Can I select row depend on LogIn page.
Error is: Additional information: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''' at line 1
in Update page I wrote this code:
protected void Page_Load(object sender, EventArgs e)
{
string StudentId = Session["StudentId"].ToString();
if (Session["FirstName"] == null)
{
Response.Redirect("Login.aspx");
}
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["AHSConnection"].ToString();
using (MySqlConnection conn = new MySqlConnection(connStr))
{
MySqlDataReader myReader = null;
MySqlCommand cmd = new MySqlCommand("Select * from student where S_Id=" + StudentId + "';", conn);
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
conn.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
lblStudentId.Text = Session["StudentId"].ToString();
txtFirstName.Text = myReader["FirstName"].ToString();
txtLastName.Text = myReader["LastName"].ToString();
if (RadioButtonList1.Items.FindByValue(myReader["level"].ToString()) != null)
{
RadioButtonList1.SelectedValue = myReader["level"].ToString();
}
if (RadioButtonList2.Items.FindByValue(myReader["LO_interested"].ToString()) != null)
{
RadioButtonList2.SelectedValue = myReader["LO_interested"].ToString();
}
}
conn.Close();
}
In Log In page i wrote this code:
if (ds.Tables[0].Rows.Count > 0)
{
Session["FirstName"] = ds.Tables[0].Rows[0]["FirstName"].ToString();
Session["LastName"] = ds.Tables[0].Rows[0]["LastName"].ToString();
Session["StudentId"] = ds.Tables[0].Rows[0]["S_Id"].ToString();
Session["level"] = ds.Tables[0].Rows[0]["level"].ToString();
Session["LO_interested"] = ds.Tables[0].Rows[0]["LO_interested"].ToString();
I have a table in my sql database called "usertype". My website has a registration form where the user will choose which type of user s/he is. So, what I want is that, when the user type of the person who logs in is User add, edit and delete buttons would be disable in the List of Faculty page of the website.
Click the link to see how my usertype table looks like:
http://i44.tinypic.com/2j34cau.jpg
And this is my code for Register.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Register : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(Helper.GetConnection());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetUserType();
}
}
void GetUserType()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ID, userType FROM type";
SqlDataReader dr = cmd.ExecuteReader();
ddlType.DataSource = dr;
ddlType.DataTextField = "userType";
ddlType.DataValueField = "ID";
ddlType.DataBind();
con.Close();
}
bool IsExisting(string email)
{
bool existing = true; //initial Value
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT userEmail FROM users WHERE userEmail = #userEmail";
cmd.Parameters.Add("userEmail", SqlDbType.VarChar).Value = email;
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows) // record (email Address) is existing
existing = true;
else //record is not existing
existing = false;
con.Close();
return existing;
}
protected void btnRegister_Click(object sender, EventArgs e)
{
if (!IsExisting(txtEmail.Text)) //if email not existing
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO users VALUES (#TypeID, #userFN, #userLN, #userEmail, #userPassword, #userAddress, #userContact, #userCourse, #userSection, #userSchool)";
cmd.Parameters.Add("#TypeID", SqlDbType.Int).Value = ddlType.SelectedValue;
cmd.Parameters.Add("#userFN", SqlDbType.VarChar).Value = txtFN.Text;
cmd.Parameters.Add("#userLN", SqlDbType.VarChar).Value = txtLN.Text;
cmd.Parameters.Add("#userEmail", SqlDbType.VarChar).Value = txtEmail.Text;
cmd.Parameters.Add("#userPassword", SqlDbType.VarChar).Value = Helper.CreateSHAHash(txtPassword.Text);
cmd.Parameters.Add("#userAddress", SqlDbType.VarChar).Value = "";
cmd.Parameters.Add("#userContact", SqlDbType.VarChar).Value = "";
cmd.Parameters.Add("#userCourse", SqlDbType.VarChar).Value = "";
cmd.Parameters.Add("#userSection", SqlDbType.VarChar).Value = "";
cmd.Parameters.Add("#userSchool", SqlDbType.VarChar).Value = "";
cmd.ExecuteNonQuery();
con.Close();
string message = "Hello, " + txtFN.Text + " " + txtLN.Text + "! <br />"
+ "<br />You have successfully registered in our website. <br />" + "<br /> Click <a href = 'http://localhost:7773/PROJECT%20%5BWB-DEV1%5D/Login.aspx'>" + "here</a> to login <br /> <br />" + "Regards, <br /> " + "The Administrator";
Helper.SendEmail(txtEmail.Text, "Registered Successfully", message);
Response.Redirect("Login.aspx");
}
else //error existing
{
error.Visible = true;
}
}
}
This is the Faculty.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Faculty : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(Helper.GetConnection());
protected void Page_Load(object sender, EventArgs e)
{
GetProfessor();
}
void GetProfessor()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ProfNo, SchoolID, LastName, FirstName, MI, " +
"Address, ContactNo, EmailAddress FROM Professor";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Professor");
gvProfessor.DataSource = ds;
gvProfessor.DataBind();
con.Close();
}
protected void gvProfessor_SelectedIndexChanged(object sender, EventArgs e)
{
btnEdit.Visible = true;
btnDelete.Visible = true;
btnAdd.Visible = true;
}
protected void btnDelete_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "DELETE FROM Professor WHERE ProfNo=#ProfNo";
cmd.Parameters.Add("#ProfNo", SqlDbType.Int).Value =
gvProfessor.SelectedRow.Cells[0].Text;
cmd.ExecuteNonQuery();
con.Close();
GetProfessor();
}
protected void btnEdit_Click(object sender, EventArgs e)
{
Session["ID"] = gvProfessor.SelectedRow.Cells[0].Text;
Response.Redirect("EditFaculty.aspx");
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Response.Redirect("AddFaculty.aspx");
}
}
The btnAdd, btnEdit, btnDelete should be disable when its a User, and should be enabled when its an Admin.
I'm new to this and I hope you can help me. Thanks!
Since you didn't provide any code, all I can give you is pseudo-code:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// If the user type doesn't equal user, they're enabled
btnAdd.Enabled = user.Type != "User";
btnEdit.Enabled = user.Type != "User";
btnDelete.Enabled = user.Type != "User";
}
}
If your user types are stored in the database as IDs, the best way to handle this is to create an enum whose values match the IDs in your database. The enum would look like this.
public enum UserType
{
Unknown = 0,
Admin = 1,
User = 2
}
Then, your code would look similar to this.
protected void Page_Load(object sender, EventArgs e)
{
SetButtonsEnabledDisabled(IsAdmin(userType));
}
private bool IsAdmin(int userTypeId)
{
return userTypeId == (int)UserType.Admin;
}
private void SetButtonsEnabledDisabled(bool isEnabled)
{
ButtonAdd.Enabled = isEnabled;
ButtonEdit.Enabled = isEnabled;
ButtonDelete.Enabled = isEnabled;
}
It's a good idea to store your IDs in an enum, if for no other reason than to increase the readability of your code. In Faculty.aspx.cs, you need to do a check on your currently logged in user. Whether you're passing some value through a query string, or doing an extra database call, I'm not going to architect it for you. But once you have that context, you can apply that to enable or disable your buttons.
Another thing to note is it's always a BAD idea to put data layer code in your code behind. Have a look at this SO answer for reasons why. https://stackoverflow.com/a/5318242/1717855
i am trying to make a windows form to log into another one,
i am using a database with users and passwords
the code is as follows:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=mmtsql.XXX.XXXX.XX.XX;Initial Catalog=mmtXX-XXX;User ID=mmtXX-XXX;Password=mmtXX-XXX");
conn.Open();
SqlCommand mycommand = new SqlCommand("SELECT User, Password FROM UsersData WHERE User = '" + textBox1.Text + "' and Password = '" + textBox2.Text + "'", conn);
SqlDataReader reader = mycommand.ExecuteReader();
if(reader != null)
{
if(reader.Read())
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}
else
{
label3.Text = "Invalid Username or Password !";
}
the problem that a getting is that no matter what i insert into the textboxes, right or wrong i am getting:
Invalid Username or Password !
is there anyway to fix my code?
regards;
I would do it this way, keeping to the method you are using:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(conn_str);
conn.Open();
string sql = "SELECT User, Password
FROM UsersData WHERE User=#user and Password=#password"
SqlCommand mycommand = new SqlCommand(sql, conn);
//parameterize your query!
mycommand.Parameters.AddWithValue("user", txtuser.text);
mycommand.Parameters.AddWithValuye("password", txtpassword.password);
SqlDataReader reader = mycommand.ExecuteReader();
if(reader == null)
{
label3.Text = "Database query failed!";
}
else if(reader.HasRows)
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
Use parameterized queries as they will help you against sql injection as mentioned by SLaks.
Change your code to below
using (SqlCommand command = new SqlCommand("SELECT User, Password
FROM UsersData WHERE User=#user and Password=#password", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("user ", textbox1.text));
command.Parameters.Add(new SqlParameter("password", textbox2.text));
SqlDataReader reader = command.ExecuteReader();
if (reader == null)
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}