Imported Excel sheet not sorted normally - asp.net

Below code to import data from excel sheet to ASP.Net web page and saving it at SQL server in my database.
When I import data from required sheet not imported by it's default sorting in ASP web page or database, and it is affect badly on the final result and lose data too.
For more clarification if first row in excel sheet having first ID is '1' , Activities is "New Installation" and so on...in the ASP web page and SQL Database may appear in ninth row and without full data
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.OleDb;
namespace ImpExpExc
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateData();
lblMessage.Text = "Current Database Data!";
}
}
private void PopulateData()
{
using (TEDataEntities dc = new TEDataEntities())
{
gvData.DataSource = dc.ImportExportExcels.ToList();
gvData.DataBind();
}
}
protected void btnImport_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile.ContentType == "application/vnd.ms-excel" ||
FileUpload1.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
try
{
string fileName = Path.Combine(Server.MapPath("~/ImportDocument"), Guid.NewGuid().ToString() + Path.GetExtension(FileUpload1.PostedFile.FileName));
FileUpload1.PostedFile.SaveAs(fileName);
string conString = "";
string ext = Path.GetExtension(FileUpload1.PostedFile.FileName);
if (ext.ToLower() == ".xls")
{
conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (ext.ToLower() == ".xlsx")
{
conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
string query = "Select [ID], [Activities], [Governorate], [Exchange], [Client], [Technician], [CircuitNo], [Comment], [Date] from [Sheet1$]";
OleDbConnection con = new OleDbConnection(conString);
if (con.State == System.Data.ConnectionState.Closed)
{
con.Open();
}
OleDbCommand cmd = new OleDbCommand(query, con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
da.Dispose();
con.Close();
con.Dispose();
//Import to Database
using (TEDataEntities dc = new TEDataEntities())
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
string empID = dr["ID"].ToString();
var v = dc.ImportExportExcels.Where(a => a.ID.Equals(empID)).FirstOrDefault();
if (v != null)
{
//Update here
v.Activities = dr["Activities"].ToString();
v.Governorate = dr["Governorate"].ToString();
v.Exchange = dr["Exchange"].ToString();
v.Client = dr["Client"].ToString();
v.Technician = dr["Technician"].ToString();
v.CircuitNo = dr["CircuitNo"].ToString();
v.Comment = dr["Comment"].ToString();
v.Date = dr["Date"].ToString();
}
else
{
//Insert here
dc.ImportExportExcels.AddObject(new ImportExportExcel
{
ID = dr["ID"].ToString(),
Activities = dr["Activities"].ToString(),
Exchange = dr["Exchange"].ToString(),
Client = dr["Client"].ToString(),
Technician = dr["Technician"].ToString(),
CircuitNo = dr["CircuitNo"].ToString(),
Comment = dr["Comment"].ToString(),
Date = dr["Date"].ToString()
});
}
}
dc.SaveChanges();
}
PopulateData();
lblMessage.Text = "Successfully data import done!";
}
catch (Exception)
{
throw;
}
}
}
}
}

Finally issue of sorting solved by adding additional column with incremental ID in database but still some of cells which is related to date is empty

Related

How to compare a password against a hashed password with Scrypt.NET?

I was trying to use scrypt in asp.net for hashing the passwords from users, in the database, after sign up, but when I try to login, I don't know exactly how to compare the password for user with the hash from database.
Can anyone help me figure it out how to compare a password against a hashed password?
For SIGN-UP I used:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
using System.Security.Cryptography;
using Scrypt;
namespace WebApplication1
{
public partial class SignUp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btSignup_Click(object sender, EventArgs e)
{
if (tbUname.Text != "" & tbPass.Text != "" && tbName.Text != "" && tbEmail.Text != "" && tbCPass.Text != "")
{
if (tbPass.Text == tbCPass.Text)
{
String CS = ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
ScryptEncoder encoder = new ScryptEncoder();
string hashsedPassword = encoder.Encode(tbPass.Text);
SqlCommand cmd = new SqlCommand("insert into Users values('" + tbUname.Text + "','" + hashsedPassword + "','" + tbEmail.Text + "','" + tbName.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
lblMsg.Text = "Registration Succesfull";
lblMsg.ForeColor = Color.Green;
Response.Redirect("~/SignIn.aspx");
}
}
else { lblMsg.Text = "Passwords do not match"; }
}
else
{
lblMsg.ForeColor = Color.Red;
lblMsg.Text = "All Fields are Mandatory";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True";
con1.Open();
SqlCommand cm1 = new SqlCommand();
cm1.CommandText = "select * from [Users]where Username=#Uname";
cm1.Parameters.AddWithValue("#Uname", tbUname.Text);
cm1.Connection = con1;
SqlDataReader rd = cm1.ExecuteReader();
if (rd.HasRows)
{
Label1.Visible = true;
Label1.Text = "Username already exists !";
Label1.ForeColor = System.Drawing.Color.Red;
}
else
{
Label1.Visible = true;
Label1.Text = "Username is available !";
Label1.ForeColor = System.Drawing.Color.Green;
}
}
}
}
And LOGIN:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace WebApplication1
{
public partial class SignIn : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS)) {
SqlCommand cmd= new SqlCommand("select * from Users where Username='"+ Username.Text+"' and Password='"+Password.Text+"'" , con);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count != 0)
{
Session["USERNAME "] = Username.Text;
Response.Redirect("~/UserHome.aspx"); }
else {
lblError.Text = "Invalid Username or Password !";
}
}
}
}
}
Scrypt.NET handles the comparison of the typed in password and the existing hash for you. The documentation page shows:
ScryptEncoder encoder = new ScryptEncoder();
bool areEquals = encoder.Compare("mypassword", hashedPassword);
In your case that means that you cannot use the password in the SQL query to get a specific user. You would have to use only the given Username to find the correct row in the Users table.
SqlCommand cmd = new SqlCommand("select * from Users where Username=#Username" , con);
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 255, Username.Text);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count != 0) {
ScryptEncoder encoder = new ScryptEncoder();
foreach(DataRow row in dt.Rows)
{
if (encoder.Compare(Password.Text, (string)row["Password"]))
{
Session["USERNAME "] = Username.Text;
Response.Redirect("~/UserHome.aspx");
return;
}
}
} else {
lblError.Text = "Invalid Username or Password !";
}
Always use parametrized SQL queries. Otherwise, you're open to SQL injection attacks.

