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.
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");
}
I am creating a program that creates, writes, and saves an xml file. When I try to open the saved file I get an error that says the file cannot be accessed because it is being used by another process. I assumed it was because I didn't close the filestream after I saved the file so I made the correction. I still can't open the file and I receive the same error. I'm not sure what the issue is beyond this point. How can I fix this?
namespace XML_DataSets
{
public partial class FormAddNew : Form
{
XmlSerializer xs;
List<Class1> ls;
//create the DataTable
DataTable dt = new DataTable("Contact");
XDocument xd = new XDocument();
public FormAddNew()
{
InitializeComponent();
ls = new List<Class1>();
xs = new XmlSerializer(typeof(List<Class1>));
//create columns for the DataTable
DataColumn dc1 = new DataColumn("Id");
dc1.DataType = System.Type.GetType("System.Int32");
dc1.AutoIncrement = true;
dc1.AutoIncrementSeed = 1;
dc1.AutoIncrementStep = 1;
//add columns to the DataTable
dt.Columns.Add(dc1);
dt.Columns.Add(new DataColumn("Name"));
dt.Columns.Add(new DataColumn("Age"));
dt.Columns.Add(new DataColumn("Gender"));
//create DataSet
DataSet ds = new DataSet();
ds.DataSetName = "AddressBook";
ds.Tables.Add(dt);
}
private void buttonCreate_Click(object sender, EventArgs e)
{
DataRow row = dt.NewRow();
row["Name"] = textBoxName.Text;
row["Age"] = textBoxAge.Text;
row["Gender"] = textBoxGender.Text;
dt.Rows.Add(row);
dataGridView1.DataSource = dt;
//dt.WriteXml("Contacts.xml");
xd = WriteDt2Xml(dt);
}
public static XDocument WriteDt2Xml(DataTable dt)
{
using (var stream = new MemoryStream())
{
dt.WriteXml(stream);
stream.Position = 0;
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
XmlReader reader = XmlReader.Create(stream, settings);
reader.MoveToContent();
if (reader.IsEmptyElement) { reader.Read(); return null; }
return XDocument.Load(reader);
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
Stream input = null;
OpenFileDialog dialog = new OpenFileDialog();
openFileDialog.Filter = "xml file | *.xml";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((input = openFileDialog.OpenFile()) != null)
{
FileStream fs = new FileStream(#openFileDialog.FileName.ToString(), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
ls = (List<Class1>)xs.Deserialize(fs);
dataGridView1.DataSource = ls;
fs.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR");
}
}
}
}
}
#Daniel Advise taken well...I refactored the code and see the error you referred to. I checked out the two links you provided as examples. I made corrections but I still get the same result.
First change the way you open the file to:
using (var fs = new FileStream(#openFileDialog.FileName, FileMode.Open, FileAccess.Read))
{
ls = (List<Class1>) xs.Deserialize(fs);
dataGridView1.DataSource = ls;
}
an then try to check (Debug) the entire Exception in openToolStripMenuItem_Click event:
System.InvalidOperationException was caught
HResult=-2146233079
Message=There is an error in XML document (2, 2).
Source=System.Xml
StackTrace:
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
at WindowsFormsApplication1.FormAddNew.openToolStripMenuItem_Click(Object sender, EventArgs e) in c:\Users\admin\Documents\Visual Studio 2013\Projects\WindowsFormsApplication1\WindowsFormsApplication1\FormAddNew.cs:line 131
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=<AddressBook xmlns=''> was not expected. --The problem!
Source=Microsoft.GeneratedCode
StackTrace:
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderList1.Read3_ArrayOfClass1()
InnerException:
Then read:
xmlns='' was not expected when deserializing nested classes
{"<user xmlns=''> was not expected.} Deserializing Twitter XML
Update:
You need an atomic object when desalinizing like:
public class AddressBook
{
public AddressBook()
{
Contacts = new List<Contact>();
}
public List<Contact> Contacts { get; set; }
}
public class Contact
{
public int Id { get; set; }
public string Name { get; set; }
public string Age { get; set; }
public string Gender { get; set; }
}
and I would suggest to get rid of xDocument, DataSet & DataTable. they add too much complication for nothing. and I guess the reason u r using them because of DataGrid which is minor concern, focus on coding first:
private readonly XmlSerializer xs;
private AddressBook ls;
private int _counter = 0;
public FormAddNew2()
{
InitializeComponent();
ls = new AddressBook();
xs = new XmlSerializer(typeof(AddressBook));
}
private void buttonCreate_Click(object sender, EventArgs e)
{
var addressBookContact2 = new Contact
{
Id = ++_counter,
Name = textBoxName.Text,
Age = textBoxAge.Text,
Gender = textBoxGender.Text
};
ls.Contacts.Add(addressBookContact2);
dataGridView1.DataSource = null; // strangly u need this
dataGridView1.DataSource = ls.Contacts;
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
var saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = #"C:\";
saveFileDialog.RestoreDirectory = true;
saveFileDialog.Title = "Select save location file name";
saveFileDialog.Filter = "XML-File | *.xml";
if(saveFileDialog.ShowDialog() == DialogResult.OK)
{
using(var writer = new StreamWriter(saveFileDialog.FileName))
{
xs.Serialize(writer, ls);
MessageBox.Show(saveFileDialog.FileName);
}
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "xml file | *.xml";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if(openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
using (var reader = new StreamReader(#openFileDialog.FileName))
{
ls = (AddressBook) xs.Deserialize(reader);
_counter = 0;
dataGridView1.DataSource = ls.Contacts;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "ERROR");
}
}
}
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());
}
}
I have point files like:
I have created code that allows users to select the files from a dialog box and it will populate the data to the gridview.
private void cmdload_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("Point");
table.Columns.Add("X");
table.Columns.Add("Y");
table.Columns.Add("Z");
table.Columns.Add("R");
table.Columns.Add("A");
table.Columns.Add("B");
table.Columns.Add("C");
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "C:\\";
openFileDialog1.Filter = "Data Files (*.PNT)|*.PNT";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
string filename = openFileDialog1.FileName;
using (var reader = File.OpenText(filename))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(' ');
table.Rows.Add(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7]);
}
dataGridView1.DataSource = table;
}
}
}
}
catch (Exception ex) // you need to add the catch block if yo are using try block
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
This code works fine, however the datagridview does not display the value.
If you are not creating the DataGridView columns through code then you have to set the DataPropertyName of the DataGridViewColumn to the columns ids in the DataTable.
Sample code:
dataGridView1.AutoGenerateColumns = false;
DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
col1.Name = "Point";
col1.HeaderText = "Point";
col1.DataPropertyName = "Point";
dataGridView1.Columns.Add(col1)
The other way is to set AutoGenerateColumns property to true to create the required columns automatically and bind the data to the DataTable. By this you don't have to create columns through code like in the above sample code.
dataGridView1.AutoGenerateColumns = true;