ORA-01460: unimplemented or unreasonable conversion requested-uploading files - c#

Following is the code to upload file in party_images table.
protected void upload_Click(object sender, EventArgs e)
{
try
{
using (OracleConnection connection = new OracleConnection(conString))
{
connection.Open();
string filename = Path.GetFileName(FileUpload1.FileName);
string[] tokenize = filename.Split('.');
FileUpload1.SaveAs(Server.MapPath("~/files/") + descBox.Text + "." + tokenize[1]);
string sourceLoc = Server.MapPath("~/files/" + descBox.Text + "." + tokenize[1]);
FileStream fs = new FileStream(sourceLoc, FileMode.Open, FileAccess.Read);
byte[] ImageData = new byte[fs.Length];
fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
String block = " BEGIN " +
" INSERT INTO party_images(party_id, sr_no, descr, party_image) VALUES ('"+Session["userId"]+"',"+srNo.Text+",'"+descBox.Text+"."+tokenize[1]+"', :1); " +
" END; ";
OracleCommand cmd = new OracleCommand();
cmd.CommandText = block;
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
OracleParameter param = cmd.Parameters.Add("blobtodb", OracleDbType.LongRaw);
param.Direction = ParameterDirection.Input;
param.Value = ImageData;
cmd.ExecuteNonQuery();
descBox.Text = "";
srNo.Text = "";
}
}
catch (Exception ex) {
ClientScript.RegisterStartupScript(this.GetType(), "unSuccessMessage", "window.onload = function(){ alert('"+ex.Message+"')};", true);
}
finally
{
populateGrid(loadFromDb());
}
}
table description is,
PARTY_ID is VARCHAR2(10)
SR_NO is NUMBER
DESCR is VARCHAR2(50)
PARTY_IMAGE is LONG RAW()
This function is uploading all the files i.e., images,.docx,.pdf,.sql but when I upload any .docx containing screen shots or pictures then the upper error appears.
I have tried the following links,
ORA-01460: unimplemented or unreasonable conversion requested
The requested format conversion is not supported.
ORA-01460: unimplemented or unreasonable conversion requested
But I haven't got any solution. How can I upload any type of file without having this error?

Why are you using LONG RAW to store binary objects? That's a datatype which has been deprecated for over twenty years.
If you define PARTY_IMAGE as a BLOB (or maybe BFILE) you will find it a lot easier to work with. Find out more.

Related

C# Binary conversion of document fails

I'm trying to put a document from my computer into a BLOB column in a MySQL database.
I have tried converting the .doc file into a byte[] array, but it keeps saving [BLOB - 13 B] (which is system.byte[] as a string) to the database instead of the actual bytes.
I don't know which part fails, i have tried multiple converting methods and stuck with this one since:
int curr = 0;
foreach (string path in documenteFinal)
{
try
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (BinaryReader br = new BinaryReader(fs))
{
byte[] fileData = br.ReadBytes((int)fs.Length);
connection.Open();
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "insert into documents values(null, '" + documenteFinal[curr] + "', '" + fileData + "')";
cmd.ExecuteNonQuery();
connection.Close();
}
}
catch (System.ArgumentNullException)
{ break; }
curr++;
}
That's because you need to tell your query that it is writing to a Blob Field and you're not just trying to store the ToString() representation of fileData.
I haven't tested it, but you should be able to achieve what you are trying to do using parameterized queries:
int curr = 0;
foreach (string path in documenteFinal)
{
var fileBytes = File.ReadAllBytes(path);
connection.Open();
using (var command = new MySqlCommand(
"INSERT INTO documents VALUES(null,'" + documenteFinal[curr] + "',#File)", connection))
{
command.Parameters.Add("#File", MySqlDbType.VarBinary, fileBytes.Length).Value = fileBytes;
command.ExecuteNonQuery();
}
connection.Close();
curr++;
}
You should have add a 0x before binary data and remove the single quotes, try this line in place of yours:
cmd.CommandText = "insert into documents values(null, '" + documenteFinal[curr] + "', 0x" + fileData + ")";
I suggest however to try this more compact source code that makes use of the mysql native LOAD_FILE function:
foreach (string path in documenteFinal) {
try {
connection.Open();
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = $"insert into documents values(null, '{path}', LOAD_FILE('{path}'))";
cmd.ExecuteNonQuery();
connection.Close();
} catch(Exception) { break; }
}

convert long binary data in database access to image using c#

