Solved

I need to return data from table to webpage

Posted on 2011-09-26
2
351 Views
Last Modified: 2012-05-12
I have the aspx webpage collecting the data and storing it correctly. I have the aspx.cs page working correctly in the background.
It has been a long time since I have had to program in aspx I need some help with the returning of data.
ASPX page
<%@ Page Language="c#" AutoEventWireup="false" CodeBehind="FSU.aspx.cs" Inherits="FileUpload.WebForm1"
    Src="FSU.aspx.cs" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<!-- TemplateBeginEditable name="doctitle" -->
	<title>Mercury Deposition Project</title>
	<meta name="description" content="Designed and developed by Codify Design Studio - codifydesign.com" />
	<!-- TemplateEndEditable -->
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
		<script src="SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
		<link href="SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
		<!-- TemplateBeginEditable name="head" -->
		<!-- TemplateEndEditable -->
</head>
<body ms_positioning="GridLayout">

		<div class="bannerArea">
			<div class="container">
				<div class="bannernav"><a href="#" >Privacy Policy</a> &bull; <a href="#" >Contact Us</a> &bull; <a href="#" >Site Map</a></div>
				<div class="toplogo"><a href="index.htm" ><br/>Mercury Deposition Project</a><br/></div>
				<div style="clear:both;"></div>
			</div>
		</div>
<div class="topnavigationArea">
			<div class="container"> 
				<div class="topnavigationgroup">
					<ul id="MenuBar1" class="MenuBarHorizontal">
						<li><a class="MenuBarItemSubmenu" href="http://uwf.edu/hgdeposition/Publish/grantDetails.htm">Grant Details</a>
							<ul>
								<li><a href="http://uwf.edu/hgdeposition/Publish/methods.htm">Methods</a></li>
								<li><a href="http://uwf.edu/hgdeposition/Publish/localCollectionSites.htm">Local Collection Sites</a></li>
								<li><a href="http://uwf.edu/hgdeposition/Publish/regionalCollectionSites.htm">Regional Collection Sites</a></li>
                                <li><a href="http://uwf.edu/hgdeposition/Publish/photoJournal.htm">Photo Journal</a></li>
                                <li><a href="http://uwf.edu/hgdeposition/Publish/acknowledgements.htm">Acknowledgements</a></li>
							</ul>
						</li>
						 <li><a class="MenuBarItemSubmenu" href="">Deliverables</a>
							<ul>
								<li><a href="http://uwf.edu/hgdeposition/Publish/conferences.htm">Conferences</a></li>
								<li><a href="http://uwf.edu/hgdeposition/Publish/publications.htm">Publications</a></li>
							</ul>
						</li>
						<li><a class="MenuBarItemSubmenu" href="">Participants</a>
							<ul>
								<li><a href="http://uwf.edu/hgdeposition/Publish/janeCaffrey.htm">Dr. Jane Caffrey</a></li>
								<li><a href="http://uwf.edu/hgdeposition/Publish/sikhaBagui.htm">Dr. Sikha S. Bagui</a></li>
								<li><a href="http://uwf.edu/hgdeposition/Publish/suhashBagui.htm">Dr. Subhash C. Bagui</a></li>
								<li><a href="http://uwf.edu/hgdeposition/Publish/williamLanding.htm">Dr. William Landing</a></li>
							</ul>
					  </li>
                      <li><a class="MenuBarItemSubmenu" href="">DataBase</a>
						  <ul>
								<li><a href="http://uwf.edu/hgdeposition/Publish/dataRequest.htm">Data Request</a></li>
									<ul>
										<li><a href="http://uwf.edu/hgdeposition/Publish/standardView.htm">Standard View</a></li>
                                        <li><a href="http://uwf.edu/hgdeposition/Publish/databaseDocumentation.htm">Database Documentation</a></li>
									</ul>
								<li><a href="uploadFiles">Upload Files</a></li>
									<ul>
										<li><a href="http://uwf.edu/hgdeposition/Publish/FSU.htm">FSU</a></li>
										<li><a href="http://uwf.edu/hgdeposition/Publish/UWF.htm">UWF</a></li>
									</ul>
								<li><a href="http://uwf.edu/hgdeposition/Publish/dataInput.htm">Data Input</a></li>
									<ul>
										<li><a href="http://uwf.edu/hgdeposition/Publish/rainEventsTable.htm">Rain Events Table</a></li>
										<li><a href="http://uwf.edu/hgdeposition/Publish/contaminationTable.htm">Contamination Table</a></li>
									</ul>

								<li><a href="http://uwf.edu/hgdeposition/Publish/dataCleaningConsiderations.htm">Data Cleaning Considerations</a></li>
                                <li><a href="http://uwf.edu/hgdeposition/Publish/dataMiningTechniques.htm">Data Mining Techniques</a></li>
                                <li><a href="http://uwf.edu/hgdeposition/Publish/challenges.htm">Challenges</a></li>
						  </ul>
						</li>
						<li style="border-right-style: solid;"><a href="http://uwf.edu/hgdeposition/Publish/sponsors.htm">Sponsors</a></li>
					</ul>
				</div>
				<div style="clear:both;"></div>
			</div>
		</div>
		<div class="contentArea">
			<div class="container"><!-- TemplateBeginEditable name="content" -->
				<div class="contentleft">
    <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>
    <br />
    <input id="filMyFile" type="file" runat="server">
    <p>
    </p>
    <asp:Label ID="notesLabel" runat="server" Font-Bold="True">Please give a description of the file you are uploading:<br /></asp:Label>
    <input id="lblnotes1" type="Text" runat="server">
    <br />
    <br />
  
    <asp:Button ID="cmdSend" runat="server" Text="Submit File to Database Folders" />
    <p>
    </p>
    <asp:Label ID="lblInfo" runat="server" Font-Bold="True" Visible="false"></asp:Label>
    <p>
    </p>
    <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>
    <br />
    <br />
    <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>
    <asp:Image ID="imgFile" runat="server" Visible="False"></asp:Image> <br />
    <asp:Image ID="imgDB" runat="server" Visible="False"></asp:Image> <br />
    </form>
    </div>
			<!-- TemplateEndEditable --><!-- TemplateBeginEditable name="sidebar" -->
			<div class="contentright">
				<h2>The Center for Environmental Diagnostics and Bioremediation.</h2>
				<img src="images/uwf.jpg" width="103" height="105" border="0" class="imageright" />
