How to do if/else statement for fileUpload - c#

Heyy all. I am trying to do an if/else statement for my fileupload function on my Edit Profile page in my ASP.net webpage.
Here is my code:
protected void btnContinue_Click(object sender, EventArgs e)
{
//Declaration of variable to update Profile Image
string imageName, newContact;
imageName = FileUpload1.FileName.ToString();
newContact = tbMobile.Text.ToString();
username = (String)Session["NonAdmin"];
MySqlConnection mcon = new MySqlConnection("server=182.50.133.91;user id=Jonathan;password=jon123;persistsecurityinfo=True;database=ajactrac_;allowuservariables=True");
MySqlDataAdapter sda = new MySqlDataAdapter("select * from pointofcontact where Username = '" + username.ToString() + "'", mcon);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count.ToString() == "1")
{
MySqlCommand command = mcon.CreateCommand();
MySqlCommand command1 = mcon.CreateCommand();
MySqlCommand command2 = mcon.CreateCommand();
MySqlCommand command3 = mcon.CreateCommand();
MySqlCommand command4 = mcon.CreateCommand();
MySqlCommand command5 = mcon.CreateCommand();
MySqlCommand command6 = mcon.CreateCommand();
MySqlCommand command7 = mcon.CreateCommand();
command.CommandText = "update pointofcontact set Password = ?pwd where Username = '" + username.ToString() + "'";
command1.CommandText = "update pointofcontact set FirstName = ?firstname where Username = '" + username.ToString() + "'";
command2.CommandText = "update pointofcontact set LastName = ?lastname where Username = '" + username.ToString() + "'";
command3.CommandText = "update pointofcontact set ContactNumber = ?contact where Username = '" + username.ToString() + "'";
command4.CommandText = "update pointofcontact set EmailAddress = ?email where Username = '" + username.ToString() + "'";
command5.CommandText = "update pointofcontact set Address = ?address where Username = '" + username.ToString() + "'";
command6.CommandText = "update pointofcontact set BackupContactNumber = ?backupnumber where Username = '" + username.ToString() + "'";
command7.CommandText = "update pointofcontact set ProfilePic = ?newimage where Username = '" + username.ToString() + "'";
mcon.Open();
if (tbNewPassword.Text == "")
{
command.Parameters.AddWithValue("?pwd", tbOldPassword.Text.Trim());
}
else
{
command.Parameters.AddWithValue("?pwd", tbNewPassword.Text.Trim());
}
if(tbNewFirstName.Text == "")
{
command1.Parameters.AddWithValue("?firstname", tbFirstName.Text.Trim());
}
else
{
command1.Parameters.AddWithValue("?firstname", tbNewFirstName.Text.Trim());
}
if(tbNewLastName.Text == "")
{
command2.Parameters.AddWithValue("?lastname", tbLastName.Text.Trim());
}
else
{
command2.Parameters.AddWithValue("?lastname", tbNewLastName.Text.Trim());
}
if(tbNewContact.Text == "")
{
command3.Parameters.AddWithValue("?contact", tbMobile.Text.Trim());
}
else
{
command3.Parameters.AddWithValue("?contact", tbNewContact.Text.Trim());
}
if(tbNewEmail.Text == "")
{
command4.Parameters.AddWithValue("?email", tbEmail.Text.Trim());
}
else
{
command4.Parameters.AddWithValue("?email", tbNewEmail.Text.Trim());
}
if(tbNewAddress.Text == "")
{
command5.Parameters.AddWithValue("?address", tbAddress.Text.Trim());
}
else
{
command5.Parameters.AddWithValue("?address", tbNewAddress.Text.Trim());
}
if(tbNewBackupContact.Text == "")
{
command6.Parameters.AddWithValue("?backupnumber", tbBackupContact.Text.Trim());
}
else
{
command6.Parameters.AddWithValue("?backupnumber", tbNewBackupContact.Text.Trim());
}
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + imageName);
command7.Parameters.AddWithValue("?newimage", imageName);
command.ExecuteNonQuery();
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
command3.ExecuteNonQuery();
command4.ExecuteNonQuery();
command5.ExecuteNonQuery();
command6.ExecuteNonQuery();
command7.ExecuteNonQuery();
mcon.Close();
string javaScript = "<script language=JavaScript>\n" + "alert('Profile Updated!');\n" + "</script>";
RegisterStartupScript("xyz", javaScript);
}
else
{
string javaScript = "<script language=JavaScript>\n" + "alert('Some Error Occured! Profile Not Updated!');\n" + "</script>";
RegisterStartupScript("xyz", javaScript);
}
tbNewPassword.Text = "";
}
I had planned to use the if else statement for my fileupload function such that if the user has not uploaded a new picture, he/she would be still able to update their profile.
Currently when I try to edit a user's profile, this error message comes out.

