I want to insert and read pdf blop to oracle with c#.I tried to do something below.I need insert oracle blop pdf file with C#.I am using this code
var fs = new FileStream(txtFileName.Text, FileMode.Open, FileAccess.Read);
var blobByte = new byte[fs.Length];
fs.Read(blobByte, 0, Convert.ToInt32(fs.Length));
fs.Close();
id=nextİd("tablename")//take ID_SEQ.NEXTVAL
var con = new racleConnection(System.Configuration.ConfigurationSettings.AppSettings["Orclsys"]);
var cmd = new OracleCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO tablename values(:id,:blopfile )";
OracleTransaction sqlTrans = con.BeginTransaction();
cmd.Transaction = sqlTrans;
try
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue(":id", Id);
var blobParameter = new OracleParameter();
blobParameter.OracleType = OracleType.Blob;
blobParameter.ParameterName = ":blopfile ";
blobParameter.Value = blobByte;
cmd.Parameters.Add(blobParameter);
cmd.ExecuteNonQuery();
Result = true;
sqlTrans.Commit();
}
catch(Exception ex)
{
}
finally
{
con.Close();
con.Dispose();
sqlTrans.Dispose();
cmd.Dispose();
}
so I want read this file from db and i am starting code but I can not continue.
How can I continue after.could you help me.!!
try
{
orcl.Connect(DbUser.System);
orcl.CommandText = "SELECT blopfile FROM tablename WHERE id= :id";
orcl.ClearParameters();
orcl.AddParameter(":id", id);
orcl.ExecuteDataReader();
var lob = orcl.DataReader.GetOracleLob(0);
var pdffile= new Bitmap(lob);
//
//how can I continue code here....
//
}
catch(Exception ex)
{
}
Related
I´m having some issue inserting a new record to this table.
Though can't seem to find the real issue within my code.
try
{
conn = new MySqlConnection(cs.ConnString);
conn.Open();
cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into Depense_Vehicule (Code,Date,Responsable,Source_Cr,Numero_Plaque_Dt,Possession,Chauffeur,Categorie,Type,Libelle,Montant_$,Montant_FC,Taux_Echange,Total_$,Status)" +
"VALUES (#d1,#d2,#d3,#d4,#d5,#d6,#d7,#d8,#d9,#d10,#d11,#d12,#13,#14,#15)";
cmd.Parameters.AddWithValue("d1", Code_ADV_txt.Text);
cmd.Parameters.AddWithValue("d2", Date_ADVe_dt.Text);
cmd.Parameters.AddWithValue("d3", Responsable_ADV_txt.Text);
cmd.Parameters.AddWithValue("d4", Source_ADV_cb.Text);
cmd.Parameters.AddWithValue("d5", Numero_Plaque_ADV_txt.Text);
cmd.Parameters.AddWithValue("d6", Possesion_ADV_txt.Text);
cmd.Parameters.AddWithValue("d7", Chauffeur_ADV_cb.Text);
cmd.Parameters.AddWithValue("d8", Categorie_ADV_cb.Text);
cmd.Parameters.AddWithValue("d9", Type_Payment_ADV_cb.Text);
cmd.Parameters.AddWithValue("d10", Libelle_ADV_txt.Text);
cmd.Parameters.AddWithValue("d11", MontantDollars_ADV_txt.Text);
cmd.Parameters.AddWithValue("d12", MontantFranc_ADV_txt.Text);
cmd.Parameters.AddWithValue("d13", TauxEchange_ADV_txt.Text);
cmd.Parameters.AddWithValue("d14", TotalDollars_ADV_txt.Text);
cmd.Parameters.AddWithValue("d15", Status_ADV_cb.Text);
MySqlDataReader myReader;
myReader = cmd.ExecuteReader();
conn.Close();
MessageBox.Show("Record Ajouter");
Source_ADV_cb.SelectedIndex = -1;
Chauffeur_ADV_cb.SelectedIndex = -1;
Numero_Plaque_ADV_txt.Text = "";
Possesion_ADV_txt.Text = "";
Categorie_ADV_cb.SelectedIndex = -1;
Type_Payment_ADV_cb.SelectedIndex = -1;
MontantDollars_ADV_txt.Text = "";
MontantFranc_ADV_txt.Text = "";
TotalDollars_ADV_txt.Text = "";
Status_ADV_cb.SelectedIndex = -1;
Libelle_ADV_txt.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
finally
{
conn.Close();
}
I think you must use cmd.ExecuteNonQuery instead of cmd.ExecuteReader().
ExecuteReader is for run SQL SELECT command.
I hope this answer is useful for you.
Here in the code I'm trying to get all data from SQL Server and the method is used to list an users with their rolls in grid form. My question here is how to call/merge two stored procedures and return one result and am I in right way ? If not please explain it and show me the right way so I can learn it how to do it in future. Thanks.
public IEnumerable<ApplicationUser> GetAllUsers()
{
try
{
List<ApplicationUser> userList = new List<ApplicationUser>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("sp_UsersReadAll", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlCommand cmd2 = new SqlCommand("sp_GetUserRolls", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ApplicationUser apUser = new ApplicationUser();
apUser.Id = Convert.ToString(reader["Id"]);
apUser.UserName = reader["Username"].ToString();
apUser.FirstName = reader["FirstName"].ToString();
apUser.LastName = reader["LastName"].ToString();
apUser.Email = reader["Email"].ToString();
userList.Add(apUser);
}
con.Close();
}
return userList;
}
catch (Exception)
{
throw;
}
}
You can call two stored procedures for one shot and then use Data SqlDataReader.NextResult() to read another result set:
public IEnumerable<ApplicationUser> GetAllUsers()
{
try
{
List<ApplicationUser> userList = new List<ApplicationUser>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(#"exec sp_UsersReadAll
exec sp_GetUserRolls", con);
cmd.CommandType = System.Data.CommandType.Text;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ApplicationUser apUser = new ApplicationUser();
apUser.Id = Convert.ToString(reader["Id"]);
apUser.UserName = reader["Username"].ToString();
apUser.FirstName = reader["FirstName"].ToString();
apUser.LastName = reader["LastName"].ToString();
apUser.Email = reader["Email"].ToString();
userList.Add(apUser);
}
reader.NextResult();
while (reader.Read())
{
ApplicationUserRoll apUserRoll = new ApplicationUserRoll();
apUserRoll.Id = Convert.ToString(reader["Id"]);
apUserRoll.UserId = reader["UserId"].ToString();
userList.Single(u => u.Id == apUserRoll.UserId).Rolls.Add(apUserRoll);
}
con.Close();
}
return userList;
}
catch (Exception)
{
throw;
}
}
Hope it helps.
Something like that should work (i'm considering you want unique id)
public IEnumerable<ApplicationUser> GetAllUsers()
{
try
{
ApplicationUser apUser;
List<ApplicationUser> userList = new List<ApplicationUser>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("sp_UsersReadAll", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlCommand cmd2 = new SqlCommand("sp_GetUserRolls", con);
cmd2.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
apUser = new ApplicationUser();
apUser.Id = Convert.ToString(reader["Id"]);
apUser.UserName = reader["Username"].ToString();
apUser.FirstName = reader["FirstName"].ToString();
apUser.LastName = reader["LastName"].ToString();
apUser.Email = reader["Email"].ToString();
userList.Add(apUser);
}
// You can refactor this code in another method for don't have to write it both
reader = cmd2.ExecuteReader();
while (reader.Read())
{
apUser = new ApplicationUser();
apUser.Id = Convert.ToString(reader["Id"]);
// If id doesn't exists, we can continue and add the item
if(!userList.Exists(o=>o.Id==apUser.Id))
{
apUser.UserName = reader["Username"].ToString();
apUser.FirstName = reader["FirstName"].ToString();
apUser.LastName = reader["LastName"].ToString();
apUser.Email = reader["Email"].ToString();
userList.Add(apUser);
}
}
con.Close();
}
return userList;
}
catch (Exception)
{
// Actually it's like if you had not try / catch
throw;
}
}
I just show you the way, i didn't optimised the code.
There may be many approaches to do this task. For example -
You may create a new procedure which can merge the data for these two procedures and you would have to call one proc only from code.
Call one procedure and retain the list of users and pass user ids to seconds procedure to fetch corresponding roles.
Share output of procedures and attributes of ApplicationUser class if you are looking for more help.
I am trying to save and read back pdf files in a SQL Server CE local database. I was able to save them as binary data in an Image column, but I don't know how to read them back and open the pdf file (original format).
Table Schema
Here is how I stored the PDF files:
try
{
SqlCeConnection con = new SqlCeConnection(#"Data Source = D:\C# Projects\StoreFileSqlCe\StoreFileSqlCe\Test_File_Stotage.sdf");
con.Open();
string filePath = textBox1.Text.ToString();
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(Name, ContentType, Data) values (#Name, #ContentType, #Data)";
SqlCeCommand cmd = new SqlCeCommand(strQuery, con);
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", "application/vnd.ms-word");
cmd.Parameters.AddWithValue("#Data",bytes);
cmd.ExecuteNonQuery();
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
con.Close();
con.Dispose();
}
Try this
try
{
SqlCeConnection con = new SqlCeConnection(#"Data Source = D:\C# Projects\StoreFileSqlCe\StoreFileSqlCe\Test_File_Stotage.sdf");
con.Open();
string strQuery = "select Data where Name = #Name and ContentType = #ContentType";
SqlCeCommand cmd = new SqlCeCommand(strQuery, con);
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", "application/vnd.ms-word");
SqlCeDataReader reader = cmd.ExecuteReader();
if (reader != null)
{
if (reader.Read())
{
byte[] pdf = (byte[])reader["Data"];
File.WriteAllBytes(filename, pdf);
}
}
}
First of all I'm using a FileStream with the server. The server is SQL Server express 2014.
I configured the database and table correctly (I hope) and I was able to upload an image as a varbinary, but when I try to download that image I get an error
An invalid parameter was passed to the function.
Here is the database structure
Records(
[id] [uniqueidentifier] ROWGUIDCOL NOT NULL UNIQUE,
[Name] [varchar](64) NULL,
[Clip] [varbinary](max) FILESTREAM NULL,
)
And the code for downloading the image
private object GetTransactionContext()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()";
cmd.CommandType = CommandType.Text;
cmd.Connection = sql_Connection;
return cmd.ExecuteScalar();
}
private void BeginTransaction()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "BEGIN TRANSACTION";
cmd.CommandType = CommandType.Text;
cmd.Connection = sql_Connection;
cmd.ExecuteScalar();
}
private void CommitTransaction()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "COMMIT TRANSACTION";
cmd.CommandType = CommandType.Text;
cmd.Connection = sql_Connection;
cmd.ExecuteScalar();
}
//Command for reading the data
public async void ReadFromDatabase(string Name)
{
//enter the command parameter
sql_Command_Read.Parameters.Add("#Name", SqlDbType.VarChar).Value = Name;
//open a connection to the server
sql_Connection.Open();
this.BeginTransaction();
//get the path to the BLOB object
string filePath = null;
Object pathObj = sql_Command_Read.ExecuteScalar();
if (DBNull.Value != pathObj)
{
filePath = (string)pathObj;
}
else
{
throw new NotImplementedException();
}
Object obj = this.GetTransactionContext();
byte[] sql_TransactionToken = (byte[])obj;
sql_FileStream = new SqlFileStream(filePath, sql_TransactionToken, FileAccess.ReadWrite, FileOptions.SequentialScan, 0);
byte[] buffer = new byte[(int)sql_FileStream.Length];
sql_FileStream.Seek(0L, SeekOrigin.Begin);
sql_FileStream.Read(buffer, 0, buffer.Length);
File.WriteAllBytes("C:\test.mp4", buffer);
this.CommitTransaction();
}
The content of the command is
sql_Command_Read.CommandText = "SELECT Picture.PathName() FROM Archive.dbo.Records WHERE Name = #Name";
Again I am new to database and sql client programming. Now about the code. The error that I get is on this line:
sql_FileStream = new SqlFileStream(filePath, sql_TransactionToken, FileAccess.ReadWrite, FileOptions.SequentialScan, 0);
and about the parameters here are the values they get:
filePath = "\\\\LAPTOP-PC\\VIDEOPRESENTERDB\\v02-A60EC2F8-2B24-11DF-9CC3-AF2E56D89593\\Archive\\dbo\\Records\\Picture\\C94D4189-9ECF-448B-B05A-ABF9331BF6CE\\VolumeHint-HarddiskVolume2"
obj has 16 numbers ranging from 0 to 255.
I am obviously making a mistake somewhere but I don't know where exactly
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