Solved

need to seperate dates into datepart date and datepart time

Posted on 2011-09-19
11
339 Views
Last Modified: 2012-05-12
I have updated the database, I can get the time to show the getNow date as datePart like 1/1/2011
I have added two fields called:
dateGathered as short date and timeGathered as mediumTime

instead of passing the getNow date I need to be able to allow the input of a date and time....ideally I would like to use a datePicker but not sure how to go about it....however if I can just get the dates to pass correctly after being inserted as text that would work for now.

have not starated on the code part so here goes the flying leap.

frontend:
<%@ 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.WebControls.CheckBox 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.Checked);

					// 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 completeFile)
        {
            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"] = completeFile;

            // 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
  • 6
  • 5
11 Comments
 
LVL 7

Expert Comment

by:NauticalNonsense
ID: 36564524
This should give you a good start... I'm not sure how the access database wants it, but this might do it... you can format the DateTime any way you want once you have it at your dbrow dealy.


<%@ 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" />
    <br />
    <br />
    Enter the Date: <asp:TextBox ID="tbDate" runat="server" />
    <br />
    <br />
    Enter the Time: <asp:TextBox ID="tbTime" runat="server" />
    <br />
    <br />
    <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>
            <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>
            <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

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;
        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, complete.Checked, myDateTime);

					// 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 checkedFile, DateTime myDateTime)
        {
            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"] = checkedFile;
            dbRow["dateGathered"] = myDateTime.Date.ToShortDateString();
            dbRow["mediumtime"] = myDateTime.Date.ToShortTimeString();

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

Author Comment

by:Tagom
ID: 36564581
man you are fast!
I tried it and except for the time it works
What happens when i put the time in is this
I inserted 12:45 pm in text box
what was recorded was 12:00 am

and actually for what I am doing this works much better than a datePicker!
I can't thank you enough for helping me walk through this
0
 
LVL 7

Expert Comment

by:NauticalNonsense
ID: 36564591
try this for my line 177:

dbRow["mediumTime"] = myDateTime.ToString("t");

or

dbRow["mediumTime"] = myDateTime.ToString("T");

lemme know how it works
0
 

Author Comment

by:Tagom
ID: 36564601
dbRow["mediumTime"] = myDateTime.ToString("t");

should "mediumTime" not be the column name timeGathered - ?
0
 
LVL 7

Accepted Solution

by:
NauticalNonsense earned 500 total points
ID: 36564602
Oh, you are correct...

dbRow["timeGathered"] = myDateTime.ToString("t");

dbRow["timeGathered"] = myDateTime.ToString("T");
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:Tagom
ID: 36564607
I had to change it on the other code because it gave me an error....
0
 
LVL 7

Expert Comment

by:NauticalNonsense
ID: 36564608
in that case, my original code might work as well, so you can try that line, .... I put in the wrong column name :)
0
 
LVL 7

Expert Comment

by:NauticalNonsense
ID: 36564609
original code being the right code of course...

dbRow["timeGathered"] = myDateTime.Date.ToShortTimeString();

0
 

Author Closing Comment

by:Tagom
ID: 36564613
woohoo! works perfectly.....
Thank you so very very much!...I have been at this for about 14 hours...going to call it a night...thank you again
0
 

Author Comment

by:Tagom
ID: 36564615
I changed it the first time...so the second code is correct
0
 
LVL 7

Expert Comment

by:NauticalNonsense
ID: 36564616
Hey, no problem... I'm ready to call it quits too.

Happy to help!
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
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 goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

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

12 Experts available now in Live!

Get 1:1 Help Now