Before uploading files to any directory, it is good to have this statement before saving file.
if (!Directory.Exists(Server.MapPath("~/Images")))
Directory.CreateDirectory("~/Images");
add above statement before this line
FileUpload1.PostedFile.SaveAs(Server.MapPath(Path.Combine("~/Images", imageName)));

Related

ASP.NET C# - Edit Account Page INSERT and UPDATE data

I'm not a strong coder and quite new to C#. I am having problems with the edit account page of the website that I am trying to create. I am trying to update and insert data into the database and they don't seem to work.
Here's my code:
public partial class EditAccount : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");
private readonly object MessageBox;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlCommand com;
string str;
conn.Open();
str = "SELECT Address.HouseNumber, Address.AddressLine1, Address.AddressLine2, Address.City, Address.PostCode, CardDetails.CardDetailsID, CardDetails.NameOnCard, CardDetails.NameOfCard, CardDetails.CardNumber, CardDetails.CardExpiryDate, CardDetails.CVV, AddressType.AddressTypeDescription, Member.MemberID, Member.MemberName, Member.Phone, Member.Email, Member.Username FROM Address FULL JOIN AddressType ON Address.AddressTypeID = AddressType.AddressTypeID FULL JOIN Member ON AddressType.MemberID = Member.MemberID FULL JOIN CardDetails ON Member.MemberID = CardDetails.MemberID WHERE Member.Email = '" + Session["Email"] + "'";
com = new SqlCommand(str, conn);
SqlDataReader reader = com.ExecuteReader();
if (reader.Read())
{
TxtEName.Text = reader["MemberName"].ToString();
LblEUser.Text = reader["Username"].ToString();
TxtEEmail.Text = reader["Email"].ToString();
TxtEPhone.Text = reader["Phone"].ToString();
TxtEType.Text = reader["AddressTypeDescription"].ToString();
TxtEHouse.Text = reader["HouseNumber"].ToString();
TxtEA1.Text = reader["AddressLine1"].ToString();
TxtEA2.Text = reader["AddressLine2"].ToString();
TxtECity.Text = reader["City"].ToString();
TxtEPostcode.Text = reader["PostCode"].ToString();
TxtENameOf.Text = reader["NameOfCard"].ToString();
TxtENameOn.Text = reader["NameOnCard"].ToString();
TxtECardNo.Text = reader["CardNumber"].ToString();
TxtEExpDate.Text = reader["CardExpiryDate"].ToString();
TxtECVV.Text = reader["CVV"].ToString();
reader.Close();
conn.Close();
}
}
}
protected void BtnSave_Click(object sender, EventArgs e)
{
conn.Open();
SqlDataAdapter str = new SqlDataAdapter ("SELECT Address.HouseNumber, Address.AddressLine1, Address.AddressLine2, Address.City, Address.PostCode, CardDetails.NameOnCard, CardDetails.NameOfCard, CardDetails.CardNumber, CardDetails.CardExpiryDate, CardDetails.CVV, AddressType.AddressTypeDescription, Member.MemberName, Member.Phone, Member.Email, Member.Username FROM Address FULL JOIN AddressType ON Address.AddressTypeID = AddressType.AddressTypeID FULL JOIN Member ON AddressType.MemberID = Member.MemberID FULL JOIN CardDetails ON Member.MemberID = CardDetails.MemberID WHERE Member.Email = '" + Session["Email"] + "'",conn);
DataSet ds = new DataSet();
str.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
SqlCommand updateCommand = new SqlCommand("UPDATE Member SET MemberName = '" + TxtEName.Text + "', Email = '" + TxtEEmail.Text + "', Phone = '" + TxtEPhone.Text + "'", conn);
SqlCommand updateCommand1 = new SqlCommand("UPDATE Address SET HouseNumber ='" + TxtEHouse.Text + "', AddressLine1 = '" + TxtEA1.Text + "', AddressLine2 = '" + TxtEA2.Text + "', City = '" + TxtECity.Text + "',PostCode = '" + TxtEPostcode.Text + "'", conn);
SqlCommand updateCommand2 = new SqlCommand("UPDATE AddressType SET AddressTypeDescription = '" + TxtEType.Text + "'", conn);
SqlCommand updateCommand3 = new SqlCommand("UPDATE CardDetails SET NameOnCard = '" + TxtENameOn.Text + "', NameOfCard = '" + TxtENameOf.Text + "', CardNumber = '" + TxtECardNo.Text + "', CardExpiryDate = '" + TxtEExpDate.Text + "', CVV = '" + TxtECVV.Text + "'", conn);
updateCommand.ExecuteNonQuery();
updateCommand1.ExecuteNonQuery();
updateCommand2.ExecuteNonQuery();
updateCommand3.ExecuteNonQuery();
Response.Write("<script>alert('Changes saved')</script>");
}
else
{
SqlCommand insertCommand = new SqlCommand("INSERT INTO AddressType (AddressTypeDescription) VALUES (#AddressTypeDescription)", conn);
insertCommand.Parameters.AddWithValue("#AddressTypeDescription", TxtEType.Text);
insertCommand.ExecuteNonQuery();
SqlCommand insertCommand1 = new SqlCommand("INSERT INTO Address (HouseNumber, AddressLine1, AddressLine2, City, PostCode) VALUES (#HouseNumber, #AddressLine1, #AddressLine2, #City, #PostCode)", conn);
insertCommand1.Parameters.AddWithValue("#HouseNumber", TxtEHouse.Text);
insertCommand1.Parameters.AddWithValue("#AddressLine1", TxtEA1.Text);
insertCommand1.Parameters.AddWithValue("#AddressLine2", TxtEA2.Text);
insertCommand1.Parameters.AddWithValue("#City", TxtECity.Text);
insertCommand1.Parameters.AddWithValue("#PostCode", TxtEPostcode.Text);
insertCommand1.ExecuteNonQuery();
SqlCommand insertCommand2 = new SqlCommand("INSERT INTO CardDetails (NameOnCard, NameOfCard, CardNumber, CardExpiryDate, CVV) VALUES (#NameOnCard, #NameOfCard, #CardNumber, #CardExpiryDate, #CVV)", conn);
insertCommand2.Parameters.AddWithValue("#NameOnCard", TxtENameOn.Text);
insertCommand2.Parameters.AddWithValue("#NameOfCard", TxtENameOf.Text);
insertCommand2.Parameters.AddWithValue("#CardNumber", TxtECardNo.Text);
insertCommand2.Parameters.AddWithValue("#CardExpiryDate", TxtEExpDate.Text);
insertCommand2.Parameters.AddWithValue("#CVV", TxtECVV.Text);
insertCommand2.ExecuteNonQuery();
Response.Write("<script>alert('Changes saved')</script>");
}
conn.Close();
}
}

