unable to update profile picture using varbinary - c#

I'm trying to update my profile picture using varbinary (SQL Server 2008). It don't seem to update the picture that I put in the fileupload. Below is the code I use to update my profile picture. Do help me take a look on which part of my coding did I do wrongly.
Thanks.
protected void btnUpload_Click(object sender, EventArgs e)
{
String username = (String)Session["username"];
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
switch (ext)
{
case ".jpg":
contenttype = "image/jpg";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "Update LoginRegisterOthers Set profilepic = #Data Where username = '" + username + "'";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "Profile Updated.";
Response.Redirect("MemberProfile.aspx");
}
else if (contenttype == String.Empty)
{
lblMessage.Text = "Please select your image before uploading!";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised." + " Upload Image formats";
}
}
private Boolean InsertUpdateData(SqlCommand cmd)
{
SqlConnection con = new SqlConnection("Data Source=localhost; Initial Catalog=project; Integrated Security=True");
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}

try this:
...
//insert the file into database
string strQuery = "Update LoginRegisterOthers Set profilepic = (SELECT BULKCOLUMN FROM OPENROWSET(BULK N'"+filename+"', SINGLE_BLOB) AS FIle_picture) Where username = '" + username + "'";
...
You can load a file directly with sql.

Related

textBox3 specific key to make accounts

I am coding an Application with my friend and I am having some trouble figuring out how to make the 3rd textbox contain a certain word/key to continue in order to make the account
Here is what the form looks like
Then here is the entire code for the database part of where it creates the account.
private void button5_Click(object sender, EventArgs e)
{
if (!textBox1.Text.Equals("") && !textBox2.Text.Equals("") && textBox2.Text.Equals(textBox3.Text))
{
StringBuilder sb = new StringBuilder();
using (SHA256 hash = SHA256Managed.Create())
{
Encoding enc = Encoding.UTF8;
Byte[] result = hash.ComputeHash(enc.GetBytes(textBox2.Text));
foreach (Byte b in result)
{
sb.Append(b.ToString("x2"));
}
}
string connectionString = "datasource=127.0.0.1;port=3306;username=root;password=;database=majorpayne;";
string query = "INSERT INTO staff(USERNAME, PASSWORD) VALUES('" + textBox1.Text + "', '" + sb.ToString() + "')";
string query2 = "SELECT * FROM staff WHERE username='" + textBox1.Text + "' AND password='" + sb.ToString() + "'";
MySqlConnection con = new MySqlConnection(connectionString);
MySqlConnection databaseConnection = new MySqlConnection(connectionString);
MySqlCommand insertCommand = new MySqlCommand(query, databaseConnection);
MySqlCommand checkCommand = new MySqlCommand(query2, databaseConnection);
MySqlDataReader reader;
try
{
databaseConnection.Open();
reader = insertCommand.ExecuteReader();
reader.Close();
reader = checkCommand.ExecuteReader();
if (reader.HasRows)
{
MessageBox.Show("Successfully Created Account.");
{
Login main = new Login();
main.Show();
this.Hide();
}
}
else
{
MessageBox.Show("Database Error (404)");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
}
If anyone can help make a way where the textBox3 equals a specific word thanks in advance.
And for a short explanation, I want the textBox3 to have a "key" in it that checks if the key is the exact key and if the correct key is there, it goes on and creates the account with the user/pass that was entered.
you can add label Under textBox3 Then on textBox3_KeyUp Event Write your Code Like This
private void textBox3_KeyUp(object sender, KeyEventArgs e)
{
if (textBox1.Text == "Your Key")
{
label1.Text = "correct key";
label1.ForeColor = System.Drawing.Color.Green;
}
else
{
label1.Text = "wrong key";
label1.ForeColor = System.Drawing.Color.Red;
}
}

When uploading file in Visual Studio Development works but not when the website has been published

I have a page where the user the can upload a csv file, this will then be saved in the database and displayed in in a gridview. This all works fine when developing the site, but when I publish the site to IIS and access it externally it gives and error of "500 internal server error" When trying to uplaod the file
This is the code I am using to upload the files:
private string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["OfficeConnection"].ConnectionString;
}
private void CreateDatabaseTable(DataTable dt, string tableName)
{
string sqlQuery = string.Empty;
string sqlDBType = string.Empty;
string dataType = string.Empty;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("CREATE TABLE {0} (", tableName));
for (int i = 0; i < dt.Columns.Count; i++)
{
int maxLength = 0;
dataType = dt.Columns[i].DataType.ToString();
if (dataType == "System.Int32")
{
sqlDBType = "INT";
}
else if (dataType == "System.String")
{
sqlDBType = "NVARCHAR";
maxLength = dt.Columns[i].MaxLength;
}
else
{
//do something else
}
if (maxLength > 0)
sb.AppendFormat(string.Format("{0} {1} ({2}), ", dt.Columns[i].ColumnName, sqlDBType, maxLength));
else
sb.AppendFormat(string.Format("{0} {1},", dt.Columns[i].ColumnName, sqlDBType));
}
sqlQuery = sb.ToString();
sqlQuery = sqlQuery.Trim().TrimEnd(',');
sqlQuery = sqlQuery + " )";
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
using (SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn))
{
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
}
private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter)
{
string sqlQuery = string.Empty;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("BULK INSERT {0} ", tableName));
sb.AppendFormat(string.Format(" FROM '{0}'", fileFullPath));
sb.AppendFormat(string.Format(" WITH ( FIELDTERMINATOR = '{0}' , ROWTERMINATOR = '\n' )", delimeter));
sqlQuery = sb.ToString();
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
using (SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn))
{
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
}
private void UploadAndProcessFile()
{
if (FileUpload1.HasFile)
{
FileInfo fileInfo = new FileInfo(FileUpload1.PostedFile.FileName);
if (fileInfo.Name.Contains(".csv"))
{
string fileName = fileInfo.Name.Replace(".csv", "").ToString();
string csvFilePath = Server.MapPath("UploadedCSVFiles") + "\\" + fileInfo.Name;
//Save the CSV file in the Server inside 'UploadedCSVFiles'
FileUpload1.SaveAs(csvFilePath);
//Fetch the location of CSV file
string filePath = Server.MapPath("UploadedCSVFiles") + "\\";
string strSql = string.Format("SELECT * FROM [{0}]", fileInfo.Name);
string strCSVConnString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='text;HDR=YES;'", filePath);
// load the data from CSV to DataTable
DataTable dtCSV = new DataTable();
DataTable dtSchema = new DataTable();
using (OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, strCSVConnString))
{
adapter.FillSchema(dtCSV, SchemaType.Mapped);
adapter.Fill(dtCSV);
}
if (dtCSV.Rows.Count > 0)
{
CreateDatabaseTable(dtCSV, fileName);
Label2.Text = string.Format("The table ({0}) has been successfully created to the database.", fileName);
string fileFullPath = filePath + fileInfo.Name;
LoadDataToDatabase(fileName, fileFullPath, ",");
Label1.Text = string.Format("({0}) records has been loaded to the table {1}.", dtCSV.Rows.Count, fileName);
}
else
{
lblError.Text = "File is empty.";
}
}
else
{
lblError.Text = "Unable to recognize file.";
}
}
}
protected void btnImport_Click(object sender, EventArgs e)
{
UploadAndProcessFile();
}
Is this a setting in IIS I need to change? I have checked the permission on the site and all is fine.
Thanks

