Can I store difference file types into SQL Server database? - sql

I have created a vb.net project and a SQL Server database, I want to store my other created projects to the database with some of there description. I don't know can I do that or I can store my projects files into the database in the first place. I wanted to compress my projects files to a zip file and then store the zip file to the database but I don't know if I can store these files to the database which includes a lot of file types like (jar, java, sln, vb, c#, txt ...etc)?
Thanks for your help.

Yes, you can store files in a SQL Server database table. I highly recommend you to compress them into a zip file.
First step is to create a table:
CREATE TABLE Files
(
Id INT IDENTITY PRIMARY KEY,
FileData VARBINARY(MAX) FILESTREAM NULL,
Name NVARCHAR(300)
)
and then open your zip file as stream and Insert it into your table.
OpenFileDialog openFileDlg = new OpenFileDialog();
openFileDlg.InitialDirectory = Directory.GetCurrentDirectory();
if (openFileDlg.ShowDialog() == DialogResult.OK)
{
FileInfo fi = new FileInfo(openFileDlg.FileName);
FileStream fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read);
BinaryReader rdr = new BinaryReader(fs);
byte[] fileData = rdr.ReadBytes((int)fs.Length);
rdr.Close();
fs.Close();
string cs = #"Data Source=<your server>;Initial Catalog=MyFsDb;Integrated Security=TRUE";
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
string sql = "INSERT INTO Files VALUES (#Data, #Name)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#Data", SqlDbType.Image, fileData.Length).Value = fileData;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = fi.Name;
cmd.ExecuteNonQuery();
con.Close();
}
MessageBox.Show(fi.FullName, "File Inserted!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Source : MSDN

Related

Saving objects in a SQL Server database

I am trying to include an object of a class created by me in a SQL Server database. I am trying to convert it to VARBINARY, but the method Add doesn't recognize the VARBINARY type. The error I get is:
VARBINARY : undeclared identifier.
I am using namespaces System.Data and System.Data.SqlClient.
Here is my code:
MemoryStream^ memStream = gcnew MemoryStream();
StreamWriter^ sw = gcnew StreamWriter(memStream);
sw-> Write (eyemax);
SqlConnection^ myConnection = gcnew SqlConnection();
myConnection->ConnectionString = "Data Source = (localdb)\\ProjectsV13;AttachDbFilename\=C:\\Users\\Usuario\\AppData\\Local\\Microsoft\\VisualStudio\\SSDT\\TUKDatabase.mdf; Integrated Security = True; Connect Timeout = 30";
myConnection->Open();
SqlCommand^ cmd = gcnew SqlCommand("INSERT INTO Features(Face,Eye) VALUES (#face, #eye)",myConnection);
cmd->Parameters->AddWithValue("#face", face);
cmd->Parameters->Add("#eye",SqlDbType(VarBinary));
cmd->Parameters["#eye"]->Value = memStream->GetBuffer();

i need to export data to pdf in specfic format

i am using this function to export data from database to pdf but its output like table ... i want to export a specfic row in format like :
id :
Name :
Gender :
Salary :
how do i do this ..
thanks in advance
public void ExportToPDF()
{
SqlCommand cmd = new SqlCommand("SELECT EmployeeId , EmployeeName , EmployeeGender , EmployeeSalary , isActive FROM Employee", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView gridview1 = new GridView();
gridview1.AllowPaging = false;
gridview1.DataSource = ds;
gridview1.DataBind();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=DataSet.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridview1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4 , 10f , 10f , 10f , 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc , Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
Please take a look at the UnitedStates example. For the sake of simplicity, I don't use a database but a CSV file. It should be very easy to adapt the example so that it accepts it data from a database rather than by parsing a CSV.
The key class you need is PdfPTable. For instance, if databaseObject is an object that you created to store the data from your database (e.g. the contents of a record), you need something like this:0
PdfPTable table = new PdfPTable(2);
table.addCell("Id:");
table.addCell(databaseObject.getId());
table.addCell("Name:");
table.addCell(databaseObject.getName());
I see that you are using HTMLWorker in your code. This is problematic for two reasons:
It implies that you first convert all your data to XHTML. This costs processing time and if you don't need XHTML, then that time is wasted.
The HTMLWorker class is obsolete. It is no longer supported. If you do want to convert XHTML tables to PDF, you should use XML Worker as is done in these examples
Obviously, you can solve your problem in many other ways. Watch this video and you'll discover that you could also create a template (see for instance state.pdf) and then fill this form like this:
public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader,
new FileOutputStream(dest));
AcroFields fields = stamper.getAcroFields();
fields.setField("name", "CALIFORNIA");
fields.setField("abbr", "CA");
fields.setField("capital", "Sacramento");
fields.setField("city", "Los Angeles");
fields.setField("population", "36,961,664");
fields.setField("surface", "163,707");
fields.setField("timezone1", "PT (UTC-8)");
fields.setField("timezone2", "-");
fields.setField("dst", "YES");
stamper.close();
reader.close();
}
That is shown in the FillForm example.
It's a pity that, with the abundance of documentation that can be found online (of which I only use a handful of examples), you chose a code snippet that doesn't come close to doing what you wanted to do.

How to save the SQL Server table xml column data in physical path as .xml format?

I have an sql server database table which has xml column name called "MESSAGE" and which will store xml data.
The database table look like,
Now I need to get this "MESSAGE" column data and save into System physical path as xml file(Ex: test.xml etc.,)
Any suggestion how to implement this using c#.net?
You could try something like this (using plain ADO.NET and a very basic SQL query):
static void Main(string[] args)
{
// get connection string from app./web.config
string connectionString = "server=.;database=yourDB;Integrated Security=SSPI;";
// define query
string query = "SELECT MESSAGE FROM dbo.SamTest WHERE ID = 1;";
// set up connection and command
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand selectCmd = new SqlCommand(query, conn))
{
// open connection, execute query to get XML, close connection
conn.Open();
string xmlContents = selectCmd.ExecuteScalar().ToString();
conn.Close();
// define target file name
string targetFileName = #"C:\tmp\test.xml";
// write XML out to file
File.WriteAllText(targetFileName, xmlContents);
}
}

