Suppose I have this method from one class:
private void btnChangeImage_Click(object sender, EventArgs e)
{
using (var openFileDialogForImgUser = new OpenFileDialog())
{
string location = null;
string fileName = null;
openFileDialogForImgUser.Filter = "Image Files (*.jpg, *.png, *.gif, *.bmp)|*.jpg; *.png; *.gif; *.bmp|All Files (*.*)|*.*"; // filtering only picture file types
var openFileResult = openFileDialogForImgUser.ShowDialog(); // show the file open dialog box
if (openFileResult == DialogResult.OK)
{
using (var formSaveImg = new FormSave())
{
var saveResult = formSaveImg.ShowDialog();
if (saveResult == DialogResult.Yes)
{
imgUser.Image = new Bitmap(openFileDialogForImgUser.FileName); //showing the image opened in the picturebox
location = openFileDialogForImgUser.FileName;
fileName = openFileDialogForImgUser.SafeFileName;
FileStream fs = new FileStream(location, FileMode.Open, FileAccess.Read); //Creating a filestream to open the image file
int fileLength = (int)fs.Length; // getting the length of the file in bytes
byte[] rawdata = new byte[fileLength]; // creating an array to store the image as bytes
fs.Read(rawdata, 0, (int)fileLength); // using the filestream and converting the image to bits and storing it in an array
MySQLOperations MySQLOperationsObj = new MySQLOperations("localhost", "root", "myPass");
MySQLOperationsObj.saveImage(rawdata);
fs.Close();
}
else
openFileDialogForImgUser.Dispose();
}
}
}
}
And this method from another class (MySQLOperations):
public void saveImage(byte[] rawdata)
{
try
{
string myConnectionString = "Data Source = " + server + "; User = " + user + "; Port = 3306; Password = " + password + ";";
MySqlConnection myConnection = new MySqlConnection(myConnectionString);
string currentUser = FormLogin.userID;
string useDataBaseCommand = "USE " + dbName + ";";
string updateTableCommand = "UPDATE tblUsers SET UserImage = #file WHERE Username = \'" + currentUser + "\';";
MySqlCommand myCommand = new MySqlCommand(useDataBaseCommand + updateTableCommand, myConnection);
myCommand.Parameters.AddWithValue("#file", rawdata);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
If I must, this is my constructor for the MySQLOperations class:
public MySQLOperations(string server, string user, string password)
{
this.server = server;
this.user = user;
this.password = password;
}
What I'm trying to do is save an image file (which the user selects through the open file dialog box) to the database. Problem is I get this error: "You have an error in your SQL syntax; check the manual that correponds to your MySQL server version for the right syntax to use near ';UPDATE tblUsers SET UserImage = _binary'?PNG ... (and so on with some random characters). So, I can't really save the file in the database. I would love to post a picture on how the error is seen at the MessageBox, but I guess my account is not given the privilege to do so yet.
I'm not really sure where the syntax error is in that. I'm thinking, it's in the #file - but that's just a guess. Your help would be very much appreciated.
And oh, the table column UserImage has a type of LONGBLOB.
Other things I'm interested to know about also:
Is it necessary that I add another column for my table to store the
size of the file (because I'm going to need to retrieve the file
to display the image later on)?
Is it okay that I used the using statement that way in the method
btnChangeImage_Click?
Thank you very much.
EDIT: Got the problem solved. Such a simple thing not given attention to. Thanks to everybody who tried to help. I'm still willing to hear your opinion on the questions at the bottom (those on bullets).
I think the problem is in the following line of code:
WHERE Username = \'" + currentUser + "\';"
It should change to the following one:
WHERE Username = " + currentUser;
Or better (to avoid sql injections) to the following one:
WHERE Username = #Username";
myCommand.Parameters.AddWithValue("#Username", currentUser);
Do not store binary files in a MySQL table. Instead, save it to disk and save path to PNG file to MySQL database. Also, use Christos advice to avoid SQL injections.
Related
My application successfully creates a new database utilising the following string:
SqlString = $"CREATE DATABASE {_databaseName} ON PRIMARY " +
$"(NAME = {_databaseName}_Data, " +
$"FILENAME = '{_filePath}', " +
"SIZE = 8192KB, MAXSIZE = UNLIMITED, FILEGROWTH = 10%) " +
$"LOG ON (NAME = {_databaseName}_Log, " +
$"FILENAME = '{_databasePathLdf}', " +
"SIZE = 8192KB, " +
"MAXSIZE = UNLIMITED, " +
"FILEGROWTH = 10%)";
ExecuteSqlQuery(#"server=.\SQLEXPRESS; Trusted_Connection = Yes", SqlString);
When I then try to reconnect to the database use the following connection string
internal string ConnectionString(String databaseName)
{
return $"Server =.\\SQLEXPRESS;Database={databaseName};Trusted_Connection=Yes;";
}
I get the following error
For clarity the connection strings both use Trusted_Connection = Yes and the owner and login are the same when creating and connecting to the database.
For further clarity I am utilising OpenFileDialog to navigate to the database to connect utilising the following:
internal string OpenFileDialog(String initialDirectory)
{
string filePath = "";
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = initialDirectory;
openFileDialog.Filter = "mdf Database file (*.mdf)|*.mdf";
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog.FileName;
}
}
return filePath;
}
The error occurs on the DialogResult.OK.
How can you utilise OpenFileDialog in this instance to return the file path of the database to connect to?
I am using SQL Server Express 2019 (v15.0.2070).
Thanks in advance for any assistance.
I'm making this website to download subtitles. Right now I have this function to upload:
using (StreamReader sr = new StreamReader(file.InputStream, Encoding.Default, true))
{
string line;
while ((line = sr.ReadLine()) != null)
{
srtContent += line + '\0';
}
}
SubtitleFile item = new SubtitleFile();
UpdateModel(item);
item.state = State.Edit;
item.SubtitleText = srtContent;
item.name = char.ToUpper(item.name[0]) + item.name.Substring(1);
repo.AddSubtitle(item);
repo.Save();
ModelState.Clear();
And this uploads the srtContent to a place in my databse called SubtitleText,
Now I somehow need to be able to download this again.
So far I only have a hyperlink to a View that I call Downloader,
But that's all I got so far for the downloader.
What I'm missing is a way to take the information of ID given and do some sort of streamwriter or something, and put the info back into a new file where it would be something like
Model.name + '.srt'
with all the same text as I originally copied.
Hopefully I made this understandable. All constructive help appriciated.
Given that the information is stored in a database, we're gonna use the System.Data.SqlClient namespace.
SqlConnection myConnection = new SqlConnection("your connection string");
myConnection.Open();
string id = "my_id";
string text;
string fileName;
SqlCommand query = new SqlCommand();
query.CommandText = "SELECT FileName, SubtitleText FROM Subtitles WHERE ID = '#id'";
query.Parameters.AddWithValue("#id", id);
query.Connection = myConnection;
SqlDataReader data = query.ExecuteReader();
while (data.Read()) {
text = (string)data["SubtitleText"];
fileName = (string)data["FileName"];
}
using (FileStream fs = File.Create(file + ".srt")) {
File.WriteAllText(file, text);
}
This is kind of bad code but it roughly gives the idea of what you can do to achieve your goal (As i understood it*). If the ID is int, you can change it to that.
Addendum: English is not my first language so excuse the mistakes.
Hello I have saved an image in my database field and want to display that image in my crystal report viewer but unable to figure out how to perform it? Any help or suggestion will be very helpful.
Ok I was using SQLite and important thing that is to be done is to create
1.) A BLOB field to save your data is to be used.
2.) Use the following code to select the file. For this one need to call the Open Dialog Box.
{
OpenFileDialog of1 = new OpenFileDialog();
of1.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg";
of1.ShowDialog();
tbImage.Text = of1.FileName;
}
Note: Don't forget to set the related Database Field type as System.byte[];
3.) Now convert the file into Byte Stream.
{
byte[] imageBt = null;
FileStream fstream = new FileStream(tbImage.Text,FileMode.Open,FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imageBt = br.ReadBytes((int)fstream.Length);
}
4.) Insert the image in the database
{
String query = "Insert into Employee Values (" + e1.EmpID + ",'" + e1.FirstName + "','" + e1.LastName + "','" + e1.EmailAddress + "', #IMG)";
myCommand = new SQLiteCommand(query, dbConn);
myCommand.Parameters.Add(new SQLiteParameter("#IMG", e1.Image));
}
For Retrieval of the images first an ImageBox is required
1.) Use the following code to get the BLOB data byte and to place the image in the Image Box
{
MemoryStream mstream = new MemoryStream((byte[])(reader["Image"]));
ImageBox.Image = System.Drawing.Image.FromStream(mstream);
}
On my local machine everything works well but..
After publishing my MVC4 web project there is a problem with an uploaded Excel file.
I load an HttpPostedFileBase and send the path to my BL. There I load it to dataTable and on my second call I get it to a list.
Here is the code..
Controller:
[HttpPost]
public ActionResult UploadCards(HttpPostedFileBase file, string sheetName, int ProductID)
{
try
{
if (file == null || file.ContentLength == 0)
throw new Exception("The user not selected a file..");
var fileName = Path.GetFileName(file.FileName);
var path = Server.MapPath("/bin");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
path = Path.Combine(path, fileName);
file.SaveAs(path);
DataTable cardsDataTable = logic.LoadXLS(path, sheetName);
cardsToUpdate = logic.getUpdateCards(cardsDataTable, ProductID);
foreach (var item in cardsToUpdate)
{
if (db.Cards.ToList().Exists(x => x.SerialNumber == item.SerialNumber))
cardsToUpdate.Remove(item);
}
Session["InfoMsg"] = "click update to finish";
}
catch (Exception ex)
{
Session["ErrorMsg"] = ex.Message;
}
return View("viewUploadCards", cardsToUpdate);
}
BL:
public DataTable LoadXLS(string strFile, String sheetName)
{
DataTable dtXLS = new DataTable(sheetName);
try
{
string strConnectionString = "";
if (strFile.Trim().EndsWith(".xlsx"))
strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);
else if (strFile.Trim().EndsWith(".xls"))
strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);
OleDbConnection SQLConn = new OleDbConnection(strConnectionString);
SQLConn.Open();
OleDbDataAdapter SQLAdapter = new OleDbDataAdapter();
string sql = "SELECT * FROM [" + sheetName + "$]";
OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn);
SQLAdapter.SelectCommand = selectCMD;
SQLAdapter.Fill(dtXLS);
SQLConn.Close();
}
catch (Exception ex)
{
string res = ex.Message;
return null;
}
return dtXLS;
}
and:
public List<Card> getUpdateCards(DataTable dt, int prodId)
{
List<Card> cards = new List<Card>();
try
{
Product product = db.Products.Single(p => p.ProductID == prodId);
foreach (DataRow row in dt.Rows)
{
cards.Add(new Card
{
SerialNumber = row[0].ToString(),
UserName = row[1].ToString(),
Password = row[2].ToString(),
Activated = false,
Month = product.Months,
Bandwidth = product.Bandwidth,
ProductID = product.ProductID,
// Product = product
});
}
}
catch (Exception ex)
{
db.Log.Add(new Log { LogDate = DateTime.Now, LogMsg = "Error : " + ex.Message });
}
return cards;
}
Now I think Windows Azure doesn't let me save this file because on the middle view when I supposed to see the data - I don't see it.
I thought of some ways...
one - not saving the file, but I don't see how to complete the ConnectionString...
second maybe there is a way to save the file there.
I'd love to get suggestions for solving this problem...
10x and sorry for my bad English =)
I'm embarrassed but I found a similar question here.. Not exactly but it gave me a good direction.
Hare the finally result:
[HttpPost]
public ActionResult UploadCards(HttpPostedFileBase file, string sheetName, int ProductID)
{
IExcelDataReader excelReader = null;
try
{
if (file == null || file.ContentLength == 0)
throw new Exception("The user not selected a file..");
if (file.FileName.Trim().EndsWith(".xlsx"))
excelReader = ExcelReaderFactory.CreateOpenXmlReader(file.InputStream);
else if (file.FileName.Trim().EndsWith(".xls"))
excelReader = ExcelReaderFactory.CreateBinaryReader(file.InputStream);
else
throw new Exception("Not a excel file");
cardsToUpdate = logic.getUpdateCards(excelReader.AsDataSet().Tables[sheetName], ProductID);
foreach (var item in cardsToUpdate)
{
if (db.Cards.ToList().Exists(x => x.SerialNumber == item.SerialNumber))
cardsToUpdate.Remove(item);
}
Session["InfoMsg"] = "Click Update to finish";
}
catch (Exception ex)
{
Session["ErrorMsg"] = ex.Message;
}
finally
{
excelReader.Close();
}
return View("viewUploadCards", cardsToUpdate);
}
10q all.
EDIT: download, reference and using
the dll is avalibale hare
i add the reference to the Excel.dll and i add the using Excel;
The problem might be caused by writing the file to the disk. Cloud providers usually do not allow the applications to write to the disk.
In your case it seems that the file is written to the disk only temporary and is loaded directly to the DB. You should be able to open the stream from the uploaded file directly and write it directly to the DB - without writing to the disk.
Check the exception which you are stocking in the Session - you should find more information there.
#hoonzis is right, writing files to disk in the cloud is not permited(you can't event get or set a path for the file). You should use blob storage, much more efficient for files and is cheaper than sql. I recommend to use the table storage service, it is noSQL but it's more cheaper than azure sql.
Use azure sql only if it is a must for your solution.
Blob storage see more details here: http://www.windowsazure.com/en-us/develop/net/how-to-guides/blob-storage/
Table storage: http://www.windowsazure.com/en-us/develop/net/how-to-guides/table-services/
Some more information about choosing the right storage you can find here: http://www.windowsazure.com/en-us/develop/net/fundamentals/cloud-storage-scenarios/
How can I dynamically insert images when user uploads an image file to SQL Server 2005 with C# in ASP.NET? This is to let users upload their profile photos in my web app. Is it very different from how it is done for windows app with C#?
There is a metric ton of examples on the web on this one:
http://aspalliance.com/138
https://web.archive.org/web/20210304133428/https://www.4guysfromrolla.com/articles/120606-1.aspx
http://www.aspfree.com/c/a/ASP.NET/Uploading-Images-to-a-Database--C---Part-I/
You should be able to follow any of those to accomplish what you want.
The same way as in in WinForms. Get byte[] and same to image column. But i strongly recommend to use file system to store pictures. DB is for relational data, File System for raw bytes.
http://msdn.microsoft.com/en-us/library/aa479405.aspx
Here is a sample of the code behind for inserting an image into a database in C#. You will of coarse need supporting table the picture should be a byte field and keep the picture type so you can retrieve the image later to display it. In addition to that you need to put a file input box on your page along with a submit button.
public void AddImage(object sender, EventArgs e)
{
int intImageSize;
String strImageType;
Stream ImageStream;
FileStream fs = File.OpenRead(Request.PhysicalApplicationPath + "/Images/default_image.png");
Byte[] ImageContent;
if (PersonImage.PostedFile.ContentLength > 0)
{
intImageSize = PersonImage.PostedFile.ContentLength;
strImageType = PersonImage.PostedFile.ContentType;
ImageStream = PersonImage.PostedFile.InputStream;
ImageContent = new Byte[intImageSize];
int intStatus;
intStatus = ImageStream.Read(ImageContent, 0, intImageSize);
}
else
{
strImageType = "image/x-png";
ImageContent = new Byte[fs.Length];
fs.Read(ImageContent, 0, ImageContent.Length);
}
SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["conn"]);
SqlCommand objCmd;
string strCmd;
strCmd = "INSERT INTO ImageTest (Picture, PictureType) VALUES (#Picture, #PictureType)";
objCmd = new SqlCommand(strCmd, objConn);
SqlParameter prmPersonImage = new SqlParameter("#Picture", SqlDbType.Image);
prmPersonImage.Value = ImageContent;
objCmd.Parameters.Add(prmPersonImage);
objCmd.Parameters.AddWithValue("#PictureType", strImageType);
lblMessage.Visible = true;
try
{
objConn.Open();
objCmd.ExecuteNonQuery();
objConn.Close();
lblMessage.Text = "ImageAdded!";
}
catch
{
lblMessage.Text = "Error occured the image has not been added to the database!";
}
}