Solved

getting error after adding column to database and forms

Posted on 2011-09-19
9
284 Views
Last Modified: 2012-05-12
I had this code working correctly. Added a column to the table, tried to add the text filed to proved information for new column and now I get an error where before I did not:
ERROR:
Line 73:
Line 74:                               // Write data into a file
Line 75:                     WriteToFile(Server.MapPath(@"FSU\" + strFilename), ref myData);
Line 76:                    
Line 77:    

BELOW are the changes I made along with the actual file.
Code added to lines:
I added lines 20 and 160
I added the column name to lines 60 and 80
ASP code
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data;
using System.Data.OleDb;

namespace FileUpload
{
	
	public class WebForm1 : System.Web.UI.Page
	{
		private const string MDBFILE = "FileUpload.mdb";

		protected Label lblFile;
		protected HtmlInputFile filMyFile;
		protected System.Web.UI.WebControls.Label lblInfo;
        protected System.Web.UI.WebControls.Label lblnotes1;
		protected System.Web.UI.WebControls.Button cmdSend;
		protected System.Web.UI.WebControls.Image imgFile;
		protected System.Web.UI.WebControls.Image imgDB;
		protected System.Web.UI.WebControls.Label lblText1;
		protected System.Web.UI.WebControls.Label lblText2;
	
		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}

		private void InitializeComponent()
		{    
			this.Load += new System.EventHandler(this.Page_Load);
			this.cmdSend.Click += new System.EventHandler(this.cmdSend_Click);
		}

		private void Page_Load(object sender, System.EventArgs e)
		{
			// Check if FileID was passed to this page as a parameter
			if( Request.QueryString["FileID"] != null )
			{
				// Get the file out of database and return it to requesting client
				ShowTheFile(Convert.ToInt32(Request.QueryString["FileID"]));
			}
			
		}

		// Processes click on our cmdSend button
		private void cmdSend_Click(object sender, System.EventArgs e)
		{
			// Check to see if file was uploaded
			if( filMyFile.PostedFile != null )
			{
				// Get a reference to PostedFile object
				HttpPostedFile myFile = filMyFile.PostedFile;

				// Get size of uploaded file
				int nFileLen = myFile.ContentLength; 

				// make sure the size of the file is > 0
				if( nFileLen > 0 )
				{
					// Allocate a buffer for reading of the file
					byte[] myData = new byte[nFileLen];

					// Read uploaded file from the Stream
					myFile.InputStream.Read(myData, 0, nFileLen,lblnotes1);

					// Create a name for the file to store
					string strFilename = Path.GetFileName(myFile.FileName);lblFile

					// Write data into a file
                    WriteToFile(Server.MapPath(@"FSU\" + strFilename), ref myData);
                    
                    

					// Store it in database
					int nFileID = WriteToDB(strFilename, myFile.ContentType, ref myData, lblnotes1 );

					// Set label's text
					lblInfo.Text = 
						"Filename: " + strFilename + "<br>" + 
						"Size: " + nFileLen.ToString() + "<br>";
						

					// Set URL of the the object to point to the file we've just saved
					imgFile.ImageUrl = strFilename;
					imgFile.ToolTip = "This file will be stored to the FSU folder as file.";
					lblText1.Text = imgFile.ImageUrl;

					// Set URL of the the object to point to the this script with ID of the file
					// that will retrieve file out the database
					imgDB.ImageUrl = GetMyName() + "?FileID=" + nFileID.ToString();
					imgDB.ToolTip = "This file Will be stored in the uploadData database.";
					lblText2.Text = imgDB.ImageUrl;
					
					
                    // show the images and text
					imgFile.Visible = false;
					imgDB.Visible = false;
					lblText1.Visible = true;
					lblText2.Visible = true;
                    
				}
			}
		}

		// Writes file to current folder
		private void WriteToFile(string strPath, ref byte[] Buffer)
		{
			// Create a file
			FileStream newFile = new FileStream(strPath, FileMode.Create);

			// Write data to the file
			newFile.Write(Buffer, 0, Buffer.Length);

			// Close file
			newFile.Close();
		}

		// Generates database connection string
		private string GetConnectionString()
		{
			return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(MDBFILE) + ";";
		}

        // Writes file to the database
        private int WriteToDB(string strName, string strType, ref byte[] Buffer, string notes)
        {
            int nFileID = 0;

            // Create connection
            OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

            // Create Adapter
            OleDbDataAdapter dbAdapt = new OleDbDataAdapter("SELECT * FROM tblFile", dbConn);

            // We need this to get an ID back from the database
            dbAdapt.MissingSchemaAction = MissingSchemaAction.AddWithKey;

            // Create and initialize CommandBuilder
            OleDbCommandBuilder dbCB = new OleDbCommandBuilder(dbAdapt);

            // Open Connection
            dbConn.Open();

            // New DataSet
            DataSet dbSet = new DataSet();

            // Populate DataSet with data
            dbAdapt.Fill(dbSet, "tblFile");

            // Get reference to our table
            DataTable dbTable = dbSet.Tables["tblFile"];

            // Create new row
            DataRow dbRow = dbTable.NewRow();

            // Store data in the row
            dbRow["FileName"] = strName;
            dbRow["FileSize"] = Buffer.Length;
            dbRow["ContentType"] = strType;
            dbRow["FileData"] = Buffer;
            dbRow["uploadDate"] = DateTime.Now;
            dbRow["Notes"] = strType;

            // Add row back to table
            dbTable.Rows.Add(dbRow);

            // Update data source
            dbAdapt.Update(dbSet, "tblFile");

            // Get newFileID
            if (!dbRow.IsNull("FileID"))
                nFileID = (int)dbRow["FileID"];

            // Close connection
            dbConn.Close();

            // Return FileID
            return nFileID;
        }

		// Read file out of the database and returns it to client
		private void ShowTheFile(int FileID)
		{
			// Define SQL select statement
			string SQL = "SELECT FileSize, FileData, ContentType, Notes FROM tblFile WHERE FileID = " 
						+ FileID.ToString();

			// Create Connection object
			OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

			// Create Command Object
			OleDbCommand dbComm = new OleDbCommand(SQL, dbConn);

			// Open Connection
			dbConn.Open();

			// Execute command and receive DataReader
			OleDbDataReader dbRead = dbComm.ExecuteReader();

			// Read row
			dbRead.Read();

			// Clear Response buffer
			Response.Clear();

			// Set ContentType to the ContentType of our file
			Response.ContentType = (string)dbRead["ContentType"];

			// Write data out of database into Output Stream
			Response.OutputStream.Write((byte[])dbRead["FileData"], 0, (int)dbRead["FileSize"]);

			// Close database connection
			dbConn.Close();

			// End the page
			Response.End();
		}

		// Reads the name of current web page
		private string GetMyName()
		{
			// Get the script name
			string strScript = Request.ServerVariables["SCRIPT_NAME"];

			// Get position of last slash
			int nPos = strScript.LastIndexOf("/");

			// Get everything after slash
			if( nPos > -1 )
				strScript = strScript.Substring(nPos + 1);

			return strScript;
		}
	}
}

Open in new window


Added lines:
11 and 12 to html file
<input id="lblnotes1" type="text" runat="server">
<asp:button id="cmdSend" runat="server" Text="Send"/>

<%@ Page language="c#" AutoEventWireUp="false" Codebehind="default.aspx.cs" Inherits="FileUpload.WebForm1" Src="default.aspx.cs" %>

<HTML>
	<HEAD>
	</HEAD>
	<body MS_POSITIONING="GridLayout">
		<form id="Form1" method="post" runat="server" enctype="multipart/form-data">
				<asp:label id="" runat="server" Font-Bold="True">Please Select the Data File you will be uploading:</asp:label>
				<input id="filMyFile" type="file" runat="server">
				<p></p>
                <asp:label id="" runat="server" Font-Bold="True">Please describe data file you are uploading:</asp:label>
				<input id="lblnotes1" type="text" runat="server">
				<asp:button id="cmdSend" runat="server" Text="Send"/>
				<p></p>
				<asp:Label id="lblInfo" runat="server" Font-Bold="True" Visible="false"></asp:Label>
				<p></p>
				<table>
						<tr>
							<td>
								<asp:Label id="lblText1" runat="server" Font-Bold="True" Visible="True">This file will be placed in the FSU folder on the CEDB server.</asp:Label>
							</td>
						<tr>
							<td>
								<asp:Label id="lblText2" runat="server" Font-Bold="True" Visible="True">This file and all of its meta data will be stored in uploadedData database</asp:Label>
							</td>
							</tr>
						</tr>
						<tr>
							<td>
								<asp:Image id="imgFile" runat="server" Visible="False"></asp:Image>
							</TD>
							<td>
								<asp:Image id="imgDB" runat="server" Visible="False"></asp:Image>
							</td>
						</TR>
				</TABLE>
		</FORM>
	</body>
</HTML>

Open in new window



0
Comment
Question by:Tagom
  • 5
  • 4
9 Comments
 
LVL 22

Expert Comment

by:pivar
ID: 36560327
Hi,

Try removing lblfile from this line:

                              string strFilename = Path.GetFileName(myFile.FileName);lblFile

that is

                              string strFilename = Path.GetFileName(myFile.FileName);

/peter
0
 
LVL 22

Expert Comment

by:pivar
ID: 36560336
You'll find it on line 72
0
 

Author Comment

by:Tagom
ID: 36560387
new error created:
Line 67:
Line 68:                               // Read uploaded file from the Stream
Line 69:                               myFile.InputStream.Read(myData, 0, nFileLen,lblnotes1);
Line 70:
Line 71:                               // Create a name for the file to store
0
 

Author Comment

by:Tagom
ID: 36560430
ERROR
Compiler Error Message: CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
original error

New error:
Compiler Error Message: CS1501: No overload for method 'Read' takes '4' arguments

So, kind of lost here. Not sure how to get this new column activated!
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 22

Expert Comment

by:pivar
ID: 36560512
What is it you want to do? The function Read takes 3 parameters, not 4.
 If you want to save the lblnotes1 in db, I think you should change

69: myFile.InputStream.Read(myData, 0, nFileLen,lblnotes1);

to

myFile.InputStream.Read(myData, 0, nFileLen);

and

167: dbRow["Notes"] = strType;

to

dbRow["Notes"] = notes;


0
 

Author Comment

by:Tagom
ID: 36560654
That is exactly what I need to do:
I need the text string that is inserted in the textbox lblnotes1 to be stored in the Notes column in the database.
I changed the code you suggested and this is the error I received:
Compiler Error Message: CS1502: The best overloaded method match for 'FileUpload.WebForm1.WriteToDB(string, string, ref byte[], string)' has some invalid arguments

Source Error:

Line 78:
Line 79:                               // Store it in database
Line 80:                               int nFileID = WriteToDB(strFilename, myFile.ContentType, ref myData, lblnotes1 );
Line 81:
Line 82:                               // Set label's text
 somewhere I am not linking it correctly:
Here is both sets of code again and The database I am using
backend code code
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data;
using System.Data.OleDb;

namespace FileUpload
{

    public class WebForm1 : System.Web.UI.Page
    {
        private const string MDBFILE = "FileUpload.mdb";

        protected Label lblFile;
        protected HtmlInputFile filMyFile;
        protected System.Web.UI.WebControls.Label lblInfo;
        protected System.Web.UI.WebControls.Label lblnotes1;
        protected System.Web.UI.WebControls.Button cmdSend;
        protected System.Web.UI.WebControls.Image imgFile;
        protected System.Web.UI.WebControls.Image imgDB;
        protected System.Web.UI.WebControls.Label lblText1;
        protected System.Web.UI.WebControls.Label lblText2;

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
            this.cmdSend.Click += new System.EventHandler(this.cmdSend_Click);
        }

        private void Page_Load(object sender, System.EventArgs e)
        {
            // Check if FileID was passed to this page as a parameter
            if (Request.QueryString["FileID"] != null)
            {
                // Get the file out of database and return it to requesting client
                ShowTheFile(Convert.ToInt32(Request.QueryString["FileID"]));
            }

        }

        // Processes click on our cmdSend button
        private void cmdSend_Click(object sender, System.EventArgs e)
		{
			// Check to see if file was uploaded
			if( filMyFile.PostedFile != null )
			{
				// Get a reference to PostedFile object
				HttpPostedFile myFile = filMyFile.PostedFile;

				// Get size of uploaded file
				int nFileLen = myFile.ContentLength; 

				// make sure the size of the file is > 0
				if( nFileLen > 0 )
				{
					// Allocate a buffer for reading of the file
					byte[] myData = new byte[nFileLen];

					// Read uploaded file from the Stream
                    myFile.InputStream.Read(myData, 0, nFileLen);

					// Create a name for the file to store
					string strFilename = Path.GetFileName(myFile.FileName);

					// Write data into a file
                    WriteToFile(Server.MapPath(@"FSU\" + strFilename), ref myData);
                    
                    

					// Store it in database
                    int nFileID = WriteToDB(strFilename, myFile.ContentType, ref myData, strName);

					// Set label's text
					lblInfo.Text = 
						"Filename: " + strFilename + "<br>" + 
						"Size: " + nFileLen.ToString() + "<br>";
						

					// Set URL of the the object to point to the file we've just saved
					imgFile.ImageUrl = strFilename;
					imgFile.ToolTip = "This file will be stored to the FSU folder as file.";
					lblText1.Text = imgFile.ImageUrl;

					// Set URL of the the object to point to the this script with ID of the file
					// that will retrieve file out the database
					imgDB.ImageUrl = GetMyName() + "?FileID=" + nFileID.ToString();
					imgDB.ToolTip = "This file Will be stored in the uploadData database.";
					lblText2.Text = imgDB.ImageUrl;
					
					
                    // show the images and text
					imgFile.Visible = false;
					imgDB.Visible = false;
					lblText1.Visible = true;
					lblText2.Visible = true;
                    
				}
			}
		}

        // Writes file to current folder
        private void WriteToFile(string strPath, ref byte[] Buffer)
        {
            // Create a file
            FileStream newFile = new FileStream(strPath, FileMode.Create);

            // Write data to the file
            newFile.Write(Buffer, 0, Buffer.Length);

            // Close file
            newFile.Close();
        }

        // Generates database connection string
        private string GetConnectionString()
        {
            return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(MDBFILE) + ";";
        }

        // Writes file to the database
        private int WriteToDB(string strName, string strType, ref byte[] Buffer, string strName)
        {
            int nFileID = 0;

            // Create connection
            OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

            // Create Adapter
            OleDbDataAdapter dbAdapt = new OleDbDataAdapter("SELECT * FROM tblFile", dbConn);

            // We need this to get an ID back from the database
            dbAdapt.MissingSchemaAction = MissingSchemaAction.AddWithKey;

            // Create and initialize CommandBuilder
            OleDbCommandBuilder dbCB = new OleDbCommandBuilder(dbAdapt);

            // Open Connection
            dbConn.Open();

            // New DataSet
            DataSet dbSet = new DataSet();

            // Populate DataSet with data
            dbAdapt.Fill(dbSet, "tblFile");

            // Get reference to our table
            DataTable dbTable = dbSet.Tables["tblFile"];

            // Create new row
            DataRow dbRow = dbTable.NewRow();

            // Store data in the row
            dbRow["FileName"] = strName;
            dbRow["FileSize"] = Buffer.Length;
            dbRow["ContentType"] = strType;
            dbRow["FileData"] = Buffer;
            dbRow["uploadDate"] = DateTime.Now;
            dbRow["Notes"] = strName;

            // Add row back to table
            dbTable.Rows.Add(dbRow);

            // Update data source
            dbAdapt.Update(dbSet, "tblFile");

            // Get newFileID
            if (!dbRow.IsNull("FileID"))
                nFileID = (int)dbRow["FileID"];

            // Close connection
            dbConn.Close();

            // Return FileID
            return nFileID;
        }

        // Read file out of the database and returns it to client
        private void ShowTheFile(int FileID)
        {
            // Define SQL select statement
            string SQL = "SELECT FileSize, FileData, ContentType, Notes FROM tblFile WHERE FileID = "
                        + FileID.ToString();

            // Create Connection object
            OleDbConnection dbConn = new OleDbConnection(GetConnectionString());

            // Create Command Object
            OleDbCommand dbComm = new OleDbCommand(SQL, dbConn);

            // Open Connection
            dbConn.Open();

            // Execute command and receive DataReader
            OleDbDataReader dbRead = dbComm.ExecuteReader();

            // Read row
            dbRead.Read();

            // Clear Response buffer
            Response.Clear();

            // Set ContentType to the ContentType of our file
            Response.ContentType = (string)dbRead["ContentType"];

            // Write data out of database into Output Stream
            Response.OutputStream.Write((byte[])dbRead["FileData"], 0, (int)dbRead["FileSize"]);

            // Close database connection
            dbConn.Close();

            // End the page
            Response.End();
        }

        // Reads the name of current web page
        private string GetMyName()
        {
            // Get the script name
            string strScript = Request.ServerVariables["SCRIPT_NAME"];

            // Get position of last slash
            int nPos = strScript.LastIndexOf("/");

            // Get everything after slash
            if (nPos > -1)
                strScript = strScript.Substring(nPos + 1);

            return strScript;
        }
    }
}

Open in new window

FRONT END CODE
<%@ Page language="c#" AutoEventWireUp="false" Codebehind="default.aspx.cs" Inherits="FileUpload.WebForm1" Src="default.aspx.cs" %>

<HTML>
	<HEAD>
	</HEAD>
	<body MS_POSITIONING="GridLayout">
		<form id="Form1" method="post" runat="server" enctype="multipart/form-data">
				<asp:label id="" runat="server" Font-Bold="True">Please Select the Data File you will be uploading:</asp:label>
				<input id="filMyFile" type="file" runat="server">
				<p></p>
                <asp:label id="" runat="server" Font-Bold="True">Please describe data file you are uploading:</asp:label>
				<input id="lblnotes1" type="text" runat="server">
				<asp:button id="cmdSend" runat="server" Text="Send"/>
				<p></p>
				<asp:Label id="lblInfo" runat="server" Font-Bold="True" Visible="false"></asp:Label>
				<p></p>
				<table>
						<tr>
							<td>
								<asp:Label id="lblText1" runat="server" Font-Bold="True" Visible="True">This file will be placed in the FSU folder on the CEDB server.</asp:Label>
							</td>
						<tr>
							<td>
								<asp:Label id="lblText2" runat="server" Font-Bold="True" Visible="True">This file and all of its meta data will be stored in uploadedData database</asp:Label>
							</td>
							</tr>
						</tr>
						<tr>
							<td>
								<asp:Image id="imgFile" runat="server" Visible="False"></asp:Image>
							</TD>
							<td>
								<asp:Image id="imgDB" runat="server" Visible="False"></asp:Image>
							</td>
						</TR>
				</TABLE>
		</FORM>
	</body>
</HTML>

Open in new window



FileUpload.mdb
0
 
LVL 22

Accepted Solution

by:
pivar earned 500 total points
ID: 36560740
Try changing

      130: private int WriteToDB(string strName, string strType, ref byte[] Buffer, string strName)
to
      private int WriteToDB(string strName, string strType, ref byte[] Buffer, string strNotes)

and

      167: dbRow["Notes"] = strName;

to
      dbRow["Notes"] = strNotes;

and

      80: int nFileID = WriteToDB(strFilename, myFile.ContentType, ref myData, lblnotes1 );

to

      int nFileID = WriteToDB(strFilename, myFile.ContentType, ref myData, lblnotes1.Text);
0
 

Author Comment

by:Tagom
ID: 36561748
Well it appears I am getting close - I appreciate your help!
IN changing the file with your suggestions I now get an error on the frontend.
Not sure how to handle this: It looks like i need to name the labels but when I try it gives me even more errors...Stuck.
Error

Parser Error Message: '' is not a valid identifier.

Source Error:

Line 6:        <body MS_POSITIONING="GridLayout">
Line 7:              <form id="Form1" method="post" runat="server" enctype="multipart/form-data">
Line 8:                          <asp:label id="" runat="server" Font-Bold="True">Please Select the Data File you will be uploading:</asp:label>
Line 9:                          <input id="filMyFile" type="file" runat="server">
Line 10:                         <p></p>
<%@ Page language="c#" AutoEventWireUp="false" Codebehind="default.aspx.cs" Inherits="FileUpload.WebForm1" Src="default.aspx.cs" %>

<HTML>
	<HEAD>
	</HEAD>
	<body MS_POSITIONING="GridLayout">
		<form id="Form1" method="post" runat="server" enctype="multipart/form-data">
				<asp:label id="" runat="server" Font-Bold="True">Please Select the Data File you will be uploading:</asp:label>
				<input id="filMyFile" type="file" runat="server">
				<p></p>
                <asp:label id="lblnotes1" runat="server" Font-Bold="True">Please Select the Data File you will be uploading:</asp:label>
				<input id="lblnotes1" type="Text" runat="server">
				<asp:button id="cmdSend" runat="server" Text="Send"/>
				<p></p>
				<asp:Label id="lblInfo" runat="server" Font-Bold="True" Visible="false"></asp:Label>
				<p></p>
				<table>
						<tr>
							<td>
								<asp:Label id="lblText1" runat="server" Font-Bold="True" Visible="True">This file will be placed in the FSU folder on the CEDB server.</asp:Label>
							</td>
						<tr>
							<td>
								<asp:Label id="lblText2" runat="server" Font-Bold="True" Visible="True">This file and all of its meta data will be stored in uploadedData database</asp:Label>
							</td>
							</tr>
						</tr>
						<tr>
							<td>
								<asp:Image id="imgFile" runat="server" Visible="False"></asp:Image>
							</TD>
							<td>
								<asp:Image id="imgDB" runat="server" Visible="False"></asp:Image>
							</td>
						</TR>
				</TABLE>
		</FORM>
	</body>
</HTML>

Open in new window

0
 

Author Closing Comment

by:Tagom
ID: 36562562
Thank you
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to measure sizes and angles in scanned images ? 3 55
Syntax error 9 45
Syntax Error 2 48
rebind a grid after user clicks on node in treeview 1 17
How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
If you haven’t already, I encourage you to read the first article (http://www.experts-exchange.com/articles/18680/An-Introduction-to-R-Programming-and-R-Studio.html) in my series to gain a basic foundation of R and R Studio.  You will also find the …
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now