How can i bind a table from oracle directly to pdf - asp.net

How can I bind data from oracle database to pdf in asp.net 4.0?

I don't know if this is possible directly. You might take a look at iTextSharp for generating PDF files in .NET.

Did you try using PL/PDF ? Haven't used it personally, but its the only direct method of creating/populating PDFs out of Oracle that I know of (unless perhaps Apex has some plug-in)

Thank you soo much for your responses. I got the answer. Below is the code for binding a database table from an Oracle database to PDF in ASP.net
using System.Web.UI.WebControls;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Data;
public partial class generate_pdf_from_dataset : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
OracleConnection con = new OracleConnection("User id=book;Password=book;Data Source=test");
OracleDataAdapter da = new OracleDataAdapter("select * from category" , con);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
Document pdfDoc = new Document(PageSize.A4, 30, 30, 40, 25);
System.IO.MemoryStream mStream = new System.IO.MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream);
int cols = dt.Columns.Count;
int rows = dt.Rows.Count;
pdfDoc.Open();
iTextSharp.text.Table pdfTable = new iTextSharp.text.Table(cols, rows);
pdfTable.BorderWidth = 1;
pdfTable.Width = 100;
pdfTable.Padding = 1;
pdfTable.Spacing = 1;
//creating table headers
for (int i = 0; i < cols; i++)
{
Cell cellCols = new Cell();
Font ColFont = FontFactory.GetFont(FontFactory.HELVETICA, 12, Font.BOLD);
Chunk chunkCols = new Chunk(dt.Columns[i].ColumnName, ColFont);
cellCols.Add(chunkCols);
pdfTable.AddCell(cellCols);
}
//creating table data (actual result)
for (int k = 0; k < rows; k++)
{
for (int j = 0; j < cols; j++)
{
Cell cellRows = new Cell();
Font RowFont = FontFactory.GetFont(FontFactory.HELVETICA, 12);
Chunk chunkRows = new Chunk(dt.Rows[k][j].ToString(), RowFont);
cellRows.Add(chunkRows);
pdfTable.AddCell(cellRows);
}
}
pdfDoc.Add(pdfTable);
pdfDoc.Close();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=Report.pdf");
Response.Clear();
Response.BinaryWrite(mStream.ToArray());
Response.End();
}
}

Related

Export to Excel function working in localhost but not in published website