Loop through multiple files in temp directory and insert files into MS SQL database with existing rows/id's

I have a SQL database with existing rows and attachment ID's. I have a folder of several thousand PDF files that need to be inserted into this database. The files should be inserted in each row based on filename/column.
Example. One file is called 123.pdf that should be inserted in the row with the ID of 123.
I have created an Asp.net web forms application using the Ajax File Upload tool. It works fine if I use a real directory. How can I do this with a temporary Directory?
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
try
{
string filePath = e.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
switch (ext)
{
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
string tempPath = System.IO.Path.GetTempFileName();
AjaxFileUpload1.SaveAs(tempPath);
using (FileStream fs = File.OpenRead(tempPath))
{
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//How do I create a temp directory of the files in the AjaxFileUploader?
var dir = new DirectoryInfo(CreateTempDirectoryHere);
FileInfo[] pdfFiles = dir.GetFiles();
foreach (FileInfo pdfFile in pdfFiles)
{
var attachmentID = Path.GetFileNameWithoutExtension(pdfFile.ToString());
string constr = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("dbo.spUploadContentBulk", con);
cmd.Parameters.AddWithValue("#AttachmentID", attachmentID);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#FileName",
Value = filename
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#FileContent",
Value = bytes
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#FileType",
Value = contenttype
});
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
File.Delete(tempPath);
}
}
catch (Exception ex)
{
txtError.Text = ex.ToString();
}
}
I mean something more like this (don't even use a temp folder):
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
try
{
string filename = e.FileName;
var bytes = e.GetContents();
var attachmentID = Path.GetFileNameWithoutExtension(fileName);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
switch (ext)
{
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
string constr = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("dbo.spUploadContentBulk", con);
cmd.Parameters.AddWithValue("#AttachmentID", attachmentID);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#FileName",
Value = filename
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#FileContent",
Value = bytes
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#FileType",
Value = contenttype
});
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
catch (Exception ex)
{
txtError.Text = ex.ToString();
}
}

Change Password issues in ASP.Net