<p>The Center for Environmental Diagnostics and Bioremediation
  (CEDB) reflects a fundamental emphasis on modern biological research as applied to environmental systems.</p>
<p>The Center for Environmental Diagnostics and Bioremediation at the   University of West Florida provides a vital program of research and   education.</p>
			</div>
			<!-- TemplateEndEditable -->
			<div style="clear:both;"></div>
			</div>
		</div>
		<div class="footerArea">
			<div class="container"> 
				<div class="copyright">&copy; 2009 Our Company.  All rights reserved.</div>
			</div>
		</div>
		
		<script type="text/javascript">
		<!--
		var MenuBar1 = new Spry.Widget.MenuBar("MenuBar1", {imgDown:"SpryAssets/SpryMenuBarDownHover.gif", imgRight:"SpryAssets/SpryMenuBarRightHover.gif"});
		//-->
		</script>
</body>
</html>

Open in new window


aspx.cs page
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 = "FileUpload2.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.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;
        //protected System.Web.UI.WebControls.TextBox tbDate;
        //protected System.Web.UI.WebControls.TextBox tbTime;
        //protected System.Web.UI.WebControls.CheckBox complete;

        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);

                    // Grab the dates, and put it into a datetime
                    //DateTime myDateTime = DateTime.Parse(tbDate.Text + " " + tbTime.Text);
                    // that gives you a true asp.net datetime, and you can format that
                    // however you like later....

                    // 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 = "File Name: " + " " + 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 = "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)
        {
            int nFileID = 0;

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

            // Create Adapter
            OleDbDataAdapter dbAdapt = new OleDbDataAdapter("SELECT * FROM FSUdata", 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, "FSUdata");

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

            // 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"] = checkedFile;
            //dbRow["dateGathered"] = myDateTime.Date.ToShortDateString();
            //dbRow["timeGathered"] = myDateTime.ToString("t");

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

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

            // 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 FSUdata 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
2 Comments
 
LVL 7

Accepted Solution

by:
NauticalNonsense earned 500 total points
ID: 36598896
Hey Dude!

Have you tried with a text file? What is the behavior of the page when you submit a TXT, JPG, or HTML file? Returns nothing, blank page, error, ... ?

And are you SURE that you're getting it back right? If you want to test, you can upload a small TXT file, and do a Response.Write(byte[])dbRead["FileData"], 0, (int)dbRead["FileSize"]);
0
 

Author Comment

by:Tagom
ID: 36599021
I am pretty sure that the data is being returned correctly:
But I also know that I do not have the code written correctly to return the data rows.
I know that it should be put in the .aspx page
I also need to be able to write the information out to a scv or txt file. Where would I put the Response.Write code to get the information returned correctly
the aspx page or the aspx.cs page...front end or back end?
0

Featured Post

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.

Join & Write a Comment

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 …
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

747 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

9 Experts available now in Live!

Get 1:1 Help Now