I have this code to export my GridViews to Excel, it works in localhost but after deploying it does not work. The error I received upon clicking my export button is Runtime Error.
protected void EXPORT_BUTTON_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
String DATA1 = "DATA1";
String DATA2 = "DATA2";
ExportToExcel(app, workbook, DATA_1, DATA1);
workbook.Worksheets["Sheet1"].Delete();
workbook.Worksheets["Sheet2"].Delete();
workbook.Worksheets["Sheet3"].Delete();
ExportToExcel(app, workbook, DATA_2, DATA2);
string FolderPath = ServerName + DirectoryLocation + DirectoryFolder + ExportsFolder;
var filename = #"EXCEL_" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xlsx";
workbook.SaveAs(FolderPath + filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close();
app.Quit();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=" + filename + ";");
Response.TransmitFile(FolderPath + filename);
Response.Flush();
Response.End();
}
public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook, GridView gridview, string SheetName)
{
// see the excel sheet behind the program
app.Visible = false;
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets.Add();
// changing the name of active sheet
worksheet.Name = SheetName;
// storing header part in Excel
for (int i = 1; i < gridview.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
for (int j = 0; j < gridview.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Text.ToString();
}
}
}
I solved my question using EPPLUS, EPPlus is a .net library that reads and writes Excel 2007/2010 files using the Open Office Xml format (xlsx). It does not require excel to be installed on the server machines. thanks.
The codes below is an reference:
protected void ExportToExcel_Click(object sender, EventArgs e)
{
var products = GetProducts();
GridView1.DataSource = products;
GridView1.DataBind();
ExcelPackage excel = new ExcelPackage();
var workSheet = excel.Workbook.Worksheets.Add("Products");
var totalCols = GridView1.Rows[0].Cells.Count;
var totalRows = GridView1.Rows.Count;
var headerRow = GridView1.HeaderRow;
for (var i = 1; i <= totalCols; i++ )
{
workSheet.Cells[1, i].Value = headerRow.Cells[i - 1].Text;
}
for (var j = 1; j <= totalRows; j++ )
{
for (var i = 1; i <= totalCols; i++)
{
var product = products.ElementAt(j-1);
workSheet.Cells[j + 1, i].Value = product.GetType().GetProperty(headerRow.Cells[i - 1].Text).GetValue(product, null);
}
}
using (var memoryStream = new MemoryStream())
{
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=products.xlsx");
excel.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
'Microsoft.Office.Interop.Excel' means that Microsoft Office Runtime must be installed to make this code work.
Exporting data using Microsoft.Office.Interop.Excel is avoided, since it needs application installation on server, is poorly scalable, and is against MS Office licence conditions.
I suggest other ways, like text-csv exporting that will meet better performance on a server.
protected void EXPORT_BUTTON_Click(object sender, EventArgs e)
{
...
StringBuilder sb = new StringBuilder();
// storing header part in Excel
for (int i = 1; i < gridview.Columns.Count + 1; i++)
{
sb.Append (gridview.Columns[i - 1].HeaderText);
stringBuilder.Append(",");
}
sb.Append(Environment.NewLine);
// storing Each row and column value to excel sheet
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
for (int j = 0; j < gridview.Columns.Count; j++)
{
sb.Append (gridview.Rows[i].Cells[j].Text.ToString());
stringBuilder.Append(",");
}
sb.Append(Environment.NewLine);
}
WriteToCSV(sb.ToString();
}
public static void WriteToCSV(string text, string fileName)
{
string attachment = "attachment; filename="+fileName+DateTime.Now.ToString("yy-MM-dd")+".csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv;charset=utf8";
HttpContext.Current.Response.AddHeader("Pragma", "public");
HttpContext.Current.Response.Write('\uFEFF'); //this is BOM
HttpContext.Current.Response.Write(text);
HttpContext.Current.Response.End();
}
The reason it is failing is you don't have Excel installed. There are other options here (such as converting to CSV file), but if you want to use your code as is, the simplest way is to probably just install Excel on the server !

Dynamically adding Table rows

I am trying to add values in table rows on button click. It's working on database but not working on web page. It override on last row on page.
How can I generate new row on every button click.
here is my button click code--
protected void Page_Load(object sender, EventArgs e)
{
tblAdd.Visible = false;
Label1.Visible = false;
//Label2.Visible = false;
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
CheckBox cb1 = new CheckBox();
I = Hidden1.Value;
I += 1;
cb1.ID = "cb1" + I;
TableRow Table1Row = new TableRow();
Table1Row.ID = "Table1Row" + I;
TableCell RCell1 = new TableCell();
RCell1.Controls.Add(cb1);
TableCell RCell2 = new TableCell();
RCell2.Text = txtName.Text;
tblLanguagesRow.Cells.Add(RCell1);
tblLanguagesRow.Cells.Add(RCell2);
tblLanguages.Rows.Add(tblLanguagesRow);
Hidden1.Value = I;
btnAdd.Visible = true;
btnDelete.Visible = true;
Label2.Visible = true;
Label2.Text = "Successfully Added";
add();
}
txtName.Text = "";
}
public int add()
{
string strcon = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("hrm_AddLanguages", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Name", SqlDbType.VarChar).Value = txtName.Text;
command.Parameters.Add("#CreatedOn", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#UpdatedOn", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#CreatedBy", SqlDbType.BigInt).Value = 1;
command.Parameters.Add("#UpdatedBy", SqlDbType.BigInt).Value = 1;
command.Parameters.Add("#IsDeleted", SqlDbType.Bit).Value = 0;
sqlConnection.Open();
return command.ExecuteNonQuery();
}
Please Help me.
If possible try to do this using Grid view. It is better to use grid view instead of table.
Check out below link. It will help you to find your solution.
DataTable in ASP.Net Session

Dynamic Checkbox event handler asp.net

I found a few questions related to this, but none that I could figure out how to apply to my issue. Anyway, I have a ASP webform that pulls questions and answers from a database and puts them in a table. In the table, I have a column with a checkbox where the user can flag questions. My problem is that event handler for the CheckChanged event is not firing. I read some things about postback and whatnot, but my issue is that these controls are not created until the retrieve question button is pressed. Any help or pointers would be great.
Thanks,
Joseph
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ScienceAssessmentToolASP
{
public partial class createnewtest : System.Web.UI.Page
{
private int n;
private SqlConnection conn = null;
private List<int> flaggedQuestions = new List<int>();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
GetConn();
ExecuteRetrieval();
n = 1;
}
catch (Exception ex) { n = 0; Response.Write("for debugging: " + ex); }
finally { if (conn != null) conn.Close(); }
if (n < 0)
//Label1.Text = "Connection Successful";
Label3.Text = "Failed to Connect to Database, please contact the administrator.";
}
private void GetConn()
{
string connString = #"
removed ";
conn = new SqlConnection(connString);
conn.Open();
}
private void ExecuteRetrieval()
{
List<string> names = new List<string>(),
types = new List<string>();
SqlDataReader reader = null;
string query = "select * from [ScienceQA] where [GradeLevel] = " + DropDownList1.Text +
" and [Topic] = '" + DropDownList2.Text + "';";
SqlCommand cmd = new SqlCommand(query, conn);
reader = cmd.ExecuteReader();
TableHeaderRow headerRow = new TableHeaderRow();
TableHeaderCell idH = new TableHeaderCell();
TableHeaderCell questionH = new TableHeaderCell();
TableHeaderCell answerH = new TableHeaderCell();
TableHeaderCell flagH = new TableHeaderCell();
idH.Text = "ID";
questionH.Text = "Question";
answerH.Text = "Answer";
flagH.Text = "Flag";
headerRow.Cells.Add(idH);
headerRow.Cells.Add(questionH);
headerRow.Cells.Add(answerH);
headerRow.Cells.Add(flagH);
resultTable.Controls.Add(headerRow);
while (reader.Read())
{
TableRow row = new TableRow();
TableCell idCell = new TableCell();
TableCell qCell = new TableCell();
TableCell aCell = new TableCell();
TableCell flag = new TableCell();
idCell.Text = reader[0].ToString();
qCell.Text = reader[1].ToString();
aCell.Text = reader[2].ToString();
CheckBox flagBox = new CheckBox();
flagBox.ID = "flag" + idCell.Text.ToString();
//flagBox.Text = "Flag";
flagBox.CheckedChanged += new System.EventHandler(flagButton_Click);
flag.Controls.Add(flagBox);
row.Cells.Add(idCell);
row.Cells.Add(qCell);
row.Cells.Add(aCell);
row.Cells.Add(flag);
resultTable.Controls.Add(row);
}
Label4.Visible = true;
flagCounter.Visible = true;
resultTable.Visible = true;
}
protected void flagButton_Click(object sender, EventArgs e)
{
CheckBox lb = (CheckBox)sender;
int questionID = Convert.ToInt32(lb.Text.Substring(4));
if (lb.Checked)
{
lb.Checked = false;
flaggedQuestions.Add(questionID);
flagCounter.Text = Convert.ToString(Convert.ToInt32(flagCounter.Text) - 1);
}
else
{
lb.Checked = true;
flaggedQuestions.Remove(questionID);
flagCounter.Text = Convert.ToString(Convert.ToInt32(flagCounter.Text) + 1);
}
}
}
}
Try setting AutoPostBack to true when you create the control:
flagBox.AutoPostBack = true;
This makes it so the event will cause a postback. If you don't have this the code won't fire until you submit the form.
I figured it out. I guess I didnt need anything in button handler, since the clicking of the button causing a postback. So I put all the button1 handler stuff in my pageload with a if(postback) check and that worked.

how to upload image with reduced size

I am using asp.net fileupload control for uploading image but here i want to automatically re size to 250*200px.
please suggest me what to add in my code.
I am a novice to asp.net.
protected void Button1_Click(object sender, EventArgs e)
{ string s =#"~\img\"+FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath(s));
}
i also find this code useful for resizing
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing;
public partial class ImageUpload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string ImageName = txtName.Text;
if (FileUpLoad1.PostedFile != null && FileUpLoad1.PostedFile.FileName != null)
{
string strExtension = System.IO.Path.GetExtension(FileUpLoad1.FileName);
if ((strExtension.ToUpper() == ".JPG") | (strExtension.ToUpper() == ".GIF"))
{
// Resize Image Before Uploading to DataBase
FileUpload fi = new FileUpload();
fi = FileUpLoad1;
System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream( fi.PostedFile.InputStream);
int imageHeight = imageToBeResized.Height;
int imageWidth = imageToBeResized.Width;
int maxHeight = 120;
int maxWidth = 160;
imageHeight = (imageHeight * maxWidth) / imageWidth;
imageWidth = maxWidth;
if (imageHeight > maxHeight)
{
imageWidth = (imageWidth * maxHeight) / imageHeight;
imageHeight = maxHeight;
}
Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight);
System.IO.MemoryStream stream = new MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Position = 0;
byte[] image = new byte[stream.Length + 1];
stream.Read(image, 0, image.Length);
// Create SQL Connection
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["Return_AuthorizationsConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Images(ImageName,Image) VALUES (#ImageName,#Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlParameter ImageName1 = new SqlParameter("#ImageName", SqlDbType.VarChar, 50);
ImageName1.Value = ImageName.ToString();
cmd.Parameters.Add(ImageName1);
SqlParameter UploadedImage = new SqlParameter("#Image", SqlDbType.Image, image.Length);
UploadedImage.Value = image;
cmd.Parameters.Add(UploadedImage);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result > 0)
lblMessage.Text = "File Uploaded";
GridView1.DataBind();
}
}
}
}
After you get the image on the server you can resize it save it, and delete the original one.
a sample code only for resize
http://weblogs.asp.net/gunnarpeipman/archive/2009/04/02/resizing-images-without-loss-of-quality.aspx
and here is a full project with source code to manipulate images, including resize.
http://www.codeproject.com/KB/web-image/ASPImaging1.aspx

