Converting issue Byte to Byte - asp.net

i never work with Bytes before i have a getting error here in may code please have a look
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
SqlDataReader dr = ExecuteReader(Globals.con, CommandType.Text,
"select FileName,MediaData,Extension from media where Id=" + ID);
string FileName="";
Byte[] MediaData= null;
string Extension = "";
while (dr.Read())
{
FileName = dr["FileName"].ToString();
MediaData = Convert.ToByte(dr["MediaData"].ToString()); error is here
Extension = dr["Extension"].ToString();
}
dr.Close();
string filename = (String)FileName;
byte[] fileToDownload = (byte[])MediaData;
String fileExtension = (String)Extension;
in gridview i use this code below it working i need manual date
not like code below
string filename = (String)reader.GetValue(1);
byte[] fileToDownload = (byte[])reader.GetValue(2);
String fileExtension = (String)reader.GetValue(3);
please help me out in it

Convert.ToByte returns a single byte, not an array.
You are also using ToString which can completely convert the binary data into a representation that you can't use:
MediaData = Convert.ToByte(dr["MediaData"].ToString())
Should be:
MediaData = (byte[])dr.Items["MediaData"];

Related

How to get the Query String variable in ASP.NET and pass it as an Sql parameter?

string userid = Request.QueryString[0].ToString();
string Qid = Request.QueryString[1].ToString();
string connection = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString.ToString();
SqlConnection con = new SqlConnection(connection);
con.Open();
SqlCommand com = new SqlCommand("qualification", con);
com.Parameters.Add("#proctype",SqlDbType.Int).Value = 4;
com.Parameters.Add("#Qid", SqlDbType.Int).Value = Qid;
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
drpqualification.SelectedItem.Text = reader["Qualification"].ToString();
txtSubjects.Text = reader["Subject"].ToString();
txtmarksobt.Text = reader["MarksObtained"].ToString();
txtgrade.Text = reader["Percentage"].ToString();
txtboard.Text = reader["BoardUniversity"].ToString();
}
reader.Close();
con.Close();
}
and here the URL:http://localhost:35689/Academic_info.aspx?userid=94&Qid=14
i want to get the Qid only and pass it as Sql Parameter*
You should add values to parameters as below -
command.Parameters.Add("#ID", SqlDbType.Int);
command.Parameters["#ID"].Value = customerID;
// Use AddWithValue to assign Demographics.
// SQL Server will implicitly convert strings into XML.
command.Parameters.AddWithValue("#demographics", demoXml);
Check this URL - https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx
And to fetch the query string, just use Request.QueryString["Qid"]. You don't need to .ToString() it.

BinaryReader.ReadBytes returning junk when converted to string