C# ODBC mysql (null output)

can anyone help me? i am getting null output. though data exists in database.
string retrivenp = "select emp_email from E_details where emp_ID ='" + c_c +
"'AND emp_name = '" + s_s + "'AND emp_address = '" + n_n +
"'AND Date_joining = '" + Calendar1.SelectedDate + "'";
using (OdbcCommand comm1 = new OdbcCommand(retrivenp,con))
{
using (OdbcDataReader read = comm1.ExecuteReader())
{
while(read.Read())
{
url_path = read.ToString();
Label1.Text = url_path.ToString();
}
}
}
i think the string with many quotes is the problem when it will be executed it may give the wrong query
use command parameters it's better
string retrivenp = "select emp_email from E_details where emp_ID = ? AND emp_name = ? AND emp_address = ? AND Date_joining = ?";
using (OdbcCommand comm1 = new OdbcCommand(retrivenp,con))
{
comm1.Parameters.Add("#p1", OleDbType.Int).Value = c_c;
comm1.Parameters.Add("#p2", OleDbType.Text).Value = s_s;
comm1.Parameters.Add("#p3", OleDbType.Text).Value = n_n;
comm1.Parameters.Add("#p4", OleDbType.Date).Value = Calendar1.SelectedDate;
using (OdbcDataReader read = comm1.ExecuteReader())
{
while(read.Read())
{
url_path = read.GetString(0);
Label1.Text = url_path.ToString();
}
read.Close();
}
}

Insert and Update syntax error on Database / Datagrid