ASP .NET Dataset to XML: Storage and Reading

[Below is the almost full Code modified. Currently shows illegal character error when being read].
I have a C# ASP.NET application which is currently reading an XML file from the file system and then loading it into a GridView control. In the grid I can Delete rows. There is also an file upload button below the grid which upload PDF files and they show up in the grid. My code is basically a modified version of this code
The next stage of my work involves reading the XML data as String from a database field--instead of from the XML file. For that to happen, I think I can start out by just reading from the XML file, making changes in the aspx page, and the writing the 'dataset' into a database field called 'PDF_Storage'. How can I do that. Crucially, I need to be able to convert the dataset into some kind of string format for storage. Here is my code snippet.
My database is Oracle 10 but I can figure out the Update sql syntax.
SAMPLE XML FILE:
<DataSet>
<PDF>
<pdf>MyPDF1.pdf</pdf>
</PDF>
<PDF>
<pdf>MyPDF2.pdf</pdf>
</PDF>
<PDF>
<pdf>MyPDF3.pdf</pdf>
</PDF>
</DataSet>
And the corresponding code:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Oracle.DataAccess.Client;
using System.Web.Configuration;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;
public partial class XMLGridTest : System.Web.UI.Page
{
public static string GetConnString()
{
return WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
binddata();
}
}
void binddata()
{
DataSet ds = new DataSet();
// ds.ReadXml(Server.MapPath("testxml.xml"));
String strConnect = GetConnString();
OracleConnection oracleConn = new OracleConnection();
oracleConn.ConnectionString = strConnect;
oracleConn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = oracleConn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT PDF_Storage FROM CampusDev.CU_POLY WHERE OBJECTID = " + Request.QueryString["OBJECTID"];
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (!reader.IsDBNull(0))
{
//## Line Below as the 'illegal characters' problem###
ds.ReadXml(reader[0].ToString(), XmlReadMode.IgnoreSchema);
gv.DataSource = ds;
gv.DataBind();
}
else
{
// Response.Write(reader.GetString(1));
// TextBox1.Text = reader.GetString(1);
}
}
// gv.DataSource = ds;//##Hard coded for XML. Works!
// gv.DataBind();
//Finally, close the connection
oracleConn.Close();
}
protected void Canceldata(object s, GridViewCancelEditEventArgs e)
{
gv.EditIndex = -1;
binddata();
}
protected void pageddata(object s, GridViewPageEventArgs e)
{
gv.PageIndex = e.NewPageIndex;
binddata();
}
protected void insert(object sender, EventArgs e)
{
/////////////////////////////////File Upload Code/////////////////////////////////
// Initialize variables
string sSavePath = "ParcelPDF/"; ;
if (fileupload.PostedFile == null)
{
Label1.Text = "Must Upload a PDF file!";
return;
}
HttpPostedFile myFile = fileupload.PostedFile;
int nFileLen = myFile.ContentLength;
// Check file extension (must be JPG)
if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".pdf")
{
Label1.Text = "The file must have an extension of .pdf";
return;
}
// Read file into a data stream
byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData, 0, nFileLen);
// Make sure a duplicate file doesn’t exist. If it does, keep on appending an incremental numeric until it is unique
string sFilename = System.IO.Path.GetFileName(myFile.FileName);
int file_append = 0;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
{
file_append++;
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + ".pdf";
}
// Save the stream to disk
System.IO.FileStream newFile = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename), System.IO.FileMode.Create);
newFile.Write(myData, 0, myData.Length);
newFile.Close();
binddata();
DataSet ds = gv.DataSource as DataSet;
DataRow dr = ds.Tables[0].NewRow();
// dr[0] = pdf.Text;
dr[0] = sFilename.ToString();
ds.Tables[0].Rows.Add(dr);
ds.AcceptChanges();
string blah = "blah";
Response.Write(ds.Tables.ToString());
// ds.WriteXml(Server.MapPath("testxml.xml"));
String strConnect = GetConnString();
OracleConnection oracleConn = new OracleConnection();
oracleConn.ConnectionString = strConnect;
oracleConn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = oracleConn;
cmd.CommandType = CommandType.Text;
// cmd.CommandText = "SELECT OBJECTID,COMMENTS FROM CampusDev.CU_POLY WHERE OBJECTID = " + Request.QueryString["OBJECTID"];
cmd.CommandText = "UPDATE CampusDev.CU_POLY SET PDF_Storage = :PDF_Storage WHERE OBJECTID = " + Request.QueryString["OBJECTID"];
StringWriter SW = new StringWriter();
ds.WriteXml(SW);
cmd.Parameters.Add(":PDF_Storage", SW.ToString());
cmd.ExecuteNonQuery();
oracleConn.Close();
binddata();
}
protected void Deletedata(object s, GridViewDeleteEventArgs e)
{
binddata();
DataSet ds = gv.DataSource as DataSet;
ds.Tables[0].Rows[gv.Rows[e.RowIndex].DataItemIndex].Delete();
// ds.WriteXml(Server.MapPath("testxml.xml"));//Disabled now. Do database. Irfan. 07/09/10
String strConnect = GetConnString();
OracleConnection oracleConn = new OracleConnection();
oracleConn.ConnectionString = strConnect;
oracleConn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = oracleConn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE CampusDev.CU_POLY SET PDF_Storage = :PDF_Storage WHERE OBJECTID = " + Request.QueryString["OBJECTID"];
StringWriter SW = new StringWriter();
ds.WriteXml(SW,XmlWriteMode.IgnoreSchema);
Regex regex = new Regex(#"(\r\n|\r|\n)+");
string newText = regex.Replace(SW.ToString(), "");
cmd.Parameters.Add(":PDF_Storage", newText);
cmd.ExecuteNonQuery();
oracleConn.Close();
binddata();
string blah = "blah";
}
Here is how I have done this in the past. For the insert you can basically just write the dataset's xml representation out to a string and save it directly to a field in the database. In this case I leveraged Sql Server 2008 and an XML datatype for the database field. I think the datatype in Oracle is XMLTYPE.
Insert:
public static void InsertDataSet(string key, DataSet dataSet)
{
string xml = string.Empty;
using (MemoryStream ms = new MemoryStream())
{
dataSet.WriteXml(ms, XmlWriteMode.WriteSchema);
ms.Position = 0;
using (StreamReader sr = new StreamReader(ms))
{
xml = sr.ReadToEnd();
}
using (SqlServerConnection c = new SqlServerConnection(connectionString))
{
c.command.CommandType = CommandType.StoredProcedure;
c.command.CommandText = "some stored procedure to do the insert";
c.command.Parameters.Clear();
c.command.Parameters.Add(new SqlParameter("#key", key));
c.command.Parameters.Add(new SqlParameter("#xml", xml));
c.command.ExecuteNonQuery();
}
}
}
Getting the dataset back out of the database is as simple as reading the xml data from the database back into a TextReader and then building a new DataSet.
Get:
public static DataSet GetDataSet(string key)
{
using (SqlServerConnection c = new SqlServerConnection(connectionString))
{
c.command.CommandType = CommandType.StoredProcedure;
c.command.CommandText = "some stored procedure to get the xml";
c.command.Parameters.Clear();
c.command.Parameters.Add(new SqlParameter("#key", key));
dr = c.command.ExecuteReader();
if (dr == null)
{
return null;
}
if (dr.HasRows)
{
while (dr.Read())
{
if (dr["xml_field"] != DBNull.Value)
{
TextReader tr = new StringReader(dr["xml_field"].ToString());
result = new DataSet();
result.ReadXml(tr, XmlReadMode.ReadSchema);
}
}
}
}
return result;
}
Hope this helps.
Enjoy!

Resources