简体   繁体   中英

How do I get cookies to work with an asp.net web app?

all. I have a little coding problem that I hope you can help me with. I'm making a stopwatch timer for my job. My boss wants to make a program for the company that will help keep track of employee time for assigned tasks. I was told I should make it using asp.net, which I have never worked with before. I managed to get the timer working to a degree, and it does everything it is supposed to except for saving the session. This last thing I need to do is to be able to have the timer still ticking if the user closes the window or reloads the page. I figured the best way to do this would be to use cookies. The view state itself works fine except it doesn't save the timer value at the time of reload. And if I open up a new page in a tab it starts everything over. I found out how to make cookies, but I don't believe I'm using them right. If anyone could help me figure out this problem I would appreciate it.

This is the aspx code (I have a bit of javascript in there because I'm trying to see about implementing the timer that way so that it will be more accurate so please just ignore that):

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="NerdcoreTimer._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
 <script type="text/javascript">
   var seconds = 0;
   var minutes = 0;
   var hours = 0;
   var tick;

  function stopCount() {
    clearTimeout(t);
  }

function startCount() {
    document.getElementById('seconds').innerHTML = seconds;
    document.getElementById('minutes').innerHTML = minutes;
    document.getElementById('hours').innerHTML = hours;
    seconds = seconds + 1;
    if (seconds == 60) {
        seconds = 0;
        minutes = minutes + 1;
    }
    if (minutes == 60) {
        minutes = 0;
        hours = hours + 1;
    }
    tick = setTimeout("startCount()", 1000)
}

function reset() {
    seconds = 0;
    minutes = 0;
    hours = 0;
    document.getElementById('seconds').innerHTML = seconds;
    document.getElementById('minutes').innerHTML = minutes;
    document.getElementById('hours').innerHTML = hours;
}

function startTimer() { return $find('Timer1')._startTimer(); }
function stopTimer() { return $find('Timer1')._stopTimer(); }
</script>

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

<div>
    <table align="center">
        <tr>
            <td>
                <asp:DropDownList ID="Tasks" runat="server" Width="75px">
                    <asp:ListItem>Task 1</asp:ListItem>
                    <asp:ListItem>Task 2</asp:ListItem>
                    <asp:ListItem>Task 3</asp:ListItem>
                    <asp:ListItem>Task 4</asp:ListItem>
                    <asp:ListItem>Task 5</asp:ListItem>
                    <asp:ListItem>Task 6</asp:ListItem>
                </asp:DropDownList>
            </td>
            <td style="text-align:center">
                <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                    <ContentTemplate>
                        <asp:Timer ID="Timer1" runat="server" Enabled="false" Interval="879" OnTick="Timer1_Tick"></asp:Timer>
                        <asp:Label ID="hour2" runat="server" Text="0"></asp:Label>
                        <asp:Label ID="hour1" runat="server" Text="0"></asp:Label>
                        <asp:Label ID="colon1" runat="server" Text=":"></asp:Label>
                        <asp:Label ID="min2" runat="server" Text="0"></asp:Label>
                        <asp:Label ID="min1" runat="server" Text="0"></asp:Label>
                        <asp:Label ID="colon2" runat="server" Text=":"></asp:Label>
                        <asp:Label ID="sec2" runat="server" Text="0"></asp:Label>
                        <asp:Label ID="sec1" runat="server" Text="0"></asp:Label>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </td>
            <td>
                <asp:Button ID="Start" runat="server" OnClientClick="startTimer()" Text="Start" Width="75px" OnClick="Start_Click" />
            </td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>
                <asp:Button ID="Stop" runat="server" OnClientClick="stopTimer()" Text="Stop" Width="75px" OnClick="Stop_Click" />
                <asp:Button ID="Reset" runat="server"  Text="Reset" Width="75px" OnClick="Reset_Click" />
            </td>
        </tr>
    </table>
</div>
&nbsp
<div>
    <table align="center">
        <tr>
            <td style="text-align:center">
            <asp:UpdatePanel ID="UpdatePanel2" runat="server">
                    <ContentTemplate>
                        <asp:Label ID="startDate" runat="server" Text="Start Date: "></asp:Label>
                        <asp:Label ID="startTime" runat="server" Text=""></asp:Label>
                        <hr />
                        <asp:Label ID="stopDate" runat="server" Text="Stop Date: "></asp:Label>
                        <asp:Label ID="stopTime" runat="server" Text=""></asp:Label>
                        <hr />
                    </ContentTemplate>
                </asp:UpdatePanel>
            </td>
        </tr>
    </table>
</div>
&nbsp
<div>
    <table align="center">
        <tr>
            <td style="text-align:center">
            <asp:UpdatePanel ID="UpdatePanel3" runat="server">
                <ContentTemplate>
                        <asp:Label ID="hours" runat="server" ></asp:Label>
                        <asp:Label ID="minutes" runat="server" ></asp:Label>
                        <asp:Label ID="seconds" runat="server" ></asp:Label>
                </ContentTemplate>
            </asp:UpdatePanel>
            </td>
            <td>
            <asp:UpdatePanel ID="UpdatePanel4" runat="server">
                <ContentTemplate>
                    <asp:Button ID="Button1" runat="server" OnClientClick="startCount()" Text="Start" Width="75px"/>
                </ContentTemplate>
            </asp:UpdatePanel>
            </td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>
            <asp:UpdatePanel ID="UpdatePanel5" runat="server">
                <ContentTemplate>
                    <asp:Button ID="Button2" runat="server" OnClientClick="stopCount()" Text="Stop" Width="75px"/>
                    <asp:Button ID="Button3" runat="server" OnClientClick="reset()" Text="Reset" Width="75px"/>
                </ContentTemplate>
            </asp:UpdatePanel>
            </td>
        </tr>
    </table>
</div>

This is the code behind file in C#:

 using System;
 using System.Data.SqlClient;
 using System.Configuration;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.UI;
 using System.Web.UI.WebControls;
 using System.Timers;

 namespace NerdcoreTimer
 {
  public partial class _Default : System.Web.UI.Page
  {
    public int time_sec;
    public int time_min;
    public int time_hour;
    public string start;
    public string stop;

    HttpCookie cookieStartDate = new HttpCookie("startDate");
    HttpCookie cookieTask = new HttpCookie("task");
    HttpCookie cookieSec = new HttpCookie("seconds");
    HttpCookie cookieMin = new HttpCookie("minutes");
    HttpCookie cookieHr = new HttpCookie("hours");
    HttpCookie cookieStopDate = new HttpCookie("stopDate");

    //SQL connection string
    System.Data.SqlClient.SqlConnection sqlConnection1 =
    new System.Data.SqlClient.SqlConnection("Server=*****;Database=*****;User Id=*****;Password=*****;");

    protected void Page_Load(object sender, EventArgs e)
    {
        //Check to see if there are cookies
        if (Request.QueryString["startDate"] != null)
        {
            ReadCookie_StartDate();
        }
        if ((Request.QueryString["seconds"] != null) && (Request.QueryString["minutes"] != null) && (Request.QueryString["hours"] != null))
        {
            ReadCookie_Timer();
            //If the cookie values for seconds, minutes, and hours is not null, enable the timer and disable and enable the proper controls
            Timer1.Enabled = true;
            Stop.Enabled = true;

            Start.Enabled = false;
            Tasks.Enabled = false;
        }
        if (Request.QueryString["stopDate"] != null)
        {
            ReadCookie_StopDate();
        }

        //Open the sql connection
        sqlConnection1.Open();

        //Disable these controls on page load
        Stop.Enabled = false;
        Reset.Enabled = false;

        //Make sure the timer is disabled if starting a new session
        if (!IsPostBack)
        {
            Timer1.Enabled = false;
        }
    }

    protected void ReadCookie_StartDate()
    {
        //Get the cookie names
        String strCookieStart = Request.QueryString["startDate"].ToString();
        String strCookieTask = Request.QueryString["task"].ToString();

        //Grab the cookies
        HttpCookie cookieStart = Request.Cookies[strCookieStart];
        HttpCookie cookieTask = Request.Cookies[strCookieTask];

        //Check to make sure the cookies exist
        if ((cookieStart != null)&&(cookieTask != null))
        {
            String strCookieStartValue = cookieStart.Value.ToString();
            startTime.Text = strCookieStartValue;
            String strCookieTaskValue = cookieTask.Value.ToString();
            Tasks.SelectedValue = strCookieTaskValue;
        }
    }

    protected void ReadCookie_Timer()
    {
        //Get the cookie names
        String strCookieSec = Request.QueryString["seconds"].ToString();
        String strCookieMin = Request.QueryString["minutes"].ToString();
        String strCookieHr = Request.QueryString["hours"].ToString();

        //Grab the cookies
        HttpCookie cookieSec = Request.Cookies[strCookieSec];
        HttpCookie cookieMin = Request.Cookies[strCookieMin];
        HttpCookie cookieHr = Request.Cookies[strCookieHr];

        //Check to make sure the cookies exist
        if ((cookieSec != null)&&(cookieMin != null)&&(cookieHr != null))
        {
            String strCookieSecValue = cookieSec.Value.ToString();
            String strCookieMinValue = cookieMin.Value.ToString();
            String strCookieHrValue = cookieHr.Value.ToString();
            sec1.Text = strCookieSecValue;
            min1.Text = strCookieMinValue;
            hour1.Text = strCookieHrValue;
        }
    }

    protected void ReadCookie_StopDate()
    {
        //Get the cookie name
        String strCookieStop = Request.QueryString["stopDate"].ToString();

        //Grab the cookie
        HttpCookie cookieStop = Request.Cookies[strCookieStop];

        //Check to make sure the cookie exists
        if (cookieStop != null)
        {
            String strCookieStopValue = cookieStop.Value.ToString();
            stopTime.Text = strCookieStopValue;
        }
    }

    protected void Start_Click(object sender, EventArgs e)
    {
        //Start the timer
        Timer1.Enabled = true;

        //Get the start date
        start = DateTime.Now.ToString();
        if (startTime.Text == "")
        {
            startTime.Text = start;
        }

        //Store the start date in a cookie
        Start_Session();

        //Enable these controls
        Stop.Enabled = true;

        //Disable these controls
        Start.Enabled = false;
        Tasks.Enabled = false;
        Reset.Enabled = false;
    }

    protected void Timer1_Tick(object sender, EventArgs e)
    {
        //Add to the sec1 label
        time_sec = int.Parse(sec1.Text);
        time_sec = time_sec + 1;
        sec1.Text = time_sec.ToString();

        //Hide the sec2 label
        if (sec1.Text == "10")
        {
            sec2.Visible = false;
        }

        //Add to the min1 label
        if (sec1.Text == "60")
        {
            sec2.Visible = true;
            time_min = int.Parse(min1.Text);
            sec1.Text = "0";
            time_min = time_min + 1;
            min1.Text = time_min.ToString();
        }

        //Hide the min1 label
        if (min1.Text == "10")
        {
            min2.Visible = false;
        }

        //Add to the hour1 label
        if (min1.Text == "60")
        {
            min2.Visible = true;
            time_hour = int.Parse(hour1.Text);
            min1.Text = "0";
            time_hour = time_hour + 1;
            hour1.Text = time_hour.ToString();
        }

        //Hide the hour2 label
        if (hour1.Text == "10")
        {
            hour2.Visible = false;
        }

        //Store the sec1, min1, and hour1 values into cookies
        TimerTick_Session();
    }

    protected void Stop_Click(object sender, EventArgs e)
    {
        //Get the stop date
        stop = DateTime.Now.ToString();
        stopTime.Text = stop;

        //Store the stop date in a cookie
        Stop_Session();

        //Disable the timer and this control
        Timer1.Enabled = false;
        Stop.Enabled = false;

        //Enable these controls
        Start.Enabled = true;
        Reset.Enabled = true;

        //Store the selected task, start date, stop date and totalTime
        string tsk = Tasks.SelectedValue;
        string dateStart = startTime.Text;
        string dateStop = stopTime.Text;

        //Create a sql query string
        string sqlString = "INSERT TimeSheet (Task,DateStart,DateStop) VALUES (@Task,@DateStart,@DateStop)";

        //Create a sql command using the query string
        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sqlString);

        //Add the selected task value, start date value, stop date and totalTime values to the query
        cmd.Parameters.AddWithValue("@Task", tsk);
        cmd.Parameters.AddWithValue("@DateStart", dateStart);
        cmd.Parameters.AddWithValue("@DateStop", dateStop);

        //Give the sql command a connection string
        cmd.Connection = sqlConnection1;

        //Execute the sql command
        cmd.ExecuteNonQuery();

        //Close the sql connection
        sqlConnection1.Close();
    }

    protected void Reset_Click(object sender, EventArgs e)
    {
        //Clear the start and stop date labels
        startTime.Text = "";
        stopTime.Text = "";

        //Reset these counters
        time_sec = 0;
        time_min = 0;
        time_hour = 0;

        //Reset the timer labels
        sec1.Text = "0";
        min1.Text = "0";
        hour1.Text = "0";

        //Make visible these timer labels
        sec2.Visible = true;
        min2.Visible = true;
        hour2.Visible = true;

        //Disable the timer and these controls
        Timer1.Enabled = false;
        Reset.Enabled = false;
        Stop.Enabled = false;

        //Enable these controls
        Start.Enabled = true;
        Tasks.Enabled = true;
    }

    protected void Start_Session()
    {
        //Create a new cookie for the start date and selected task
        //HttpCookie cookieStartDate = new HttpCookie("startDate");
        //HttpCookie cookieTask = new HttpCookie("task");

        //Set the cookie values
        cookieStartDate.Value = start;
        cookieTask.Value = Tasks.SelectedValue;

        //Set the cookie to expire in about 8 hours
        DateTime startDateExp = DateTime.Now;
        TimeSpan startDateExpMin = new TimeSpan(0, 500, 0);
        cookieStartDate.Expires = startDateExp + startDateExpMin;
        DateTime taskExp = DateTime.Now;
        TimeSpan taskExpMin = new TimeSpan(0, 500, 0);
        cookieTask.Expires = taskExp + taskExpMin;

        //Add the cookie
        Response.Cookies.Add(cookieStartDate);
        Response.Cookies.Add(cookieTask);
    }

    protected void TimerTick_Session()
    {
        //Create a new cookies for the timer
        /*HttpCookie cookieSec = new HttpCookie("seconds");
        HttpCookie cookieMin = new HttpCookie("minutes");
        HttpCookie cookieHr = new HttpCookie("hours");*/

        //Set the cookie values
        cookieSec.Value = sec1.Text;
        cookieMin.Value = min1.Text;
        cookieHr.Value = hour1.Text;

        //Set the cookies to expire in about 8 hours
        DateTime secExp = DateTime.Now;
        TimeSpan secExpMin = new TimeSpan(0, 500, 0);
        cookieSec.Expires = secExp + secExpMin;
        DateTime minExp = DateTime.Now;
        TimeSpan minExpMin = new TimeSpan(0, 500, 0);
        cookieMin.Expires = minExp + minExpMin;
        DateTime hrExp = DateTime.Now;
        TimeSpan hrExpMin = new TimeSpan(0, 500, 0);
        cookieHr.Expires = hrExp + hrExpMin;

        //Add the cookies
        Response.Cookies.Add(cookieSec);
        Response.Cookies.Add(cookieMin);
        Response.Cookies.Add(cookieHr);
    }

    protected void Stop_Session()
    {
        //Create a new cookie for the stop date
        //HttpCookie cookieStopDate = new HttpCookie("stopDate");

        //Set the cookie value
        cookieStopDate.Value = stop;

        //Set the cookie to expire in about 8 hours
        DateTime stopDateExp = DateTime.Now;
        TimeSpan stopDateExpMin = new TimeSpan(0, 500, 0);
        cookieStopDate.Expires = stopDateExp + stopDateExpMin;

        //Add the cookie
        Response.Cookies.Add(cookieStopDate);
        }
    }
}

Any help in getting this code to save the session state would be greatly appreciated. Thanks.

I'd like to comment quickly on Database handling as well, as you may want to consider abstracting Data layer from your presentation layer, in another words, consider creating a separate project or class for data handling rather than doing everything on the same place.

Also, you may have found out already but View State preserve page state between post backs, as it stores session info on the page, but in case of a reload then there is no view state any more.

Apart from that, my apology I read it quickly, but it seems you're trying to rewrite microsoft session handling, look for asp.net session handling.

those are my 2 cents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM