How to save 1 file PDF to SQL Server with WinForm - c#

Code query database:
I can't save the PDF files to my database, I have a serious problem in the database storage area.
public void ADDWORK(String MAW, string NAMEW, string IDUSER, bool Image,string room, byte[] document,string content,bool donework)
{
String strSql = string.Format("INSERT INTO WORK(IDWORD,NAMEWORk,IDUSER,IMAGES,IDROOM,DOCUMENTS,CONTENT,DONEWORK)VALUES('{0}',N'{1}',N'{2}','{3}',N'{4}',N'{5}',N'{6}',N'{7}')"
, MAW, NAMEW, IDUSER, Image,room,document,content,donework);
db.ExecuteNonQuery(strSql);
}
Code call function:
byte[] pdf;
public void UploadFlie(string file)
{
FileStream fileStream = File.OpenRead(file);
byte[] contents = new byte[fileStream.Length];
fileStream.Read(contents, 0, (int)fileStream.Length);
fileStream.Close();
pdf = contents;
}
private void button1_Click(object sender, EventArgs e)
{
UploadFlie(filename);
dg.ADDWORK(idword, textBox1.Text,"1", false,"ROOM1", pdf, richTextBox1.Text, false);
MessageBox.Show("Done!");
}

here is my example how to get any file and save it on database.
I use two diffrent methods
Saving byte array.
Saving Stream
First you need to create column varbinary(MAX) in my case I called it - PdfFile
and PdfExtn column to save the type of the file As varchar(10) (You can use 4).
Saving byte array:
private void btnGetFile_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
string extn = new FileInfo(file).Extension;
try
{
byte[] fileBytes = File.ReadAllBytes(file);
string cmd = "INSERT INTO Employee(Id,FirstName,LastName,Email,Password,PdfFile,FileExtn) VALUES (#Id,#FirstName,#LastName,#Email,#Password,#PdfFile,#FileExtn)";
List<SqlParameter> l = new List<SqlParameter>();
l.Add(new SqlParameter("#Id", "101"));
l.Add(new SqlParameter("#FirstName", "Aviv"));
l.Add(new SqlParameter("#LastName", "Halevy"));
l.Add(new SqlParameter("#Email", "Assadsa#gmail.com"));
l.Add(new SqlParameter("#Password", "123456"));
SqlParameter sp = new SqlParameter("#PdfFile", SqlDbType.VarBinary, -1);
sp.Value = fileBytes;
l.Add(sp);
l.Add(new SqlParameter("#FileExtn", extn));
if (DAL.Database.ParametersCommand(cmd, l) > 0)
textBox1.Text = "SUCCESS! Save with byte array";
}
catch (IOException ex)
{
}
}
}
Write the file from bytes:
private void btnReadFromDb_Click(object sender, EventArgs e)
{
string cmd = "SELECT * FROM Employee WHERE Id = '101'";
string path = "YOUR_PATH\\Test";
DataTable dt = DAL.Database.GetDataTable(cmd);
if (dt != null && dt.Rows.Count > 0)
{
Byte[] file = (Byte[])dt.Rows[0]["PdfFile"];
string extn = dt.Rows[0]["FileExtn"].ToString();
path = Path.Combine(path, "Test321"+extn);
File.WriteAllBytes(path, file);
Process.Start(path);
}
}
And the result:
Using Stream
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
using (Stream stream = File.OpenRead(file))
{
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
string extn = new FileInfo(file).Extension;
string cmd = "INSERT INTO Employee(Id,FirstName,LastName,Email,Password,PdfFile,FileExtn) VALUES (#Id,#FirstName,#LastName,#Email,#Password,#PdfFile,#FileExtn)";
List<SqlParameter> l = new List<SqlParameter>();
l.Add(new SqlParameter("#Id", "102"));
l.Add(new SqlParameter("#FirstName", "Aviv"));
l.Add(new SqlParameter("#LastName", "Halevy"));
l.Add(new SqlParameter("#Email", "Assadsa#gmail.com"));
l.Add(new SqlParameter("#Password", "123456"));
l.Add(new SqlParameter("#PdfFile", buffer));
l.Add(new SqlParameter("#FileExtn", extn));
if (DAL.Database.ParametersCommand(cmd, l) > 0)
textBox1.Text = "SUCCESS! Save with Stream";
}
}
}
Write the file from stream:
private void button2_Click(object sender, EventArgs e)
{
string cmd = "SELECT * FROM Employee WHERE ID = '102'";
string path = "YOUR_PATH\\Test";
DataTable dt = DAL.Database.GetDataTable(cmd);
if (dt != null && dt.Rows.Count > 0)
{
Byte[] file = (Byte[])dt.Rows[0]["PdfFile"];
string extn = dt.Rows[0]["FileExtn"].ToString();
path = Path.Combine(path, "Test123"+extn);
File.WriteAllBytes(path, file);
Process.Start(path);
}
}
And the result:
Note:
In my examples the DAL project has a static methods that runs my sql commands.

Related

C# writing into excel files by using XLWorkbook

Sample Excel to be imported:
Data
First
Second
Third
My code at the moment:
private void button5_Click(object sender, EventArgs e)
{
OpenFileDialog ope = new OpenFileDialog();
ope.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
if (ope.ShowDialog() == DialogResult.Cancel)
return;
FileStream stream = new FileStream(ope.FileName, FileMode.Open);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet ds = excelReader.AsDataSet();
int counter = 1;
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
if (table.Rows.IndexOf(dr) != 0)
{
string SINs = Convert.ToString(dr[1]);
textBox7.Text = SINs;
Console.WriteLine(SINs);
Console.WriteLine(counter);
var wb = new XLWorkbook();
var worksheet = wb.Worksheets.Add("SINS");
for (int i=1; i<counter; i++)
{
worksheet.Cell(i, 1).Value = SINs;
}
wb.SaveAs("C:\\Users\\WYCHIN\\Desktop\\YONG_TEMP\\DHL API\\Sins.xlsx");
counter++;
}
}
}
}
What i wanted to be imported into the Sins.xlsx without header:
No Header
First
Second
Third
What i get from my code above:
No header
Third
Third
Third
Did i messed up my logic here?
Thanks in advance!
You should take lines
var wb = new XLWorkbook();
var worksheet = wb.Worksheets.Add("SINS");
and
wb.SaveAs("C:\\Users\\WYCHIN\\Desktop\\YONG_TEMP\\DHL API\\Sins.xlsx");
out of the loop.
For each row you're creating new worksheet and saving xlsx file.
I cannot test it (I don't have your DataTables), but you should try something like this:
private void button5_Click(object sender, EventArgs e)
{
OpenFileDialog ope = new OpenFileDialog();
ope.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
if (ope.ShowDialog() == DialogResult.Cancel)
return;
FileStream stream = new FileStream(ope.FileName, FileMode.Open);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet ds = excelReader.AsDataSet();
int counter = 1;
var wb = new XLWorkbook();
var worksheet = wb.Worksheets.Add("SINS");
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
string SINs = Convert.ToString(dr[1]);
textBox7.Text = SINs;
Console.WriteLine(SINs);
Console.WriteLine(counter);
for (int i=1; i<counter; i++)
{
worksheet.Cell(i, 1).Value = SINs;
}
counter++;
}
}
wb.SaveAs("C:\\Users\\WYCHIN\\Desktop\\YONG_TEMP\\DHL API\\Sins.xlsx");
}
EDIT: removed unnecessary checking for row index.
Thank you for your kind assistance and suggestion, i have solved it by doing modification at the code below.
private void button5_Click(object sender, EventArgs e)
{
OpenFileDialog ope = new OpenFileDialog();
ope.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
if (ope.ShowDialog() == DialogResult.Cancel)
{
return;
}
FileStream stream = new FileStream(ope.FileName, FileMode.Open);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet ds = excelReader.AsDataSet();
int counter = 1;
var wb = new XLWorkbook();
var worksheet = wb.Worksheets.Add("SINS");
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
if(table.Rows.IndexOf(dr) != 0)
{
string SINs = Convert.ToString(dr[1]);
textBox7.Text = SINs;
Console.WriteLine(SINs); //debug line
Console.WriteLine(counter); //debug line
worksheet.Cell(counter, 1).Value = SINs; //writes to the excel
counter++;
}
}
}
wb.SaveAs("C:\\Users\\WYCHIN\\Desktop\\YONG_TEMP\\DHL API\\Sins.xlsx");
}

How to display image from database in c#

How to display image from database in c#. I am getting below error:-
Parameter Is Not Valid
private void btnSearch_Click(object sender, EventArgs e)
{
try
{
Utilities.ClearControls(gbxMain);
AssociateID = 0;
MainModuleBO objMainModuleBO = new MainModuleBO();
string[] strReturnValue;
DataTable dtSearch = objMainModuleBO.GetSearchData(this.MasterFormId);
DataGridViewColumnPropertiesCollection objDataGridViewColumnPropertiesCollection = new DataGridViewColumnPropertiesCollection();
objDataGridViewColumnPropertiesCollection.Add(MSTAssociateMasterTO.ASSOCIATEID, "Associate Id", MSTAssociateMasterTO.ASSOCIATEID, true, true, 100);
objDataGridViewColumnPropertiesCollection.Add(MSTAssociateMasterTO.ASSOCIATENAME, "Associate Name", MSTAssociateMasterTO.ASSOCIATENAME, true, false, 500);
frmSearch objfrmSearch = new frmSearch();
objfrmSearch.dtSearch = dtSearch;
objfrmSearch.objDataGridViewColumnPropertiesCollection = objDataGridViewColumnPropertiesCollection;
objfrmSearch.ShowDialog();
strReturnValue = objfrmSearch.strReturnValue;
if (strReturnValue.Length > 0)
{
MSTAssociateMasterBO objMSTAssociateMasterBO = new MSTAssociateMasterBO();
DataTable dt = objMSTAssociateMasterBO.SelectDataById(Utilities.TextToInt(strReturnValue[0]));
AssociateID = Utilities.TextToInt(strReturnValue[0]);
Utilities.BindFormData(this, dt);
pictureBox1.Image = null;
foreach (DataRow dr1 in dt.Rows)
{
picbyte = (byte[])dr1["AssociateImageData"];
MemoryStream ms = new MemoryStream(picbyte);
pictureBox1.Image = Bitmap.FromStream(ms); // here is error occure
}
Utilities.EnableDisableControls(gbxMain, false);
Utilities.EnableDisableButtons(this, CustomControls.ButtonEvent.SearchClick);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);// (this.Controls.Find("txtName", true)[0].GetType().ToString());
}
}

How to save images in sql server using winform?

i am trying to save images like bmp,jpg,gif & png into sql server database. but not able to save all the formats into database. Only png image is getting saved into database. if trying to save jpeg, .bmp & .gif images, it's showing error "A generic error occured in GDI+". What is the problem?
private void InitializeOpenFileDialog()
{
try
{
this.openFileDialog1 = new OpenFileDialog();
// Set the file dialog to filter for graphics files.
this.openFileDialog1.Filter = "Images (*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG|" + "All files (*.*)|*.*";
//"image files|*.jpg;*.png;*.gif;*.bmp;.*;";
// Allow the user to select multiple images.
this.openFileDialog1.Multiselect = true;
this.openFileDialog1.Title = "My Image Browser";
}
catch(Exception es){
MessageBox.Show(es.Message);
}
}
//load picture
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void button2_Click(object sender, EventArgs e)
{
try
{
MemoryStream ms1 = new MemoryStream();
pictureBox2.Image.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);
// byte[] img_arr1 = ms1.ToArray();
byte[] img_arr1 = new byte[ms1.Length];
ms1.Read(img_arr1, 0, img_arr1.Length);
SqlConnection con = new SqlConnection(#"data source=xdfgh\ALEXDAVE;database=x1234;UID=sa;password=x67890");
con.Open();
SqlCommand cmd = new SqlCommand("insert into myTable(enrolmentno,aadhaarno,name,fname,address,dob,gender,picimage)values(#a,#b,#c,#d,#e,#f,#g,#h)", con);
cmd.Parameters.AddWithValue("#a", enrolmentno_txt.Text);
cmd.Parameters.AddWithValue("#b", aadhaarno_txt.Text);
cmd.Parameters.AddWithValue("#c", name_txt.Text);
cmd.Parameters.AddWithValue("#d", fname_txt.Text);
cmd.Parameters.AddWithValue("#e", address_txt.Text);
cmd.Parameters.AddWithValue("#f", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#g", gender);
cmd.Parameters.AddWithValue("#h", img_arr1);
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("Data inserted successfully");
else
MessageBox.Show("Data is not inserted in database");
con.Close();
}
catch(Exception es){
MessageBox.Show(es.Message);
}
}
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
this.Activate();
string[] files = openFileDialog1.FileNames;
try
{
foreach (string file in files)
{
FileInfo fileInfo = new FileInfo(file);
FileStream fileStream = fileInfo.OpenRead();
pictureBox2.Image = Image.FromStream(fileStream);
Application.DoEvents();
fileStream.Close();
}
}
//es
catch (Exception)
{
MessageBox.Show("please select only image files.");
}
}
Are you sure the the image is valid?
What line are you getting the error on?
Like the error indicates, it's a GDI error, and not a SQL Error.
You can remove the need for GDI by replacing the following lines of code
MemoryStream ms1 = new MemoryStream();
pictureBox2.Image.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] img_arr1 = new byte[ms1.Length];
ms1.Read(img_arr1, 0, img_arr1.Length);
with this
byte[] img_arr1 = System.IO.File.ReadAllBytes(fileName);
where fileName is the file that was selected

Visual C# Express. Data can be save but until I close Visual C#

This Is the code for Adding the new Item...
private KrystalCafeDatabaseEntities kce = new KrystalCafeDatabaseEntities();
private Byte[] byteBLOBData;
public AddItem()
{
InitializeComponent();
cmbCategory.DataSource = kce.tblItemTypes;
cmbCategory.DisplayMember = "Name";
cmbCategory.ValueMember = "ItemType";
}
private void btnUpload_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
FileStream fsBLOBFile = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
byteBLOBData = new Byte[fsBLOBFile.Length];
fsBLOBFile.Read(byteBLOBData, 0, byteBLOBData.Length);
fsBLOBFile.Close();
MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
pbImage.Image = Image.FromStream(stmBLOBData);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
tblItem Item = new tblItem();
Item.Name = txtName.Text;
Item.Price = decimal.Parse(txtPrice.Text);
Item.Image = byteBLOBData;
Item.ItemType = (int)cmbCategory.SelectedValue;
kce.AddTotblItems(Item);
kce.SaveChanges();
MessageBox.Show("Record Saved! :D");
}
}
}
The program runs normally but the data will only be stored for awhile, then If i either closed my program or edit my code the data I just added will be lost.
One likely error is that KrystalCafeDatabaseEntities opens a transaction and you need to commit that transaction after calling SaveChanges.

Can not upload file from C# (WPF) FTP

i have created a small ftp program in c# using winforms but when i try to create this in wpf it is showing me an error "Value cannot be null. Parameter name:fileName", The code works fine in winform.
here is the code:
public partial class Ftp : UserControl
{
string filePath;
public Ftp()
{
InitializeComponent();
}
//Clear TextBox when clicked
#region textBox clear
public void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
//TextBox tb = (TextBox)sender;
//tb.Text = string.Empty;
//tb.GotFocus -= TextBox_GotFocus;
}
#endregion
//Open File Dialog
private void browser_click(object sender, RoutedEventArgs e)
{
#region File Dialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.CheckFileExists = true;
dlg.DefaultExt = ".txt";
dlg.Filter = "JPEG Files (*.txt)|*.txt|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
dlg.FileName = "";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
// Open document
string filename = dlg.FileName;
pathtext.Text = filename;
}
#endregion
}
//Upload the File to FTP
private void Upload_click(object sender, RoutedEventArgs e)
{
#region Upload files
if (filePath == "")
{
MessageBox.Show("Please Select The File To Upload..");
}
else
{
browser.IsEnabled = false;
try
{
FileInfo fileInfo = new FileInfo(filePath);
string fileName = fileInfo.Name.ToString();
WebRequest requestFTP = WebRequest.Create("ftp://" + hosttext.Text + "/" + fileName);
requestFTP.Credentials = new NetworkCredential(usertext.Text, passtext.Password);
requestFTP.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fStream = fileInfo.OpenRead();
int bufferLength = 2048;
byte[] buffer = new byte[bufferLength];
Stream uploadStream = requestFTP.GetRequestStream();
int contentLength = fStream.Read(buffer, 0, bufferLength);
while (contentLength != 0)
{
uploadStream.Write(buffer, 0, contentLength);
contentLength = fStream.Read(buffer, 0, bufferLength);
}
uploadStream.Close();
fStream.Close();
requestFTP = null;
MessageBox.Show("File Uploading Is SuccessFull...");
}
catch (Exception ep)
{
MessageBox.Show("ERROR: " + ep.Message.ToString());
}
browser.IsEnabled = true;
filePath = "";
hosttext.Text = usertext.Text = passtext.Password = pathtext.Text = "";
}
#endregion
}
}
You never set your filePath variable, so it's null. In browser_click you need to do something like
if (result == true)
{
// Open document
string filename = dlg.FileName;
filePath = filename; //added this line
pathtext.Text = filename;
}
Also, you think you have handled your invalid string here:
if (filePath == "")
but at that point filePath = null.
Instead, use if (string.IsEmptyOrNull(filePath))

Categories