Solved

adding checkbox to form

Posted on 2011-09-19
9
347 Views
Last Modified: 2012-05-12
Need to add a checkbox to the following files:
Need to store as a Boolean in the database:
front 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="lab1" 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="notesLabel" 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

backend 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.HtmlControls.HtmlInputText lblnotes1;
        protected System.Web.UI.HtmlControls.HtmlInputText 
        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, lblnotes1.Value);

					// 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 strNotes, bool )
        {
            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"] = strNotes;
            dbRow["completeFile"] = ShowInNewWindow.Checked;

            // 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

0
Comment
Question by:Tagom
  • 5
  • 3
9 Comments
 
LVL 9

Expert Comment

by:BlueYonder
ID: 36564125
In the aspx page add the following for a checkbox
<asp:checkbox ID="chkboxName" runat="server'></asp:checkbox>

When assigning the value to sql assign
sqlVal = Convert.ToBoolean(chkboxName.value);

chkboxName.checked = sqlVal;
0
 
LVL 7

Expert Comment

by:NauticalNonsense
ID: 36564246
Hey Tagom,
What does the checkbox do? And what will it say?
0
 

Author Comment

by:Tagom
ID: 36564269
@NauticalNonsense THANK YOU:
okay,
The checkbox passes a Boolean into a access Database:
The column name is completeFile, the form label is imported?
I have been working on some but am struggling:
What I have so far:
front end:
<%@ 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="lab1" 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="notesLabel" runat="server" Font-Bold="True">Please Select the Data File you will be uploading:</asp:label>
				<input id="lblnotes1" type="Text" runat="server">
                <asp:CheckBox id="complete"  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


backend:
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.HtmlControls.HtmlInputText lblnotes1;
        protected System.web.UI.HtmlControls.HtmlInputText complete;
        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, lblnotes1.Value, complete.Value);

					// 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 strNotes, bool )
        {
            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"] = strNotes;
            dbRow["completeFile"] = complete.Checked;

            // 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

0
 
LVL 7

Expert Comment

by:NauticalNonsense
ID: 36564278
Change line 21 to

protected System.Web.UI.WebControls.CheckBox complete

Give that a shot and get back to me. :)

0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 7

Expert Comment

by:NauticalNonsense
ID: 36564281
also, if you error out, post what you get.
0
 

Author Comment

by:Tagom
ID: 36564304
This results from not going all the way through the .cs file and putting all the info in it.....am working on it now.

Compiler Error Message: CS1001: Identifier expected

Source Error:

Line 129:
Line 130:        // Writes file to the database
Line 131:        private int WriteToDB(string strName, string strType, ref byte[] Buffer, string strNotes, bool )
Line 132:        {
Line 133:            int nFileID = 0;
0
 
LVL 7

Accepted Solution

by:
NauticalNonsense earned 500 total points
ID: 36564315
ah, i see
line 81,

                   int nFileID = WriteToDB(strFilename, myFile.ContentType, ref myData, lblnotes1.Value, complete.Checked);

line 131,
private int WriteToDB(string strName, string strType, ref byte[] Buffer, string strNotes, bool completeFile)


then line 169

 dbRow["completeFile"] = completeFile;

Maybe?

0
 

Author Closing Comment

by:Tagom
ID: 36564353
Quick concise thorough!
Thank you again:
I am opening another question concerning datetime passing....
0
 
LVL 7

Expert Comment

by:NauticalNonsense
ID: 36564389
Awesome! In line 81, you're passing the True/False value of "complete" into line 131's private variable completeFile, and then in 169 assigning that boolean to your completeFile row.

Thanks for the points and grade!
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
This article will show, step by step, how to integrate R code into a R Sweave document
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

707 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

20 Experts available now in Live!

Get 1:1 Help Now