Grid View only updates when page refresh

In my application i have a grid view and a save task button. when i click save task my button , the Grid View doesn't refresh but when i click the refresh button of browser the grid refreshes and automatically add another task in the database. All i want is to refresh the grid when save task button is click and not add task when browser refresh button is clicked.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
static string startdate;
DataTable dt;
static string enddate;
static string EstDate;
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
protected void Page_Load(object sender, EventArgs e)
{//Page dosn't go back//
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetNoStore();
if (IsPostBack)
{
if (Session["auth"] != "ok" )
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
//Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
else
{
GridView1.DataSource = dt;
GridView1.DataBind();
if (Session["auth"] != "ok")
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
// Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
//decode url data in query string
labelID.Text = HttpUtility.UrlDecode(Request.QueryString["Id"]);
labelDur.Text = HttpUtility.UrlDecode(Request.QueryString["Duration"]);
labelStatus.Text = HttpUtility.UrlDecode(Request.QueryString["Status"]);
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
if (!IsPostBack)
{
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
}
protected void saveTask_Click(object sender, EventArgs e)
{
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
try
{
String query = "insert into Tasks (T_Description, T_Status,S_ID,StartDate,EstEndDate) values('" + TaskDesBox.Text + "', 'incomplete','" + labelID.Text + "' ,'" + startdate + "','" + EstDate + "');";
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
GridView1.DataBind();
}
else
{
TaskStatus.Text = "Task not Saved";
}
}
catch (Exception ex)
{
Response.Write("reeor" + ex);
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void TaskDesBox_TextChanged(object sender, EventArgs e)
{
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Calendar1.Visible = true;
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
startdate = Calendar1.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
SDate.Text = startdate;
Calendar1.Visible = false;
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
Calendar2.Visible = true;
}
protected void Calendar2_SelectionChanged(object sender, EventArgs e)
{
EstDate = Calendar2.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
EstDateBox.Text = EstDate;
Calendar2.Visible = false;
}
}
What you are doing on a post back is:
First show the results due to code in your Page_Load
Then perform event handlers, so if you pushed the Save button, the saveTask_Click will be performed, which adds a record to the database. You don't update your grid view datasource, but just call DataBind() afterwards which still binds the original DataSource.
Imo you shouldn't update your grid view on Page_Load. You should only show it initially on the GET (!IsPostBack).
And at the end of saveTask_Click you have to update your grid view again.
So move the code you need to show the grid view to a method you can call on other occasions:
protected void ShowGridView() {
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
Then call it in your Page_Load on !IsPostBack
if (!IsPostBack)
{
ShowGridView();
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
Then after adding the row in saveTask_Click you can call ShowGridView() to see the new result.
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
//GridView1.DataBind();
ShowGridView();
}
else
{
TaskStatus.Text = "Task not Saved";
}

SQL Connection variable not in the current context

I am a beginner in.NEt and having difficulty using the sql connection in a radio button index changed eventhandler that i defined on the page_load.
Below is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace Controls
{
public partial class Report_Selection : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.HeaderStyle.Font.Bold = true;
RadioButtonList1.SelectedIndexChanged += new EventHandler(RadioButtonList1_SelectedIndexChanged);
using (SqlConnection cnn = new SqlConnection("Data Source=DBSW9079;Initial Catalog=Underwriting;Integrated Security=SSPI;"))
{
SqlCommand cmd;
SqlDataReader sdr;
if (!IsPostBack)
{
cmd = new SqlCommand("select Categoryid,CategoryTitle from Report_Category", cnn);
cnn.Open();
sdr = cmd.ExecuteReader();
SelectCategorydlist1.DataSource = sdr;
SelectCategorydlist1.DataTextField = "CategoryTitle";
SelectCategorydlist1.DataValueField = "categoryid";
SelectCategorydlist1.DataBind();
cnn.Close();
}
else
{
//It's a Post back
//make the grid visible and fill it
GridView1.Visible = true;
RadioButtonList1.SelectedValue = "1";
cmd = new SqlCommand("Select rptdesc,rptdesctext,categoryid from report_description " + "where categoryid != 99999"
+ "and categoryid = " + Convert.ToInt32(SelectCategorydlist1.SelectedValue).ToString(), cnn);
cnn.Open();
sdr = cmd.ExecuteReader();
GridView1.DataSource = sdr;
GridView1.DataBind();
sdr.Close();
{
}
}
}
}
void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd1;
SqlDataReader sdr1;
if (RadioButtonList1.SelectedIndex.Equals(1))
{
RadioButtonList1.ClearSelection();
cmd1 = new SqlCommand("Select rptdesc,rptdesctext,categoryid from report_description "
+ "and categoryid = " + Convert.ToInt32(SelectCategorydlist1.SelectedValue).ToString(), cnn);
cnn.Open();
sdr1= cmd1.ExecuteReader();
GridView1.DataSource = sdr1;
GridView1.DataBind();
sdr1.Close();
}
}
}
}
In the above code when i use the cnn sequel connection in the event handler i get an small r
Your query in RadioButtonList1_SelectedIndexChanged appears to be incorrect. There's an and without a where:
Select rptdesc,rptdesctext,categoryid from report_description
and categoryid = ...
^^^ should be WHERE

Asp.net how to correct the error

I'm designing in my web page and image are stored in my database (The project is Photostudio management system)
MY Code:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace photoshops
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection cnn = new SqlConnection();
DataSet ds = new DataSet();
string constr = null;
SqlCommand cmd = new SqlCommand();
if (IsValid != true )
{
constr = #"Data Source=DEVI\SQLEXPRESS;Initial Catalog =cat; Integrated
Security=SSPI";
cnn.ConnectionString = constr;
try
{
if (cnn.State != ConnectionState.Open)
cnn.Open();
}
catch (Exception ex)
{
string str1 = null;
str1 = ex.ToString();
}
cmd.Connection = cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "photoset";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#BillNo", TextBox1.Text);
cmd.Parameters.AddWithValue("#CustomerName", TextBox2.Text);
cmd.Parameters.AddWithValue("#Address", TextBox3.Text);
cmd.Parameters.AddWithValue("#StartDate",Rdbsdate.SelectedDate );
cmd.Parameters.AddWithValue("#EndDate", Rdbddate.SelectedDate );
SqlParameter param0 = new SqlParameter("#Systemurl", SqlDbType.VarChar,
50);
cmd.Parameters.AddWithValue("#Numberofcopies", TextBox7.Text);
cmd.Parameters.AddWithValue("#Amount", TextBox8.Text);
cmd.Parameters.AddWithValue("#Total", TextBox9.Text);
da.SelectCommand = cmd;
try
{
da.Fill(ds);
}
catch (Exception ex)
{
string strErrMsg = ex.Message;
//throw new applicationException("!!!! An error an occured while
//inserting record."+ex.Message)
}
finally
{
da.Dispose();
cmd.Dispose();
cnn.Close();
cnn.Dispose();
}
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
Msg.Text = "Photo setting sucessfullY";
}
else
{
Msg.Text = "photosetting failled";
}
}
}
}
}
}
My ERROR
The record are not stored and image is not stored how to change in my code .
Well first of all, you're not saving the image, you're saving the path of your computer.
You need to save the byte array of the photo.
In short:
Upload its the upload control where you select the image
pic its the byte arrey where you upload the binary content of the photo
and then you only send it as a simple parameter cmd.Parameters.Add ("#pic", pic);
public void OnUpload(Object sender, EventArgs e)
{
// Create a byte[] from the input file
int len = Upload.PostedFile.ContentLength;
byte[] pic = new byte[len];
Upload.PostedFile.InputStream.Read (pic, 0, len);
// Insert the image and comment into the database
SqlConnection connection = new
SqlConnection (#"server=INDIA\INDIA;database=iSense;uid=sa;pwd=india");
try
{
connection.Open ();
SqlCommand cmd = new SqlCommand ("insert into Image "
+ "(Picture, Comment) values (#pic, #text)", connection);
cmd.Parameters.Add ("#pic", pic);
cmd.Parameters.Add ("#text", Comment.Text);
cmd.ExecuteNonQuery ();
}
finally
{
connection.Close ();
}
}
here are some tutorials, the first link it's very straightforward and the code its simple
http://www.codeproject.com/KB/web-image/PicManager.aspx
another, just in case:
http://www.redmondpie.com/inserting-in-and-retrieving-image-from-sql-server-database-using-c/
Principal resource: http://www.codeproject.com/KB/web-image/PicManager.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