I'm designing in my web page:
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)
{
onflbload(sender, e);
}
public void onflbload(object sender, EventArgs e)
{
// Create a byte[] from the input file
int len = flbload.PostedFile.ContentLength;
byte[] pic = new byte[len];
flbload.PostedFile.InputStream.Read(pic, 0, len);
// Insert the image and comment into the database
SqlConnection connection = new SqlConnection(#"Data Source=DEVI\SQLEXPRESS;
Initial Catalog =cat; Integrated Security=SSPI");
try
{
connection.Open();
SqlCommand cmd = new SqlCommand("insert into tblphotosettings " +
"(BillNo,CustomerName,Address,StartDate,EndDate,Systemurl,Numberofcopies,Amount,Total)
values (#BillNo,#CustomerName,#Address,#StartDate,#EndDate,#Systemurl,#Numberofcopies,#Amount,#Total)", connection);
cmd.Parameters.Add("#BillNo", SqlDbType.NVarChar).Value = TextBox1.Text;
cmd.Parameters.Add("#CustomerName", SqlDbType.NVarChar).Value =TextBox2.Text;
cmd.Parameters.Add("#Address", SqlDbType.NVarChar).Value = TextBox3.Text;
cmd.Parameters.Add("#StartDate", SqlDbType.NVarChar).Value = Rdbsdate.SelectedDate;
cmd.Parameters.Add("#EndDate", SqlDbType.NVarChar).Value = Rdbddate.SelectedDate;
cmd.Parameters.Add("#Systemurl", SqlDbType.Image).Value = pic;
SqlParameter Src = new SqlParameter("#FilePath", SqlDbType.VarChar, 450);
Src.Value = pic.GetName();
cmd.Parameters.Add(Src);
cmd.Parameters.Add("#Numberofcopies", SqlDbType.NVarChar).Value =TextBox7.Text;
cmd.Parameters.Add("#Amount", SqlDbType.NVarChar).Value = TextBox8.Text;
cmd.Parameters.Add("#Total", SqlDbType.NVarChar).Value = TextBox9.Text;
cmd.ExecuteNonQuery();
}
finally
{
connection.Close();
}
}
}
}
My error
Error 1 'System.Array' does not contain a definition for 'GetName'
and no extension method 'GetName' accepting a first argument of type 'System.Array' could
be found (are you missing a using directive or an assembly reference?)
C:\Documents and Settings\Administrator\My Documents\Visual Studio
2008\Projects\photoshops\photoshops\photosetting.aspx.cs 52 29 photoshops
It sounds like you want the image location in the database.
Your code actually has the byte[] being used in the INSERT statement:
cmd.Parameters.Add("#Systemurl", SqlDbType.Image).Value = pic;
Suggest pick one:
Continue with saving the binary to the database as you have above.
Save the byte[] as a file to a location on disk. Use that filename like so:
cmd.Parameters.Add("#ImagePath", SqlDbType.NVarChar).Value = myImagePathOnDisk;
You just need to do code 2 line through that you can be able store image from filepath and can be able to store into database.
string flPath = "C:\\1\\noimg.png";
byte[] imageBytes = File.ReadAllBytes(flPath);
imageBytes is your part of interest holding whole arrays of bytes of your image, you just need to insert this to column of table of image datatype.
string filename = FileUpload1.FileName.ToString();
if (filename != "")
{
ImageName = FileUpload1.FileName.ToString();
ImagePath = Server.MapPath("Images");
SaveLocation = ImagePath + "\\" + ImageName;
SaveLocation1 = "~/Image/" + ImageName;
sl1 = "Images/" + ImageName;
FileUpload1.PostedFile.SaveAs(SaveLocation);
}...........try it for image
Related
How to show pictures which are located in a folder and the path is in the database But I'm unable to Do it.
testingDataSet RTP = new testingDataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/RTPrpt.rdlc");
FillRTP();
ReportDataSource dataSource = new ReportDataSource("DataSetRTP", RTP.Tables["RTPView"]);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(dataSource);
ReportViewer1.LocalReport.Refresh();
}
private void FillRTP()
{
string connectionString = Properties.Settings.Default.ETHADAIMS;
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
string queryString = string.Empty;
queryString = " select * from RTPView";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(queryString, sqlConnection);
sqlDataAdapter.Fill(RTP, RTP.Tables["RTPView"].TableName);
}
}
}
enter image description here
Photos are not visible. How can I make them to be visible?
i have database table in which i have two columns name picid and pic1..in my pic1 column i have three data..now while wanting to retrive the data using sqldatareader i am getting the top of the column data..how to get the all data of that column and use it for the further purpose..
my code
protected void Page_Load(object sender, EventArgs e)
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
SqlCommand cmd = new SqlCommand("SELECT * From pictable", objsqlconn);
SqlDataReader grpIDreader = cmd.ExecuteReader();
grpIDreader.Read();
string path = grpIDreader["pic1"].ToString();
//slide.Attributes["style"] = String.Format("background-image:url('{0}')", path);
image1.Attributes["src"] = String.Format("{0}", path);
image2.Attributes["src"] = String.Format("{1}", path);
image3.Attributes["src"] = String.Format("{2}", path);
}
i want to just get the path which are saved in the pic1 column of the database..
i am getting this error " System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list."
i have tried like that also and getting same error
protected void Page_Load(object sender, EventArgs e)
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
SqlCommand cmd = new SqlCommand("SELECT * From pictable", objsqlconn);
SqlDataReader grpIDreader = cmd.ExecuteReader();
string[] path={"","",""};
int i = 0;
while(grpIDreader.Read())
{
path[i++] = grpIDreader["pic1"].ToString();
}
//slide.Attributes["style"] = String.Format("background-image:url('{0}')", path);
image1.Attributes["src"] = String.Format("{0}", path[0]);
image2.Attributes["src"] = String.Format("{1}", path[1]);
image3.Attributes["src"] = String.Format("{2}", path[2]);
}
You are getting a string formatting error, not a database error:
image1.Attributes["src"] = String.Format("{0}", path); //This works, as 0 indicates the first argument you are passing in
image2.Attributes["src"] = String.Format("{1}", path); //This won't work, as you are asking for the second argument, which doesn't exist
Use the following to get each row
using (SqlDataReader grpIDreader = cmd.ExecuteReader())
{
while (grpIDreader.Read()) //.Read() advances to the next row and returns false if there are no more
{
string path = grpIDreader["pic1"].ToString();
//other stuff here
}
}
also
instead of this
image1.Attributes["src"] = String.Format("{0}", path[0]);
do this
image1.Attributes["src"] = path[0];
i have a database column 'images' which can hold binary data, for some reason the images doesnt want to upload. it doest pull any exceptions or aything wrong with the code:
here is extracts of the code
protected void BtnAdd_Click(object sender, EventArgs e)
{
string imgpath = FileUploadImage.FileName.ToString();
DBConnectivity.Add(imgpath);
}
here is the DBCoectivity Class:
public static void Add(string imgpath)
{
byte[] imgbt = null;
FileStream fstream = new FileStream(imgpath, FileMode.Open, FileAccess.Read);
BinaryReader BR = new BinaryReader(fstream);
imgbt = BR.ReadBytes((int)fstream.Length);
SqlConnection myConnection = GetConnection();
string myQuery = "INSERT INTO images( imagePath) VALUES ( #IMG )";
SqlCommand myCommand = new SqlCommand(myQuery, myConnection);
try
{
myConnection.Open();
myCommand.Parameters.Add(new SqlParameter("#IMG",imgbt));
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Exception in DBHandler", ex);
}
finally
{
myConnection.Close();
}
}
This snippet works for me:
byte[] imgbt = null;
if (FileUploadImage.HasFile)
{
Stream photoStream = FileUploadImage.PostedFile.InputStream;
imgbt = new byte[FileUploadImage.PostedFile.ContentLength];
photoStream.Read(imgbt, 0, FileUploadImage.PostedFile.ContentLength);
}
Also, you were inserting the image name (misspelled as parameter to Add method and bad choice of variable name as it is not a path) into the database, not the binary data. It should read:
string myQuery = "INSERT INTO images(imgbt) VALUES (#IMG)";
Here's a sample tutorial which explains it better:
File Upload with ASP.NET
I am new in asp.net and working on the data grid view in asp.net.i have written the following code for inserting and updating the columns in grid view.the grid is showing the data very well,but when i am trying to edit any row in the grid then it is throwing an Exception:
System.NullReferenceException: Object reference not set to an instance of an object: in the following line:
string UpdateQuery = string.Format("UPDATE tbl_PaperRateList set rate=" + rate1.Text + " where companyId=" + company_id.Text + " and paperId=" +paper_id.Text+ "");
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["con"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
protected void gridRateList_RowEditing(object sender, GridViewEditEventArgs e)
{
gridRateList.EditIndex = e.NewEditIndex;
BindGridData();
}
protected void gridRateList_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gridRateList.EditIndex = -1;
BindGridData();
}
#endregion
#region Binding the RateList Grid
public void BindGridData()
{
{
conn.Open();
SqlCommand cmdCompanyId = new SqlCommand("Select max(companyId) from tbl_PaperRateList", conn);
int c_id = Convert.ToInt32(cmdCompanyId.ExecuteScalar());
using (SqlCommand comm = new SqlCommand("select p.paperId,"
+ "p.Rate,pm.PaperName from tbl_PaperRatelist p,tbl_papermaster pm where p.paperId=pm.paperId and p.companyId=" + c_id + "", conn))
{
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
gridRateList.DataSource = ds;
gridRateList.DataBind();
}
}
}
#endregion
#region /*Updating the Row in Grid View*/
protected void gridRateList_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string s = gridRateList.DataKeys[e.RowIndex].Value.ToString();
Label company_id = (Label)gridRateList.Rows[e.RowIndex].FindControl("CompanyId");
Label paper_id = (Label)gridRateList.Rows[e.RowIndex].FindControl("paperId");
TextBox rate1 = (TextBox)gridRateList.Rows[e.RowIndex].FindControl("txtRate");
string UpdateQuery = string.Format("UPDATE tbl_PaperRateList set rate=" + rate1.Text + " where companyId=" + company_id.Text + " and paperId=" +paper_id.Text+ "");
gridRateList.EditIndex = -1;
BindGridData(UpdateQuery);
}
#endregion
#region Bind the Gridview after updating the row
private void BindGridData(string Query)
{
string connectionstring = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionstring))
{
conn.Open();
SqlCommand cmdCompanyId = new SqlCommand("Select max(companyId) from tbl_PaperRateList", conn);
int cid = Convert.ToInt32(cmdCompanyId.ExecuteScalar());
using (SqlCommand comm = new SqlCommand(Query +
";select p.paperId,"
+ "p.Rate,pm.PaperName from tbl_PaperRatelist p,tbl_papermaster pm where p.paperId=pm.paperId and p.companyId=" + cid + "", conn))
{
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
gridRateList.DataSource = ds;
gridRateList.DataBind();
}
}
}
#endregion
}
Did u declared globally or assigned null value to the variable..?
like this string UpdateQuery="";
Check the rate1.Text,company_id.Text ,paper_id.Text properties getting values or not.
Debug the Function BindGridData(string Query) the error happening there i think. check the parameters of that function. some parameters getting null value that's what the Exception is coming. check it out.
Hope this may helpful....
Did u declared globally or assigned null value to the variable..?
like this string UpdateQuery="";
Check the rate1.Text,company_id.Text ,paper_id.Text properties getting values or not.
Debug the Function BindGridData(string Query) the error happening there i think. check the parameters of that function. some parameters getting null value that's what the Exception is coming. check it out.
[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!