Hi i'm trying to changing the password so the user's password is update on the database. For example, i want the user Mary Tan's password to be changed from 12345 to 54321. But if affect the rest of the user's password. I really idk how to fix it.
Output:
click here
Table
database table
My Code:
protected void btnChangePassword_Click(object sender, EventArgs e)
{
SqlDataReader dr = null;
connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
conn = new SqlConnection(connectionString);
string sql = "UPDATE Staff Set Password=#NewPwd";
if (Session["Username"] != null)
{
sql += " WHERE UserName='" + Session["Username"].ToString() + "'";
}
string newPwd = tbNewPassword.Text;
try
{
cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#NewPwd", tbNewPassword.Text);
conn.Open();
dr = cmd.ExecuteReader();
while(dr.Read())
{
if ((tbNewPassword.Text == dr["newPwd"].ToString()))
{
}
}
dr.Close();
int rows = cmd.ExecuteNonQuery();
if(rows > 0)
{
lblOutput.ForeColor = System.Drawing.Color.Green;
lblOutput.Text = "Password has been changed successfully";
}
else
{
lblOutput.ForeColor = System.Drawing.Color.Red;
lblOutput.Text = "Password does not match with our database records.";
}
}
catch(Exception ex)
{
lblOutput.Text = "Error Message: " + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
}
Which means your Session["Username"] is null at this moment of execution. Hence the Where condition will skip and update all rows. And What is the Function of Reader There? It is not necessary, The ExecuteNonQuery is enough to do this Job and it will returns the number of rows affected. So you can do this in the following way:
string connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
if (Session["Username"] != null)
{
string sql = "UPDATE Staff Set Password=#NewPwd WHERE UserName=#Username";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#NewPwd", tbNewPassword.Text);
cmd.Parameters.AddWithValue("#Username", Session["Username"]);
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
lblOutput.ForeColor = System.Drawing.Color.Green;
lblOutput.Text = "Password has been changed successfully";
}
else
{
lblOutput.ForeColor = System.Drawing.Color.Red;
lblOutput.Text = "Password does not match with our database records.";
}
}
}
}
else
{
// Show message that Session is Empty Can't Proceed
}
Important Note :- Don't save password as plain Text, Hash and salt them
Change your method like this (check Session in the start)
protected void btnChangePassword_Click(object sender, EventArgs e)
{
if (Session["Username"] == null)
{
//User is not logged-in. Display message or handle
return;
}
SqlDataReader dr = null;
connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
conn = new SqlConnection(connectionString);
string sql = "UPDATE Staff Set Password=#NewPwd Where UserName = #UserName";
string newPwd = tbNewPassword.Text;
try
{
cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#NewPwd", tbNewPassword.Text);
cmd.Parameters.AddWithValue("#UserName", Session["Username"].ToString());
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
if ((tbNewPassword.Text == dr["newPwd"].ToString()))
{
}
}
dr.Close();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
lblOutput.ForeColor = System.Drawing.Color.Green;
lblOutput.Text = "Password has been changed successfully";
}
else
{
lblOutput.ForeColor = System.Drawing.Color.Red;
lblOutput.Text = "Password does not match with our database records.";
}
}
catch (Exception ex)
{
lblOutput.Text = "Error Message: " + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
}

How to retrieve image from oracle database?

I want to retrieve image from oracle database
and show it in Image control I tried but it is showing empty image
Code for Insert Image:
protected void btnUpload_Click(object sender, EventArgs e)
{
int imgLength = 0;
string imgContentType = null;
string imgFileName = null;
Stream imgStream = FileUpload.PostedFile.InputStream;
imgLength = FileUpload.PostedFile.ContentLength;
imgContentType = FileUpload.PostedFile.ContentType;
imgFileName = FileUpload.PostedFile.FileName;
if (imgContentType == "image/jpeg" || imgContentType == "image/gif" ||
imgContentType == "image/pjpeg"
|| imgContentType == "image/bmp")
{
OracleConnection DbConnection = new OracleConnection(con1);
DbConnection.Open();
FileStream fls;
fls = new FileStream(#imgFileName, FileMode.Open, FileAccess.Read);
byte[] blob = new byte[fls.Length];
fls.Read(blob, 0, System.Convert.ToInt32(fls.Length));
fls.Close();
string query = "insert into image(id,name,photo) values(1,'" + imgFileName + "'," + " :BlobParameter )";
// Establish a new OracleCommand
OracleCommand cmd = new OracleCommand();
cmd.CommandText = query;
cmd.Connection = DbConnection;
cmd.CommandType = CommandType.Text;
System.Data.OracleClient.OracleParameter paramImage = new System.Data.OracleClient.OracleParameter("image",
Oracle.DataAccess.Client.OracleDbType.Blob);
paramImage.ParameterName = "BlobParameter";
paramImage.Value = blob;
paramImage.Direction = ParameterDirection.Input;
cmd.Parameters.Add(paramImage);
cmd.ExecuteNonQuery();
}
}
Table:
Id Name Photo
1 C:\Document\Image\Ocean.jpeg (BLOB)
In the below code I'm trying to retrieve and show that image in image control
but it's not working
Code for retrieve:
void GetImagesFromDatabase()
{
try
{
OracleConnection DbConnection = new OracleConnection(con1);
DbConnection.Open();
OracleCommand cmd = new OracleCommand("Select name from Image", DbConnection);
OracleDataReader oda = cmd.ExecuteReader();
while (oda.Read())
{
string path = oda[0].ToString();
img.ImageUrl = path;
}
}
catch (Exception ex)
{
}
}
Any ideas? Thanks in advance

Categories