if I try to explain why I need to do what I'm trying to do it will take a long time, but basically it's this: I have FileUpload control for the user to choose a Jpeg file, I make the upload and after it I want to convert that file to bytes and use it as the source of an Image control.
My code is this one:
string fileName = Server.MapPath("~/TempImages") + #"\foto.jpg";
fileUpload1.SaveAs(fileName);
System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fs);
long byteLength = new System.IO.FileInfo(fileName).Length;
byte[] buffer = binaryReader.ReadBytes((Int32)byteLength);
fs.Close();
fs.Dispose();
string valor = System.Text.Encoding.UTF8.GetString(buffer);
img.ImageUrl = "data:image/jpg;base64," + valor;
The byte array is looking ok, but when I convert it to string it's full of unrecognized characters, I have another page where I do the same thing but instead of getting the bytes from the file I get it from a MySql database and using the same System.Text.Encoding.UTF8.GetString and it works withou a problem.
UPDATE
As asked, this is the code I use when retrieving the from the MySql database:
DataView dv = (DataView)SqlDataSource3.Select(DataSourceSelectArguments.Empty);
byte[] buffer = (byte[])dv.Table.Rows[0]["BIN_FOTO"];
string valor = System.Text.Encoding.UTF8.GetString(buffer);
img.ImageUrl = "data:image/jpg;base64," + valor;
The select of this SqlDataSource3 is a simple Select BIN_FOTO from temp_image. I store this value in the database from a webcam capture WPF program, the code I use to convert the image the webcam captured is:
private string ImageToBase64String(System.Drawing.Image imageData, ImageFormat format)
{
string base64;
MemoryStream memory = new MemoryStream();
imageData.Save(memory, format);
base64 = System.Convert.ToBase64String(memory.ToArray());
memory.Close();
memory.Dispose();
return base64;
}
Then I save the base64 variable to the database.
Hope this clarifies my problem
So you want to read the image file and convert to base 64. After your reading code, do this:
string valor = Convert.ToBase64String(buffer);
Your original code was flawed because you're saving the image, as bytes, to the file with this line of code:
fileUpload1.SaveAs(fileName);
That's not saved as base64, so you have to convert it to base 64 after you read it. Your MySql reading worked because the data was converted to base64 before being saved.
By the way, there's no need for the BinaryReader in this code:
System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fs);
long byteLength = new System.IO.FileInfo(fileName).Length;
byte[] buffer = binaryReader.ReadBytes((Int32)byteLength);
fs.Close();
fs.Dispose();
You can write this instead:
byte[] buffer;
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)
{
long byteLength = fs.Length;
buffer = new byte[byteLength];
int bytesRead = fs.Read(buffer, 0, byteLength);
// optional error check to see that you got all the bytes
if (bytesRead != byteLength)
{
// handle error
}
}
string valor = Convert.ToBase64String(buffer);
I've found the problem, looking at the WPF code I used to convert the image to a Base64String. I just created the same function ImageToBase64String and now it works:
string fileName = Server.MapPath("~/TempImages") + #"\foto.jpg";
fileUpload1.SaveAs(fileName);
System.Drawing.Image teste = System.Drawing.Image.FromFile(fileName);
string valor = ImageToBase64String(teste, System.Drawing.Imaging.ImageFormat.Jpeg);
//System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
//System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fs);
//long byteLength = new System.IO.FileInfo(fileName).Length;
//byte[] buffer = binaryReader.ReadBytes((Int32)byteLength);
//buffer = File.ReadAllBytes(fileName);
//fs.Close();
//fs.Dispose();
//string valor = System.Text.Encoding.UTF8.GetString(buffer);
img.ImageUrl = "data:image/jpg;base64," + valor;
But I still don't know what was wrong with my previous code, anyone can clarify?
This solution worked for me:
System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fs);
//Add this--------------------
fs.Seek(0, SeekOrigin.Begin);
//----------------------------
long byteLength = new System.IO.FileInfo(fileName).Length;
byte[] buffer = binaryReader.ReadBytes((Int32)byteLength);
Just add highlighted line.

No data is read in SqlReader Invalid attempt to read when no data is present.