Here is my button command for save.
need help in getting this to work, will be getting this to defend for tomorrow school project.
Thanks!
Its for Datagridview, access, c#.
I use 2010VS and MS Access 2007.
private void save_Click(object sender, EventArgs e)
{
if (adminyes.Checked == true || adminno.Checked == true && textBox1.Text != null && textBox2.Text != null && textBox3.Text != null)
{
admin = "Yes";
if (mode == "a")
{
x = 0;
connect.Close();
connect.ConnectionString = inventorydb;
connect.Open();
sqlcommand.CommandText = "SELECT * FROM Users WHERE Username ='" +textBox2.Text+ "' Or User_ID ='" +textBox1.Text+ "' ";
sqlcommand.Connection = connect;
OleDbDataReader reader = sqlcommand.ExecuteReader();
while (reader.Read())
{
x++;
}
if (x != 0)
{
MessageBox.Show("", "",MessageBoxButtons.OK);
}
else
{
DialogResult res = MessageBox.Show("Are you sure?", "Save User", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (DialogResult.Yes == res)
{
connect.Close();
connect.ConnectionString = inventorydb;
connect.Open();
sqlcommand.CommandText = "INSERT INTO Users (User_ID, Username, Password, Admin) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "', '" + textBox3.Text + "', '" + admin + "') ";
sqlcommand.Connection = connect;
reader = sqlcommand.ExecuteReader();
MessageBox.Show("Record(s) Saved", "Sample");
}
reset();
}
}
else if (mode == "e")
{
DialogResult res = MessageBox.Show("Are you sure?", "Update User", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (DialogResult.Yes == res)
{
connect.Close();
connect.ConnectionString = inventorydb;
connect.Open();
sqlcommand.CommandText = "UPDATE Users SET User_ID = '" + textBox1.Text + "', Username = '" + textBox2.Text + "', Password = '" + textBox3.Text + "',Admin = '" + admin + "' WHERE SerialID = '" + idholder + "' ";
sqlcommand.Connection = connect;
OleDbDataReader reader = sqlcommand.ExecuteReader();
reader.Read();
MessageBox.Show("Record(s) Updated", "Sample");
}
reset();
}
}
else
{
MessageBox.Show("", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Password is a reserved word in Access. Change it to [Password] in your SQL queries. You should wrap all columns and tables like this.
Although this is just a school project I'll mention a few things:
Your code is vulnerable to SQL injection. Here's how to fix this for your insert method as an example:
sqlcommand.CommandText = "INSERT INTO [Users] ([User_ID], [Username], [Password], [Admin]) VALUES (#user_id, #username, #password, #admin)";
sqlcommand.Connection = connect;
sqlcommand.Parameters.AddWithValue("#user_id", textBox1.Text);
sqlcommand.Parameters.AddWithValue("#username", textBox2.Text);
sqlcommand.Parameters.AddWithValue("#password", textBox3.Text);
sqlcommand.Parameters.AddWithValue("#admin", admin);
reader = sqlcommand.ExecuteReader();
Also passwords shouldn't be stored in plain text. Look into password hashing and salting and how to approach it properly for more information.

Need to find ID number from database using string in c#

I need to get data from label which i had got back from previous page using Sessions from that label i need to use it to find ID for that data for example if Label contain word 'IT' it need to find its ID in database D_ID=5 code is given below
public partial class FinalFeedback1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetDataFromSession();
GetDID();
AddDynamicLabels();
}
public void GetDID()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader1 = null;
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
SqlCommand cmd1 = new SqlCommand(depart, connection);
myReader1 = cmd1.ExecuteReader(); // i am getting error here "Invalid column name 'IT'"
while (myReader1.Read())
{
Label9.Text = myReader1["D_ID"].ToString();
}
}
}
public void AddDynamicLabels()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader2 = null;
string CmdString = "Select Q_ID,Question_Data FROM QuestionTable where D_ID=" + Label9.Text + "";
SqlCommand cmd = new SqlCommand(CmdString, connection);
myReader2 = cmd.ExecuteReader();
while (myReader2.Read())
{
QID1.Text = myReader2["Q_ID"].ToString();
if (QID1.Text == ("1"))
{
Question1.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text ==("2"))
{
Question2.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("3"))
{
Question3.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("4"))
{
Question4.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("5"))
{
Question5.Text = myReader2["Question_Data"].ToString();
}
}
}
}
private void GetDataFromSession()
{
Label2.Text = Session["SNL"].ToString();
Label4.Text = Session["SNB"].ToString();
Label6.Text = Session["EMPID"].ToString();
Label8.Text = Session["DNAME"].ToString();
}
}
Change this line.
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
to this line
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
See the single quotes in the second line. Your string value is not in single quotes and this is the reason.
EDIT: Your code is open for SQL Injection Attack. You should use the SqlParameter instead of concatenating the query.
For More reading you can use this link:
http://www.w3schools.com/sql/sql_injection.asp
As simple as missing the quotations of your sql.
sql-> "where D_Name = 'somevalue'
... So the fix for your code would be
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
Change this line.
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
to
string depart = "select D_ID from Department where D_Name like '" + Label8.Text + "'";
or faster search
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
or for search similar string change to
string depart = "select D_ID from Department where D_Name like '%" + Label8.Text + "%'";