here is my code:
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from StudentInformation where [StudentID] = " + txtStudentID.Text + "";
command.CommandText = query;
OleDbDataReader read = command.ExecuteReader();
while (read.Read())
{
txtStudentID.Text = (read["StudentID"].ToString());
txtFirstname.Text = (read["Firstname"].ToString());
txtLastname.Text = (read["Lastname"].ToString());
byte[] imgbyte = (byte[])read["Image"]; //when i add this a got error with this code
MemoryStream ms = new MemoryStream(imgbyte);
StudentPicture.Image = Image.FromStream(ms);
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
i get the error "Parameter is not valid"
someone can help me?
im so confused!
i tried all the codes what i searched but still Error :'(
sorry for my bad english
Your response will be greatly appreciated....
Try getting your byte array like this instead:
var binLength = read.Item[3].Length;
byte[] imgByte = new byte[binLength - 1];
var bytes = read.GetBytes(0,0,imgByte,0,imgByte.Length);
MemoryStream ms = new MemoryStream(imgByte);
StudentPicture.Image = Image.FromStream(ms);

Uploading files in varbinary(MAX)

I have a database table with two field of type varbinary(max), which i use to store files.
However, I am unable to upload the files as expected. I've been stumped for this problem for a long time and I'm not sure what I can do to resolve it. There is an error message:
An exception of type 'System.Data.SqlClient.SqlException' occurred in
System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near the keyword 'title'.
Its a must for me to implement 3-tier architecture in ASP.NET.
Data Access Layer
public class Submission {
private string _title;
private byte[] _slides, _codes;
//Connection string
private string _connStr = Properties.Settings.Default.DBConnStr;
public Submission(string title, byte[] slides, byte[] codes) {
_title = title;
_slides = slides;
_codes = codes;
}
//UPLOAD files
public int SubmissionInsert()
{
string queryStr = "INSERT INTO Submission(title,slides,codes)" +
"VALUES('" +
_title + "', '" +
_slides + "', '" +
_codes + "')";
SqlConnection con = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, con);
con.Open();
int nofRow = 0;
nofRow = cmd.ExecuteNonQuery();
con.Close();
return nofRow;
}
}
Business Logic Layer
public class SubmissionBLL
{
public string submissionUpload(string title, byte[] slides, byte[] codes)
{
string returnValue = "";
if (title.Length == 0)
returnValue+= "Title cannot be empty";
if (slides == null)
returnValue += "Slides cannot be empty";
if (codes == null)
returnValue += "Codes cannot be empty";
//if there are no errors
if (returnValue.Length == 0)
{
Submission sub = new Submission(title,slides,codes);
int nofRows = 0;
nofRows = sub.SubmissionInsert();
if (nofRows > 0)
returnValue = "Submission is successful!";
else
returnValue = "Submission failure. Please try again.";
}
return returnValue;
}
Presentation Layer - Code-behind
protected void btn_submit_Click(object sender, EventArgs e)
{
string input = "";
byte[] slideArr = null, codeArr= null;
string strTestFilePath, strTestFileName, strContentType;
Int32 intFileSize, intFileLength;
Stream strmStream;
if (f_codes.HasFile)
{
strTestFilePath = f_codes.PostedFile.FileName;
strTestFileName = Path.GetFileName(strTestFilePath);
intFileSize = f_codes.PostedFile.ContentLength;
strContentType = f_codes.PostedFile.ContentType;
//Convert the source codes file to byte stream to save to database
strmStream = f_codes.PostedFile.InputStream;
intFileLength = (Int32)strmStream.Length;
codeArr = new byte[intFileLength + 1];
strmStream.Read(codeArr, 0, intFileLength);
strmStream.Close();
}
if (f_slide.HasFile)
{
strTestFilePath = f_slide.PostedFile.FileName;
strTestFileName = Path.GetFileName(strTestFilePath);
intFileSize = f_slide.PostedFile.ContentLength;
strContentType = f_slide.PostedFile.ContentType;
strmStream = f_slide.PostedFile.InputStream;
intFileLength = (Int32)strmStream.Length;
slideArr = new byte[intFileLength + 1];
strmStream.Read(slideArr, 0, intFileLength);
strmStream.Close();
}
//Pass to BLL
input = sub.submissionUpload(tb_title.Text,slideArr,codeArr);
//Display error messages
lbl_message.Text = input;
}
I tried to debug with IntelliTrace and it shows a message
ADO.NET:Execute NonQuery "INSERT INTO Submission(title,slides,codes)VALUES( 'My Water Saving Project', 'System.Byte[]','System.Byte[]')"
Am I doing this correctly? I tried to run and the exception error is still
present.
string queryStr = "INSERT INTO Submission(title,slides,codes)" + "VALUES('"+
_title + "', '" +
"0x" + BitConverter.ToString(_slides).Replace("-", "")+ "', '" +
"0x" + BitConverter.ToString(_codes).Replace("-", "") + "')";
"0x" + BitConverter.ToString(_slides).Replace("-", "")+ "', '" +
You should not convert byte to string. Instead, you want to use the parametrized query (to avoid sql injection) and insert those byte arrays straight to database.
public int SubmissionInsert(string title, byte[] slides, byte[] codes)
{
int nofRow;
string query = "INSERT INTO Submission ( title, slides, codes )" +
"VALUES ( #Title, #Slides, #Codes );";
using (var con = new SqlConnection(_connStr))
{
con.Open();
using (var cmd = new SqlCommand(query, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Title", title);
cmd.Parameters.AddWithValue("#Slides", slides);
cmd.Parameters.AddWithValue("#Codes", codes);
nofRow = cmd.ExecuteNonQuery();
}
}
return nofRow;
}
Your issue is with the type conversion. If you are inserting the value as a string (and you are by using those single quotes), you need to insert the HEX values, and prefix it with 0x.
This should help you out:
"0x" + BitConverter.ToString(byteArray).Replace("-", "")
I also got the same error when I am uploading doc USING ADO.NET and Storedproc.
I am using stored proc to upload word file to the table's column type varbinary(max).
There are so many examples with insert query to insert document but my scenario was stored proc. I spent lot of time in figuring out the solution.
Stored Proc:`Alter PROC [dbo].[usp_GMS_SaveEngagementDocument](
#pDocumentID INT=0,
#pEngagementID INT,
#pDocumentName NVARCHAR(100),
#pContentType NVARCHAR(100),
#pDocumentType NVARCHAR(100),
#pDocumentContent VARBINARY(max)=null,
#pUserID INT)
AS
BEGIN
--INSERT
END`
SOLUTION:
param = new SqlParameter();
param.ParameterName = "#pDocumentContent";
param.Direction = ParameterDirection.Input;
param.Value = document.DocumentContent;
param.DbType = DbType.Binary;
param.SqlDbType = SqlDbType.Binary;
paramList.Add(param);
Setting SQLDBType as Binary and DbType as Binary solved my problem In calling stored proc.
END

How to display Image using repeater

I have a page to upload a photo into my database. Then when I click upload, the photo has been saved as binary format in database:
protected void Button1_Click(object sender, EventArgs e)
{
Byte[] bytes = null;
if (FileUpload1.HasFile)
{
string filename = FileUpload1.PostedFile.FileName;
string filePath = Path.GetFileName(filename);
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
bytes = br.ReadBytes((Int32)fs.Length);
}
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERT INTO disc_info (disc_name,menu) VALUES('" + TextBox.Text + "','" + bytes + "')", con);
con.Open();
cmd.ExecuteNonQuery();
When I am trying to retrieve image then it is not displayed, how to display image using repeater?
Database: menu image
<asp:Image ID="ViewPhotoImage" runat="server" ImageUrl='<%# GetImage(Eval("menu")) %>' Height="190px" Width="180px"/>
public string GetImage(object img)
{
return "data:image/jpg;base64," + Convert.ToBase64String((byte[]) img);
}
I think your problem may be in how you are putting the data into the database. You may not have valid image data in the database at all. Does that code run for you when you upload an image? When I run it it errors out on the sql command because when you implicitly convert a byte[] into a string in c# you get "System.Byte[]" instead of the string representation of the data. You need to convert that byte[] into a binary string. That link has a bunch of ways to do it, and here's your upload code with one of those ways (Not Recommended, see below):
(Edited, see comment below)
Byte[] bytes = null;
string hex = "0";
if (FileUpload1.HasFile)
{
string filename = FileUpload1.PostedFile.FileName;
string filePath = Path.GetFileName(filename);
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
bytes = br.ReadBytes((Int32)fs.Length);
hex = "0x" + BitConverter.ToString(bytes).Replace("-", "");
}
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERT INTO disc_info (disc_name,menu) VALUES('" + TextBox.Text + "'," + hex + ")", con);
con.Open();
cmd.ExecuteNonQuery();
You also might want to move that sql code into the if block, but maybe that's what you want, just thought i'd mention it in case.
HOWEVER...
I would be remiss if I did not strongly suggest that you parameterize your sql statement to avoid injection attacks. But not only is it better for security, it makes working with the binary data much easier as there is no need to string convert. Here's the relevant code with parameters:
Byte[] bytes = null;
if (FileUpload1.HasFile)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
bytes = br.ReadBytes((Int32)fs.Length);
}
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERT INTO disc_info (disc_name,menu) VALUES(#disc, #menu)", con);
cmd.Parameters.AddWithValue("#disc", TextBox.Text);
cmd.Parameters.AddWithValue("#menu", bytes);
con.Open();
cmd.ExecuteNonQuery();
Once I did that, your other code worked fine and I was able to see my test images in the repeater. I hope that helps!

Incorrect syntax inserting data into table

I am having some trouble with my update() method. The idea is that the user Provides a recipe name, ingredients, instructions and then selects an image using Filestream.
Once the user clicks 'Add Recipe' this will call the update method, however as things stand I am getting an error which is mentioning the contents of the text box:
Here is the update() method code:
private void updatedata()
{
// filesteam object to read the image
// full length of image to a byte array
try
{
// try to see if the image has a valid path
if (imagename != "")
{
FileStream fs;
fs = new FileStream(#imagename, FileMode.Open, FileAccess.Read);
// a byte array to read the image
byte[] picbyte = new byte[fs.Length];
fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
//open the database using odp.net and insert the lines
string connstr = #"Server=mypcname\SQLEXPRESS;Database=RecipeOrganiser;Trusted_Connection=True";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
string query;
query = "insert into Recipes(RecipeName,RecipeImage,RecipeIngredients,RecipeInstructions) values (" + textBox1.Text + "," + " #pic" + "," + textBox2.Text + "," + textBox3.Text + ")";
SqlParameter picparameter = new SqlParameter();
picparameter.SqlDbType = SqlDbType.Image;
picparameter.ParameterName = "pic";
picparameter.Value = picbyte;
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add(picparameter);
cmd.ExecuteNonQuery();
MessageBox.Show("Image successfully saved");
cmd.Dispose();
conn.Close();
conn.Dispose();
Connection();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Can anyone see where I have gone wrong with the insert into Recipes query or suggest an alternative approach to this part of the code?
Your code is open to SQL Injection, but probably your error comes from some text that contains a single quote (the instructions fields for example) and this break your command string build using concatenating the user input.
EDIT
As someone pointed in comment the error is caused by the missing quotes around your textboxes. But while easy to fix that's not the way to go because it is wrong to fix the error adding the missing quotes. It is just postponig the problem leaving a big security hole waiting to be exploited.
A parameterized query could avoid all this mess.
string connstr = "....";
string query = "insert into Recipes(RecipeName,RecipeImage,RecipeIngredients,RecipeInstructions) " +
"values (#name, #pic, #ing, #instr)";
using(SqlConnection conn = new SqlConnection(connstr))
using(SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
SqlParameter picparameter = new SqlParameter();
picparameter.SqlDbType = SqlDbType.Image;
picparameter.ParameterName = "#pic";
picparameter.Value = picbyte;
cmd.Parameters.Add(picparameter);
cmd.Parameters.AddWithValue("#name", textbox1.Text);
cmd.Parameters.AddWithValue("#ing", textbox2.Text);
cmd.Parameters.AddWithValue("#instr", textbox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Image successfully saved");
}
Since you using string concatenations, you probably missed a quote or you put an extra quote or missed a comma or put extra comma etc etc....
Don't use this way!
Your error doesn't look obviously but you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
query = "insert into Recipes(RecipeName,RecipeImage,RecipeIngredients,RecipeInstructions) values (#p1, #pic, #p3, #p4)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue(#p1, textBox1.Text);
cmd.Parameters.AddWithValue(#pic, textBox1.Text);
cmd.Parameters.AddWithValue(#p3, textBox1.Text);
cmd.Parameters.AddWithValue(#p4, picparameter);
try this
query = "insert into Recipes(RecipeName,RecipeImage,RecipeIngredients,RecipeInstructions) values ('" + textBox1.Text + "'," + " #pic" + ",'" + textBox2.Text + "','" + textBox3.Text + "')";

Categories