I know this problem has been posted millions of times before, but this might be different.
I am using a sql table with columns id,year,month,pdffile
in my webpage, I would like the user to view the pdf document that they would like to see from what time frame they choose.
so far with this:
string year = ddlYear.SelectedValue.ToString();
string month = ddlMonth.SelectedValue.ToString();
pdfFrame.Attributes["src"] = "../pdfDocs.ashx?Year=" + year + "&Month=" + month;
it loads the pdf, if it is there. that is my problem.
how would I catch the error in my question title? I want to catch that error and display a message in a label to the user saying that no file was found. I am using a handler to read the varbinary that is my pdf file.
Here is the handler code:
SqlConnection conn = new SqlConnection(#"Server=DEV6\MSSQLHOSTING;Database=Intranet;Trusted_Connection=True;");
conn.Open();
SqlCommand cmd = new SqlCommand("select PDFDocument from LeaveChart where (Year like #Year and Month like #Month)", conn);
cmd.Parameters.AddWithValue("Year", context.Request.QueryString["Year"]);
cmd.Parameters.AddWithValue("Month", context.Request.QueryString["Month"]);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
byte[] content = (byte[])reader.GetValue(0);
MemoryStream ms = new MemoryStream(content);
ms.Position = 0;
context.Response.ContentType = "Application/pdf";
ms.WriteTo(context.Response.OutputStream);
context.Response.End();
reader.Close();
conn.Close();
like I said, that works to display present files. can anyone offer some suggestions?
is it possible to send a message from the handler back to the web page saying no file and how to display it without shocking the customer?
thanks in advance
If you can change the signature of your Handler, then:
public bool <YourHandlerName>(out MemoryStream ms)
{
SqlConnection conn = new SqlConnection(#"Server=DEV6\MSSQLHOSTING;Database=Intranet;Trusted_Connection=True;");
conn.Open();
SqlCommand cmd = new SqlCommand("select PDFDocument from LeaveChart where (Year like #Year and Month like #Month)", conn);
cmd.Parameters.AddWithValue("Year", context.Request.QueryString["Year"]);
cmd.Parameters.AddWithValue("Month", context.Request.QueryString["Month"]);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
ms = new MemoryStream(content);
if(reader.HasRows)
{
byte[] content = (byte[])reader.GetValue(0);
ms.Position = 0;
context.Response.ContentType = "Application/pdf";
ms.WriteTo(context.Response.OutputStream);
context.Response.End();
reader.Close();
conn.Close();
return true;
}
return false;
}
I guess I got your question correctly.

Unable to get the Content of the text file saved in the Database(My-Sql)

In my MySql i am having my data field as longblob i would like to get the content in that file so i have written my code as follows
This is what i am doing before inserting
string filePath = Server.MapPath("AchTemplates/genACH.txt");
string filename = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
string strQuery = "insert into tblFiles(FName,FData) values (#_FName, #_FData)";
MySqlCommand cmd = new MySqlCommand(strQuery);
cmd.Parameters.Add("#_FName", MySqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#_FData", MySqlDbType.LongBlob).Value = bytes;
InsertUpdateData(cmd);
//Get Data
private void download(DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["FData"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
But i am getting the content as system.string[] why it is happening can any one tell
if dt.Rows[0]["FData"] is coming as a string (it is just plain text), use
byte[] bytes = Encoding.UTF8.GetBytes(dt.Rows[0]["FData"]);
If the data is not plain text and binary stored as string (and not base64 encoded), you are in trouble my friend.
UPDATE
According to MySql documentation, it seems you should be using LONGBLOB and not LONGTEXT.

File Upload with HttpWebRequest doesn't post the file

Here is my code to post the file. I use asp fileupload control to get the file stream.
HttpWebRequest requestToSender = (HttpWebRequest)WebRequest.Create("http://localhost:2518/Web/CrossPage.aspx");
requestToSender.Method = "POST";
requestToSender.ContentType = "multipart/form-data";
requestToSender.KeepAlive = true;
requestToSender.Credentials = System.Net.CredentialCache.DefaultCredentials;
requestToSender.ContentLength = BtnUpload.PostedFile.ContentLength;
BinaryReader binaryReader = new BinaryReader(BtnUpload.PostedFile.InputStream);
byte[] binData = binaryReader.ReadBytes(BtnUpload.PostedFile.ContentLength);
Stream requestStream = requestToSender.GetRequestStream();
requestStream.Write(binData, 0, binData.Length);
requestStream.Close();
HttpWebResponse responseFromSender = (HttpWebResponse)requestToSender.GetResponse();
string fromSender = string.Empty;
using (StreamReader responseReader = new StreamReader(responseFromSender.GetResponseStream()))
{
fromSender = responseReader.ReadToEnd();
}
XMLString.Text = fromSender;
In the page load of CrossPage.aspx i have the following code
NameValueCollection postPageCollection = Request.Form;
foreach (string name in postPageCollection.AllKeys)
{
Response.Write(name + " " + postPageCollection[name]);
}
HttpFileCollection postCollection = Request.Files;
foreach (string name in postCollection.AllKeys)
{
HttpPostedFile aFile = postCollection[name];
aFile.SaveAs(Server.MapPath(".") + "/" + Path.GetFileName(aFile.FileName));
}
string strxml = "sample";
Response.Clear();
Response.Write(strxml);
I don't get the file in Request.Files. The byte array is created. What was wrong with my HttpWebRequest?
multipart/form-data doesn't consist of simply writing the file bytes to the request stream. You need to respect the RFC 1867. You may take a look at this post of how this could be done with multiple files.

Resources