C# textbox to database - error: C# doesn't know my column name: username & password

My Visual Studio program doesn't know my column names.
Here is a picture of my table "tblAccount":
Here is a picture of my error message:
Here is my code:
public partial class frmInloggen : Form
{
SqlConnection loonberekening;
frmStartmenu startmenu;
string usernaam, wachtwoord, bevoegdheid;
int userID, wachtwoordID;
public frmInloggen()
{
InitializeComponent();
initialiseerDB();
startmenu = new frmStartmenu();
}
private void initialiseerDB()
{
loonberekening = new SqlConnection();
loonberekening.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\gip_stap_2\loonberekening.mdf;Integrated Security=True;Connect Timeout=30";
}
private void button1_Click(object sender, EventArgs e)
{
usernaam = txtGebruikersnaam.Text;
wachtwoord = txtPaswoord.Text;
SqlCommand scmdUsername, scmdWachtwoord, scmdBevoegdheid;
scmdUsername = new SqlCommand();
scmdWachtwoord = new SqlCommand();
scmdBevoegdheid = new SqlCommand();
scmdUsername.Connection = loonberekening;
scmdWachtwoord.Connection = loonberekening;
scmdBevoegdheid.Connection = loonberekening;
scmdUsername.CommandType = CommandType.Text;
scmdWachtwoord.CommandType = CommandType.Text;
scmdBevoegdheid.CommandType = CommandType.Text;
scmdUsername.CommandText = "SELECT id FROM tblAccount WHERE usernaam = \'" + usernaam + "\'";
scmdWachtwoord.CommandText = "SELECT id FROM tblAccount WHERE wachtwoord = \'" + wachtwoord + "\'";
bevoegdheid = Convert.ToString(scmdBevoegdheid);
scmdBevoegdheid.CommandText = "SELECT rechten FROM tblAccount WHERE bevoegdheid = \'" + userID + "\'";
loonberekening.Open();
userID = Convert.ToInt32(scmdUsername.ExecuteScalar());
wachtwoordID = Convert.ToInt32(scmdWachtwoord.ExecuteScalar());
loonberekening.Close();
if (userID == wachtwoordID && userID > 0 && wachtwoordID > 0)
{
startmenu.Show();
}
else
{
MessageBox.Show("Password & username is wrong");
}
}
}
Try adding the Initial Catalog to your connection string:
loonberekening.ConnectionString = #"Data Source=(LocalDB)\v11.0;Initial Catalog=<YOUR DATABASE NAME>;AttachDbFilename=E:\gip_stap_2\loonberekening.mdf;Integrated Security=True;Connect Timeout=30";
You shouldn't be escaping your single quotes...
Try
scmdUsername.CommandText = "SELECT id FROM tblAccount WHERE usernaam = '" + usernaam + "'";
scmdWachtwoord.CommandText = "SELECT id FROM tblAccount WHERE wachtwoord = '" + wachtwoord + "'";
bevoegdheid = Convert.ToString(scmdBevoegdheid);
scmdBevoegdheid.CommandText = "SELECT rechten FROM tblAccount WHERE bevoegdheid = '" + userID + "'";
instead of
scmdUsername.CommandText = "SELECT id FROM tblAccount WHERE usernaam = \'" + usernaam + "\'";
scmdWachtwoord.CommandText = "SELECT id FROM tblAccount WHERE wachtwoord = \'" + wachtwoord + "\'";
bevoegdheid = Convert.ToString(scmdBevoegdheid);
scmdBevoegdheid.CommandText = "SELECT rechten FROM tblAccount WHERE bevoegdheid = \'" + userID + "\'";

Categories

Resources