Sql Bulk Copy Cannot access destination table

I'm trying to read data from files and to use bulk copy to insert it in the database table.
When I try to run my code, I get the error: "Cannot Access Denstination Table"
Declaration of FlatTable.
System.Data.DataTable flatTableTempData = new System.Data.DataTable("FlatTable");
DataColumn DistrictColumn = new DataColumn();
DistrictColumn.ColumnName = "DistrictName";
// Create Column 3: TotalSales
DataColumn TownColumn = new DataColumn();
TownColumn.ColumnName = "TownName";
DataColumn FarmerColumn = new DataColumn();
FarmerColumn.ColumnName = "FarmerName";
flatTableTempData.Columns.Add(DistrictColumn);
flatTableTempData.Columns.Add(TownColumn);
flatTableTempData.Columns.Add(FarmerColumn);
This is my code, with the connection string and the insertion using bulk copy:
using (SqlConnection con = new SqlConnection("Data Source=DRTARIQ-PC\\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=TestDB2"))
{
con.Open();
using (SqlBulkCopy s = new SqlBulkCopy(con))
{
s.DestinationTableName = flatTableTempData.TableName;
foreach (var column in flatTableTempData.Columns)
s.ColumnMappings.Add(column.ToString(), column.ToString());
s.BulkCopyTimeout = 500;
s.WriteToServer(flatTableTempData);
}
}
I've encountered the same problem. The table exists, the SQL user has access but SqlBulkCopy cannot access the table. My problem turned out to be I turned off the indexing to try and insert faster (rebuild index after the bulkcopy), but this made the table inaccessible. After I turned the indexing on again it worked, SqlBulkCopy has access to the table.
The table name in WriteToServer method of SqlBulkCopy must be surrounded with [ ] signs.

vb.net get result of sql statement

Hello take a look at the code below:
Try
con.ConnectionString = strCon
Dim strCommand as String = "RESTORE FILELISTONLY
FROM DISK = 'C:\AdventureWorks.BAK'
WITH FILE = 1
GO"
Dim cm As New SqlClient.SqlCommand(strCommand, con)
con.Open()
cm.ExecuteNonQuery()
Does anyone know how to get the list of logical files for my database, it does not work with executereader. i want to get the mdf and ldf files name for my database backup file.
Thanks.
As I've said before - the GO is NOT a T-SQL keyword - drop that!
And secondly, you don't need a WITH FILE when restoring only the file headers - try this:
Dim strCommand as String = "RESTORE FILELISTONLY
FROM DISK = 'C:\AdventureWorks.BAK'"
This will return several pieces of data - so you need to deal with a result set and thus use .ExecuteReader() to get this data from the query.
Try this code (it's C#, but should be easy enough to convert to VB.NET):
using System;
using System.Data;
using System.Data.SqlClient;
namespace GetPhysicalDbNames
{
class Program
{
static void Main(string[] args)
{
string stmt = #"RESTORE FILELISTONLY FROM DISK = 'D:\temp\AW2012.BAK'";
using (SqlConnection conn = new SqlConnection("server=.;database=master;integrated Security=SSPI"))
using (SqlCommand cmd = new SqlCommand(stmt, conn))
{
DataTable tblInfo = new DataTable();
SqlDataAdapter dap = new SqlDataAdapter(cmd);
dap.Fill(tblInfo);
foreach (DataRow row in tblInfo.Rows)
{
Console.WriteLine("Logical name: {0}", row["LogicalName"]);
Console.WriteLine("Physical file name: {0}", row["PhysicalName"]);
}
}
}
}
}
Executing that RESTORE command returns a result set, which contains among other two columns LogicalName and PhysicalName (which is the actual, complete physical file name of the .mdf and .ldf files)