Read Image stored in Oracle using Long DataType - asp.net-mvc

I want to read the image stored in Oracle Long datatype.
Number of images are stored in a remote Oracle database in a column with datatype long. I just need to retrieve those images and show them on my aspx page.
I could retrieve the image from database but when tried to caste it to byte array, it threw error that, string can not be converted to byte[]'.
Anybody have any suggestions on how to retrieve these images stored in long column in database.
byte[] signatureBlobReceived = cls_TBL_BROKER_BL.GetInstance().GetSignatureBlobFromAccountNumber_BL(strCRNnumber);
return File(signatureBlobReceived, "image/jpeg");
public byte[] GetSignatureBlobFromAccountNumber_BL()
{
object SignatureBlob = null;
Database db = DatabaseFactory.CreateDatabase("imageConnectionString");
DbCommand dbc = db.GetSqlStringCommand(ConfigurationSettings.AppSettings["signqry"].ToString());
dbc.CommandType = CommandType.Text;
SignatureBlob = db.ExecuteScalar(dbc);
byte[] array = Encoding.ASCII.GetBytes(Convert.ToString(SignatureBlob));
string aa = string.Empty;
return array;
}
Query used is:
<add key="signqry" value="SELECT image FROM table1"/> `

Try this (odp.net)
string connStr = "User Id=user;Password=pwd;Data Source=mySID;";
OracleConnection _conn = new OracleConnection(connStr);
_conn.Open();
string sel = #"select long_raw_col from long_raw_test";
OracleCommand cmd = new OracleCommand(sel, _conn);
cmd.InitialLONGFetchSize = 5000;
OracleDataReader reader = cmd.ExecuteReader();
int rows = 0;
// loop through rows from table
while (reader.Read())
{
rows++;
byte[] buf = new byte[5000];
long bytesRead = reader.GetBytes(reader.GetOrdinal("long_raw_col"), 0, buf, 0, 5000);
FileStream fs = new FileStream("C:\\test\\test_long" + rows + ".dat", FileMode.Create);
fs.Write(buf, 0, (int)bytesRead);
fs.Close();
Console.WriteLine("Row " + rows + ": Read " + bytesRead + " bytes from table, see test_long" + rows + ".dat");
}
This example just reads the long raw data from Oracle into a byte array, then outputs to a file. Note the InitalLONGFetchSize > 0.

I use this class :my database is informix and the images are stored in Byte type .Hope this can help you.
public class MyPhoto
{
public static Stream RetrievePhoto()
{
DBConnection DAL_Helper = new DBConnection(ConfigurationSettings.AppSettings["connection"].ToString());
Byte[] myByteBuff;
Stream myImgStream;
string qry = "----------";
DataTable dt = DAL_Helper.Return_DataTable(qry);
try
{
if (dt.Rows.Count > 0)
{
if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()))
{
myByteBuff = (Byte[])((object)(dt.Rows[0][0]));
myImgStream = new MemoryStream(myByteBuff);
}
else
{
myImgStream = RetrievePhotoNoProfile();
}
}
else
{
myImgStream = RetrievePhotoNoProfile();
}
}
catch (Exception ex)
{
myImgStream = RetrievePhotoNoProfile();
}
return myImgStream;
}
public static byte[] StreamToByteArray(Stream stream)
{
if (stream is MemoryStream)
{
return ((MemoryStream)stream).ToArray();
}
else
{
return ReadFully(stream);
}
}
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[input.Length];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
private static Stream RetrievePhotoNoProfile()
{
string noprofileimgPath = HttpContext.Current.Server.MapPath("~/images/noprofile.png");
System.IO.FileStream fs = new System.IO.FileStream(noprofileimgPath, System.IO.FileMode.Open, FileAccess.Read);
byte[] ba = new byte[fs.Length];
fs.Read(ba, 0, (int)fs.Length);
Stream myImgStream = new MemoryStream(ba);
fs.Close();
return myImgStream;
}
public static Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
}

Related

Download Excel File in .net core web api

I'm trying to create & download the excel file in asp .net core web api. Whenever I hit the service from postman or Advanced Rest Client, Instead of downloading the file I'm getting the JSON data of the file content as response. My code is like below :
[HttpGet]
[Route("GetLogsPdfORExcel")]
public IActionResult GetLogsPdfORExcel()
{
var result = _dataContext.GetLogsPdfORExcel();
if (result != null)
{
this.ExportExcel(result);
}
return Ok(result);
}
public FileStreamResult ExportExcel(DataTable dt)
{
string excelName = "LogsRecord";
ExcelPackage package = new ExcelPackage();
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("sheet1");
int currentRowNo = 5;
int totalRows = dt.Rows.Count;
int k = 0;
foreach (DataColumn column in dt.Columns)
{
worksheet.Cells[currentRowNo, k + 1].Value = column.ColumnName;
k++;
}
currentRowNo++;
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
worksheet.Cells[currentRowNo, j + 1].Value = Convert.ToString(dt.Rows[i][j]);
}
currentRowNo++;
}
int columnCount = dt.Columns.Count;
for (int i = 1; i <= columnCount; i++)
worksheet.Column(i).AutoFit();
worksheet.Row(1).Height = 55;
worksheet.SelectedRange["A1"].Style.Font.Size = 14;
worksheet.Row(5).Style.Font.Bold = true;
using (var memoryStream = new MemoryStream())
{
memoryStream.Position = 0;
var contentType = "application/octet-stream";
var fileName = "fileName.xlsx";
return File(memoryStream, contentType, fileName);
}
}
Here whenever I hit my service, I need directly my file needs to get download.
Return the file stream result and not the datatable.
[HttpGet]
[Route("GetLogsPdfORExcel")]
public IActionResult GetLogsPdfORExcel() {
var result = _dataContext.GetLogsPdfORExcel();
if (result != null) {
return this.ExportExcel(result);
}
return BadRequest(); //Or some other relevant response.
}
Also no need to dispose of the stream since the FileStreamResult will dispose of it when done
//...
var memoryStream = new MemoryStream();
using (var package = new ExcelPackage(memoryStream)) { //<<< pass stream
//...populate package
package.Save();
}
memoryStream.Position = 0;
var contentType = "application/octet-stream";
var fileName = "fileName.xlsx";
return File(memoryStream, contentType, fileName);

The UWP application use too many memory when I use Stream

I create a app to read ZipArchive(100+ photo),And Use Stream, MemoryStream, IRandomAccessStream, and BinaryReader to setSource of the bitmapImage.
private byte[] GetBytes(ZipArchiveEntry entity)
{
Stream stream = entity.Open();
MemoryStream ms = new MemoryStream();
BinaryReader reader = null;
byte[] imageData = null;
try
{
stream.CopyTo(ms);
imageData = new byte[ms.Length];
string fileclass = "";
reader = new BinaryReader(ms);
ms.Seek(0, 0);
imageData = reader.ReadBytes((int)ms.Length);
//Verify png jpg bmp
some code and return imageData
//throw exception,return null
else
{
throw new Exception();
}
}
catch (Exception ex)
{
return null;
}
//Dispose
}
BitmapImage.SetSource by byte[]
public async Task<MangaPageEntity> GetImageFromZipArchiveEntry(ZipArchiveEntry entity, int index)
{
MangaPageEntity mpe = new MangaPageEntity();
mpe.Index = index;
IRandomAccessStream iras = null;
try
{
byte[] data = GetBytes(entity);
iras = data.AsBuffer().AsStream().AsRandomAccessStream();
iras.Seek(0);
await mpe.Picture.SetSourceAsync(iras);
}//catch and dispose
return mpe;
In this way, It use too many memory too run at phone ..
Try to put your streams and other IDisposable into using statement:
private byte[] GetBytes(ZipArchiveEntry entity)
{
using (Stream stream = entity.Open())
using (MemoryStream ms = new MemoryStream())
{
byte[] imageData = null;
try
{
stream.CopyTo(ms);
imageData = new byte[ms.Length];
string fileclass = "";
using (BinaryReader reader = new BinaryReader(ms))
{
ms.Seek(0, 0);
imageData = reader.ReadBytes((int)ms.Length);
}
//Verify png jpg bmp some code and return imageData
//throw exception,return null
else
{
throw new Exception();
}
}
catch (Exception ex)
{
return null;
}
}
//Dispose
}
public async Task<MangaPageEntity> GetImageFromZipArchiveEntry(ZipArchiveEntry entity, int index)
{
MangaPageEntity mpe = new MangaPageEntity();
mpe.Index = index;
try
{
byte[] data = GetBytes(entity);
using (IRandomAccessStream iras = data.AsBuffer().AsStream().AsRandomAccessStream())
{
iras.Seek(0);
await mpe.Picture.SetSourceAsync(iras);
}
}//catch and dispose
return mpe;
}
When your code leaves using it calls Dispose(). Some more to read: Uses of “using” in C#, What is the C# Using block and why should I use it? and probably some more.

mvc 4 asp.net - export data to .csv from a local .xls file

I would be grateful if you could please help me with the code below: I am fairly new to C# and Razor. I am trying to get data from an excel sheet and displaying it on the screen using a jQuery Jtable. I can get it to be displayed but its not exporting the data to CSV file. I am using MVC 4 Razor ASP.NET
here's my controller action code:
private void ExportToCsv(object sender, System.EventArgs e)
{
string Path = #"C:\\5Newwithdate.xls";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
con.Close();
System.Data.DataTable data = new System.Data.DataTable();
da.Fill(data);
SQLDBBillingProvider sql = new SQLDBBillingProvider();
// var billingList = sql.GetAllBilling(jtStartIndex, jtPageSize, jtSorting);
// data.Rows.OfType<DataRow>().Select(dr => dr.Field<MyType>(columnName)).ToList();
List<TopPlayed> daa = new List<TopPlayed>();
foreach (DataRow p in data.Rows)
{
//daa.Add(p.Field<string>("Track Statistics"));
//daa.Add(p.Field<string>("Track Name"));
TopPlayed top = new TopPlayed()
{
TrackID = p.Field<double>("ID").ToString(),
TrackName = p.Field<string>("Track Name"),
ArtistName = p.Field<string>("Artist Name"),
Times = p.Field<double>("NoOfPlays").ToString()
};
daa.Add(top);
}
var toptracks = new List<TopPlayed>();
// toptracks.Add(GetHeader());
int k = -5;
for (int i = 0; i < 5; i++)
{
//static data
var trackInfo = new TopPlayed();
trackInfo.TrackID = "abc" + i;
trackInfo.TrackName = "xyz" + i;
trackInfo.ArtistName = "" + i;
trackInfo.Times = "" + i;
toptracks.Add(trackInfo);
}
System.Web.UI.WebControls.GridView gridvw = new System.Web.UI.WebControls.GridView();
gridvw.DataSource = toptracks.ToList().Take(7); //bind the datatable to the gridview
gridvw.DataBind();
Response.ClearContent();
Response.ContentType = "application/vnd.ms-excel;name='Excel'";
Response.AddHeader("content-disposition", "attachment;filename=TopTracks.csv");
StringWriter swr = new StringWriter();
HtmlTextWriter tw = new HtmlTextWriter(swr);
gridvw.RenderControl(tw);
Response.Write(swr.ToString());
Response.End();
}
Thanks in advance.
From an existing, working, project:
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
var sw = new StreamWriter(new MemoryStream());
// Write the strings here..
sw.WriteLine(...) etc
// Flush the stream and reset the file cursor to the start
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.Begin);
// return the stream with Mime type
return new FileStreamResult(sw.BaseStream, "text/csv");
Just tweak the variables to suit your filename and data writing method.
e.g.
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
var sw = new StreamWriter(new MemoryStream());
// Write the data here..
HtmlTextWriter tw = new HtmlTextWriter(sw);
gridvw.RenderControl(tw);
// Flush the stream and reset the file cursor to the start
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.Begin);
// return the stream with Mime type
return new FileStreamResult(sw.BaseStream, "text/csv");
In the context of your original question it will look something like:
public ActionResult ExportToCsv()
{
string Path = #"C:\\5Newwithdate.xls";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
con.Close();
System.Data.DataTable data = new System.Data.DataTable();
da.Fill(data);
SQLDBBillingProvider sql = new SQLDBBillingProvider();
// var billingList = sql.GetAllBilling(jtStartIndex, jtPageSize, jtSorting);
// data.Rows.OfType<DataRow>().Select(dr => dr.Field<MyType>(columnName)).ToList();
List<TopPlayed> daa = new List<TopPlayed>();
foreach (DataRow p in data.Rows)
{
//daa.Add(p.Field<string>("Track Statistics"));
//daa.Add(p.Field<string>("Track Name"));
TopPlayed top = new TopPlayed()
{
TrackID = p.Field<double>("ID").ToString(),
TrackName = p.Field<string>("Track Name"),
ArtistName = p.Field<string>("Artist Name"),
Times = p.Field<double>("NoOfPlays").ToString()
};
daa.Add(top);
}
var toptracks = new List<TopPlayed>();
// toptracks.Add(GetHeader());
int k = -5;
for (int i = 0; i < 5; i++)
{
//static data
var trackInfo = new TopPlayed();
trackInfo.TrackID = "abc" + i;
trackInfo.TrackName = "xyz" + i;
trackInfo.ArtistName = "" + i;
trackInfo.Times = "" + i;
toptracks.Add(trackInfo);
}
System.Web.UI.WebControls.GridView gridvw = new System.Web.UI.WebControls.GridView();
gridvw.DataSource = toptracks.ToList().Take(7); //bind the datatable to the gridview
gridvw.DataBind();
HttpContext.Response.ClearContent();
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=filename=TopTracks.csv");
HttpContext.Response.AddHeader("Expires", "0");
var sw = new StreamWriter(new MemoryStream());
// Write the data here..
HtmlTextWriter tw = new HtmlTextWriter(sw);
gridvw.RenderControl(tw);
// Flush the stream and reset the file cursor to the start
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.Begin);
// return the stream with Mime type
return new FileStreamResult(sw.BaseStream, "text/csv");
}

convert Emgu image to array and from array to image

I want you to know the methods to get the image from array of bytes :
I'am using this code but it's throw an exception ,if the size is more than 100 or the length of the arary,and if it's less than 50 it save a messay image
Bitmap b = new Bitmap(#"C:/difflena.jpg");
byte[] pixels = lolo(b);
MemoryStream stream = new MemoryStream(pixels, 0, pixels.Length);
Bitmap bitmap = new Bitmap(stream);
Image<Gray, byte> image = new Image<Gray, byte>(60, 60);
image.Bytes = pixels;
image.Save(file + "face" + "t" + ".bmp");
if (image != null) { Label1.Text = "yes";
public byte[] lolo(Bitmap n)
{
/*ImageFormat imageFormat = n.RawFormat;
byte[] Ret=null;
try
{
using (MemoryStream ms = new MemoryStream())
{
n.Save(ms, imageFormat);
Ret = ms.ToArray();
}
}
catch (Exception) { Label1.Text = "no"; }
return Ret;}

Silverlight 3 File Dialog Box

Ok - I have a WCF Service which reads an excel file from a certain location and strips the data into an object. What I need is the ability to allow users of my program to Upload an excel sheet to the file location that my Service uses.
Alternitivley I could pass the Uploaded excel sheet to the service directly.
Can anyone help with this. My service code is:
public List<ImportFile> ImportExcelData(string FileName)
{
//string dataSource = Location + FileName;
string dataSource = Location;
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() + ";Extended Properties=Excel 8.0;";
var con = new OleDbConnection(conStr);
con.Open();
var data = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
var sheetName = data.Rows[0]["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheetName + "] WHERE Status = '4'", con);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds, "Employees");
DataTable dt = ds.Tables[0];
var _impFiles = new List<ImportFile>();
foreach (DataRow row in dt.Rows)
{
var _import = new ImportFile();
_import.PurchaseOrder = row[4].ToString();
try
{
var ord = row[8].ToString();
DateTime dati = Convert.ToDateTime(ord);
_import.ShipDate = dati;
}
catch (Exception)
{
_import.ShipDate = null;
}
ImportFile additionalData = new ImportFile();
additionalData = GetAdditionalData(_import.PurchaseOrder);
_import.NavOrderNo = additionalData.NavOrderNo;
_import.IsInstall = additionalData.IsInstall;
_import.SalesOrderId = additionalData.SalesOrderId;
_import.ActivityID = additionalData.ActivityID;
_import.Subject = additionalData.Subject ;
_import.IsMatched = (_import.ShipDate != null & _import.NavOrderNo != "" & _import.NavOrderNo != null & _import.ShipDate > DateTime.Parse("01/01/1999") ? true : false);
_import.UpdatedShipToField = false;
_import.UpdatedShipToFieldFailed = false;
_import.CreateNote = false;
_import.CreateNoteFailed = false;
_import.CompleteTask = false;
_import.CompleteTaskFailed = false;
_import.FullyCompleted = 0;
_import.NotCompleted = false;
_impFiles.Add(_import);
}
oleda.Dispose();
con.Close();
//File.Delete(dataSource);
return _impFiles;
}
You will want to modify your service to accept a Stream instead of a filename, then you can save if off to a file (or parse it directly from the Stream, although I don't know how to do that).
Then in your Silverlight app you could do something like this:
private void Button_Click(object sender, RoutedEventArgs ev)
{
var dialog = new OpenFileDialog();
dialog.Filter = "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm|All Files (*.*)|*.*";
if (dialog.ShowDialog() == true)
{
var fileStream = dialog.File.OpenRead();
var proxy = new WcfService();
proxy.ImportExcelDataCompleted += (s, e) =>
{
MessageBox.Show("Import Data is at e.Result");
// don't forget to close the stream
fileStream.Close();
};
proxy.ImportExcelDataAsync(fileStream);
}
}
You could also have your WCF service accept a byte[] and do something like this.
private void Button_Click(object sender, RoutedEventArgs ev)
{
var dialog = new OpenFileDialog();
dialog.Filter = "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm|All Files (*.*)|*.*";
if (dialog.ShowDialog() == true)
{
var length = dialog.File.Length;
var fileContents = new byte[length];
using (var fileStream = dialog.File.OpenRead())
{
if (length > Int32.MaxValue)
{
throw new Exception("Are you sure you want to load > 2GB into memory. There may be better options");
}
fileStream.Read(fileContents, 0, (int)length);
}
var proxy = new WcfService();
proxy.ImportExcelDataCompleted += (s, e) =>
{
MessageBox.Show("Import Data is at e.Result");
// no need to close any streams this way
};
proxy.ImportExcelDataAsync(fileContents);
}
}
Update
Your service could look like this:
public List<ImportFile> ImportExcelData(Stream uploadedFile)
{
var tempFile = HttpContext.Current.Server.MapPath("~/uploadedFiles/" + Path.GetRandomFileName());
try
{
using (var tempStream = File.OpenWrite(tempFile))
{
uploadedFile.CopyTo(tempStream);
}
//string dataSource = Location + FileName;
string dataSource = tempFile;
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() +
";Extended Properties=Excel 8.0;";
var con = new OleDbConnection(conStr);
con.Open();
}
finally
{
if (File.Exists(tempFile))
File.Delete(tempFile);
}
}
Thanks Bendewey that was great. Had to amend it slightly -
My Service:
var tempFile = #"c:\temp\" + Path.GetRandomFileName();
try
{
int length = 256;
int bytesRead = 0;
Byte[] buffer = new Byte[length];
// write the required bytes
using (FileStream fs = new FileStream(tempFile, FileMode.Create))
{
do
{
bytesRead = uploadedFile.Read(buffer, 0, length);
fs.Write(buffer, 0, bytesRead);
}
while (bytesRead == length);
}
uploadedFile.Dispose();
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() + ";Extended Properties=Excel 8.0;";
var con = new OleDbConnection(conStr);
Thanks Again for your help

Resources