locked
Alert box for every 10 mints using asp.net c# web form RRS feed

  • Question

  • User-471420332 posted

    I need alert box for every 10 mints using asp.net c# web form, if the page also post back then also time should not loose and main correct alert system. Any code or logic for this, please help me to out this. if we write this using java script then after post back the previous time is loosing. I am not understanding I have to use session for main time, postback loosing time.

    Please help to out this.

    Monday, October 8, 2018 11:06 AM

Answers

  • User475983607 posted

    You are missing a jQuery reference.  Place the script tag after the form tag or place the scripts inside the jQuery ready event. 

    Remember to do basic troubleshooting by opening dev tools (F12) and viewing the console for errors.  You should be seeing  Uncaught ReferenceError: $ is not defined.

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            </div>
        </form>
    
        <script>
    
            var timerDefault = 1 * 60;
    
            function SetTimer(seconds) {
    
                setTimeout(function () {
                    alert('Timeout!');
                    RestTimer(timerDefault);
                }, 1000 * seconds);
            }
    
            function RestTimer(seconds) {
    
    
                var data = { seconds: seconds };
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/UpdateSessionTimer",
                    data: JSON.stringify(data),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        SetTimer(response.d);
                        $('#<%=Label1.ClientID%>').text(response.d);
                    }
                });
            }
        </script>
    
    </body>
    </html>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 9, 2018 8:29 PM

All replies

  • User475983607 posted

    I need alert box for every 10 mints using asp.net c# web form, if the page also post back then also time should not loose and main correct alert system. Any code or logic for this, please help me to out this. if we write this using java script then after post back the previous time is loosing. I am not understanding I have to use session for main time, postback loosing time.

    Please help to out this.

    Cookies and Session are two openly published ASP.NET state management feature that you can take advantage of.

    I am not understanding I have to use session for main time, postback loosing time.

    At the very least, post the code that you've tried and explain the expected and actual results?  

    I would assign a  DateTime to a Session or cookie.  Then check the variable on post back and write (Serialize) the DateTime value to JavaScript for use in a JavaScript timer. 

    It is hard to understand how your code is losing Session or Cookie values when we cannot see the code.

    Monday, October 8, 2018 11:55 AM
  • User-471420332 posted

    Any code or Example, I did not started my code part, please share if you understand my requirement.

    after login current date time assigning to session varaible

    Session["Date"] = DateTime.Now.ToString();

    Page_load retrieving date
    //Retrieve date
    string date = Session["Date"] as string;

    What is next i am not getting please help to out this.

    Monday, October 8, 2018 12:03 PM
  • User475983607 posted

    mazhar khan india

    Any code or Example, I did not started my code part, please share if you understand my requirement.

    after login current date time assigning to session varaible

    Session["Date"] = DateTime.Now.ToString();

    Page_load retrieving date
    //Retrieve date
    string date = Session["Date"] as string;

    What is next i am not getting please help to out this.

    Your asking the community to analyze and design a solution with, at best, vague requirements.  There's an infinite number of designs that will meet the requirements and I'm confident there are also unknown requirements.  These unknowns will show up as the community provides design solutions and code samples.  It is always best to create your own designs.  If you run into trouble, explain the design and post the code.  That helps us to identify the holes in your understanding.

    If you are a student, then make an appointment with your instructor and ask for assistance.  If this is an actual feature you are assigned to implement for your job then get with your team and ask for assistance in completing the task.

    I went ahead, against my better judgement, and provided a basic code example.  The concept is very simple and loosely based on the code you provided.  The code behind populates a JavaScript timer to fire in the future.  The page will adjust the JavaScript timer timeout if the page is refreshed.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebFormsApp
    {
        public partial class _Default : Page
        {
            private const int TimeoutMinutes = 1;
            private double seconds;
    
            protected void Page_Load(object sender, EventArgs e)
            {
    
                if (Session["Date"] == null)
                {
                    InitTimer();
                }
                else
                {
                    DateTime currentTimeout = (DateTime)Session["Date"];
                    seconds = (currentTimeout - DateTime.Now).TotalSeconds;
                    if(seconds > 0)
                    {
                        RenderTimerScript(seconds);
                    }
                    else
                    {
                        //The timer has expired.  Do Something.
                        Label1.Text = "The timer has expired.  Do Something.";
                        return;
                    }
                    
                }
    
                Label1.Text = seconds.ToString();
    
            }
    
    
            protected void InitTimer()
            {
                //Init Timeout and Session
                seconds = 60 * TimeoutMinutes;
                Session["Date"] = DateTime.Now.AddSeconds(seconds);
    
                RenderTimerScript(seconds);
            }
    
            protected void RenderTimerScript(double seconds)
            {
                //Init Script timer
                string script = @"<script language='javascript'>setTimeout(function(){ alert('Timeout!'); }, 1000 * " + seconds + ");</script>";
                if (!ClientScript.IsStartupScriptRegistered("TimerScript"))
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "TimerScript", script);
                }
            }
        }
    
    
    }

    It is not clear what's supposed to happen after the timeout event.   It is also not clear if this requirement is page or application scoped.  Anyway, I recommend that you meet with your professor or team to iron out the requirement details.

    I also recommend that you set aside time to learn web development basics focusing on HTTP and state in HTTP applications.  Understanding how to maintain and pass state is required in every web application regardless of the technology.

    Monday, October 8, 2018 3:11 PM
  • User-471420332 posted

    When candidate will login I need an Alert box for every 10  minutes using asp.net c#, but your code is not giving correct result what i am expecting. Only coming first time alert next time onward alert is not coming. Hope you understand my thing.

    Monday, October 8, 2018 3:45 PM
  • User475983607 posted

    When candidate will login I need an Alert box for every 10  minutes using asp.net c#, but your code is not giving correct result what i am expecting. Only coming first time alert next time onward alert is not coming. Hope you understand my thing.

    Yes, I know how the code works.  I explained clearly and openly that it is up to you to do something after the first alert. 

    Simply call InitTimer(); in the else to restart the timer.  I assume you want to do something after the timeout?

            protected void Page_Load(object sender, EventArgs e)
            {
    
                if (Session["Date"] == null)
                {
                    InitTimer();
                }
                else
                {
                    DateTime currentTimeout = (DateTime)Session["Date"];
                    seconds = (currentTimeout - DateTime.Now).TotalSeconds;
                    if(seconds > 0)
                    {
                        RenderTimerScript(seconds);
                    }
                    else
                    {
                        //The timer has expired.  Do Something.
                        //Label1.Text = "The timer has expired.  Do Something.";
                        //return;
                        InitTimer();
                    }
                    
                }
    
                Label1.Text = seconds.ToString();
    
            }

    Monday, October 8, 2018 4:23 PM
  • User-893317190 posted

    Hi mazhar khan india ,

    You could also use the way below to init time.

     protected void Page_Load(object sender, EventArgs e)
            {
              
                    if(null!= Session["loginTime"])
                    {
                  // get data from session
                    var loginTime =Convert.ToDateTime( Session["loginTime"]);
                                                                                  //pass the minute after which to alert warning    
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "myScript", "alertWarning("+ (DateTime.Now - loginTime).Minutes % 10 + ")", true);
                    }
                    
                
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
    //save the loginTime to session Session["loginTime"] = DateTime.Now; // register script ,if you want to alert warning as soon as the user login , change the parameter 10 to 0 ScriptManager.RegisterStartupScript(this, this.GetType(), "myScript", "alertWarning(10)", true); }
     <script>
    
                 
                function alertWarning(interval) {
                    // set the one-time timer 
                    setTimeout(function () {
    // in the one-time timer
    // set another timer setInterval(function () { alert("warning"); }, 60*10*1000); alert("warning"); },interval*1000*60) } </script>

    The result. To see the result, I change the interval to 5 seconds.

    Best regards,

    Ackerly Xu

    Tuesday, October 9, 2018 5:46 AM
  • User-471420332 posted

    Your code is not working when page is refresh and if i will staty on page for 1 minute then first alert is coming second alert again it not showing

    Tuesday, October 9, 2018 5:58 AM
  • User-893317190 posted

    Hi mazhar khan india,

    From the  gif I have posted, you could see when I click post back , the window alert two times.

    Maybe we have different code environment.Could you show me how you use my code in your code?

    Best regards,

    Ackerly Xu

    Tuesday, October 9, 2018 6:52 AM
  • User-471420332 posted

    Dear Ackerly thank for you valuable reply,

    In my login.aspx page passing session time as below

    Session["loginTime"] = DateTime.Now;

    In my test.aspx page page load wrote below code and Actually this an online test have 30 question with four options, every answer page will be referesh or postback and in same test.aspx page all questions will apear but every question have on post back.

    if (!IsPostBack)
    {

    if (null != Session["loginTime"])
    {
    // get data from session
    var loginTime = Convert.ToDateTime(Session["loginTime"]);
    //pass the minute after which to alert warning
    ScriptManager.RegisterStartupScript(this, this.GetType(), "myScript", "alertWarning(" + (DateTime.Now - loginTime).Minutes % 10 + ")", true);
    }

    }

     
    
    Below is code for capturing photo by calling takepic() function
    
           <script type="text/javascript">
    
            function takepic() {
                // first part   
                context.drawImage(video, 0, 0, 320, 240);
                //above line take the picture
                //second part save the picture
                var image = document.getElementById("canvas").toDataURL("image/png");
                alert(image);
    
                //get raw image data
                image = image.replace('data:image/png;base64,', '');
    
                $.ajax({
                    type: "POST",
                    url: "pcassessment.aspx/SaveUser",
                    data: '{"imageData": "' + image + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert("User has been added successfully.");
                        window.location.reload();
                    }
                });
                return false;
    
            }
    
    
        </script>
    
    
    For every 10 minutes need to  capture photo and calling takepic(); fucntion in your script 
    
             <script>
    
             function alertWarning(interval) {
                 // set the one-time timer 
                 setTimeout(function () {
                     // in the one-time timer 
                     // set another timer
                     setInterval(function () {
    
                         //  alert("warning");
                         takepic();
                     }, 60 * 1 * 1000);
    
                     // alert("warning");
                     takepic();
    
    
                 }, interval * 1000 * 60)
    
             }
    
         </script>

    Now issue is Page is refereshing loading and loading

     

    Tuesday, October 9, 2018 8:28 AM
  • User-893317190 posted

    Hi mazhar khan india,

    You write code in !IsPostBack , you should move the code out of !isPostBack, or it will not work when  the page posts back.

    if (!IsPostBack)
                {
                  
    
                }
    // please don't write the code below in if(!IsPostBack) if (null != Session["loginTime"]) { // get data from session var loginTime = Convert.ToDateTime(Session["loginTime"]); //pass the minute after which to alert warning ScriptManager.RegisterStartupScript(this, this.GetType(), "myScript", "alertWarning(" + (DateTime.Now - loginTime).Minutes % 10 + ")", true); }

    Best regards,

    Ackerly Xu

    Tuesday, October 9, 2018 8:47 AM
  • User-471420332 posted

    I remove !ispostback method but also page is continuously refreshing. Please check, my javascript script because its refreshing..

    For every 10 minutes need to  capture photo and calling takepic(); fucntion in your script 
    
             <script>
    
             function alertWarning(interval) {
                 // set the one-time timer 
                 setTimeout(function () {
                     // in the one-time timer 
                     // set another timer
                     setInterval(function () {
    
                         //  alert("warning");
                         takepic();
                     }, 60 * 1 * 1000);
    
                     // alert("warning");
                     takepic();
    
    
                 }, interval * 1000 * 60)
    
             }
    
         </script>

    Tuesday, October 9, 2018 8:58 AM
  • User-893317190 posted

    Hi mazhar khan india,

    I find your code

    $.ajax({
                    type: "POST",
                    url: "pcassessment.aspx/SaveUser",
                    data: '{"imageData": "' + image + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert("User has been added successfully.");
                        window.location.reload();
                    }
                });

    Please pay attention  , the code I mark as yellow will refresh the window.

    Best regards,

    Ackerly Xu

    Tuesday, October 9, 2018 9:20 AM
  • User-471420332 posted

    No loading issue solve. one more below issue came.

    If page will post back then your code is not working, if i will wait till 1:10 minute without doing any  action then working(photo capturing), example if i will do any action <1 minute then java script code is not working, its post back issue, please check once again.

    Tuesday, October 9, 2018 9:57 AM
  • User753101303 posted

    Hi,

    For  now the issue seems to be that suggested code starts this delay when the page is shown when you want it to start when the user logs ? You'll need to adapt the provided code and in particular :
    - when the user logs you would need to keep the target date/time for showing the next alert
    - each time a page is shown you would need to take this value into account so that the page starts with the correct delay
    - once sure the user has seen the alert, Schedule the next one

    From a usage poiint of view it could be best to keep the login date and just always show somewhere on the page a clock that shows how much time elapsed or how much time is left until the very end....

    Tuesday, October 9, 2018 11:53 AM
  • User-471420332 posted

    Dear, PatriceSc

    Please share alternative code to solve my issue.

    Tuesday, October 9, 2018 12:13 PM
  • User475983607 posted

    The code samples provided above work as expected.  What is not working as expected is how you're integrating the "Alert" and deciding when to invoke the methods.  

    I recommend meeting with your team or professor to get assistance.   Another alternative is sharing your fee.

    Tuesday, October 9, 2018 2:59 PM
  • User475983607 posted

    Please share alternative code to solve my issue.

    Here's an example where I refactored my original script to allow updating the timer on the client.   To do that I had to add a WebMethod to sync the client variable with the Session variable.

    <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebFormsApp._Default" %>
    
    <asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    
        <div>
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </div>
    
        <script>
    
            var timerDefault = 1 * 60;
    
            function SetTimer(seconds) {
    
                setTimeout(function () {
                    alert('Timeout!');
                    RestTimer(timerDefault);
                }, 1000 * seconds);
            }
    
            function RestTimer(seconds) {
                
    
                var data = { seconds: seconds };
               $.ajax({
                    type: "POST",
                    url: "default.aspx/UpdateSessionTimer",
                    data: JSON.stringify(data),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                   success: function (response) {
                        SetTimer(response.d);
                        $('#<%=Label1.ClientID%>').text(response.d);
                    }
                });
            }
        </script>
    
    
    </asp:Content>
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.Services;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebFormsApp
    {
        public partial class _Default : Page
        {
            private const int TimeoutMinutes = 1;
            private double seconds;
    
            protected void Page_Load(object sender, EventArgs e)
            {
    
                if (Session["Date"] == null)
                {
                    InitTimer();
                }
                else
                {
                    DateTime currentTimeout = (DateTime)Session["Date"];
                    seconds = (currentTimeout - DateTime.Now).TotalSeconds;
                    if(seconds > 0)
                    {
                        RenderTimerScript(seconds);
                    }
                    else
                    {
                        //The timer has expired.  Do Something.
                        //Label1.Text = "The timer has expired.  Do Something.";
                        //return;
                        InitTimer();
                    }
                    
                }
    
                Label1.Text = seconds.ToString();
    
            }
    
    
            protected void InitTimer()
            {
                //Init Timeout and Session
                seconds = 60 * TimeoutMinutes;
                Session["Date"] = DateTime.Now.AddSeconds(seconds);
    
                RenderTimerScript(seconds);
            }
    
            protected void RenderTimerScript(double seconds)
            {
                //Init Script timer
                string script = @"<script> $(function() { SetTimer(" + seconds + "); }); </script>";
                if (!ClientScript.IsStartupScriptRegistered("TimerScript"))
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "TimerScript", script);
                }
            }
    
            [WebMethod(EnableSession = true)]
            public static int UpdateSessionTimer(int seconds)
            {
                HttpContext.Current.Session["Date"] = DateTime.Now.AddSeconds(seconds);
                return seconds;
            }
        }
    
    
    }

    Tuesday, October 9, 2018 4:11 PM
  • User-471420332 posted

    I use your whole code but java script Alert message is not showing.. and label value is showing correct after refereshing

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title></title>


    <script>

    var timerDefault = 1 * 60;

    function SetTimer(seconds) {

    setTimeout(function () {
    alert('Timeout!');
    RestTimer(timerDefault);
    }, 1000 * seconds);
    }

    function RestTimer(seconds) {


    var data = { seconds: seconds };
    $.ajax({
    type: "POST",
    url: "Default.aspx/UpdateSessionTimer",
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
    SetTimer(response.d);
    $('#<%=Label1.ClientID%>').text(response.d);
    }
    });
    }
    </script>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <div>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>


    </div>
    </form>
    </body>
    </html>

    c# code

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public partial class _Default : System.Web.UI.Page
    {
    private const int TimeoutMinutes = 1;
    private double seconds;
    protected void Page_Load(object sender, EventArgs e)

    {
    if (Session["Date"] == null)
    {
    InitTimer();
    }
    else
    {
    DateTime currentTimeout = (DateTime)Session["Date"];
    seconds = (currentTimeout - DateTime.Now).TotalSeconds;
    if (seconds > 0)
    {
    RenderTimerScript(seconds);
    }
    else
    {
    //The timer has expired. Do Something.
    //Label1.Text = "The timer has expired. Do Something.";
    //return;
    InitTimer();
    }

    }

    Label1.Text = seconds.ToString();

    }


    protected void InitTimer()
    {
    //Init Timeout and Session
    seconds = 60 * TimeoutMinutes;
    Session["Date"] = DateTime.Now.AddSeconds(seconds);

    RenderTimerScript(seconds);
    }

    protected void RenderTimerScript(double seconds)
    {
    //Init Script timer
    string script = @"<script> $(function() { SetTimer(" + seconds + "); }); </script>";
    if (!ClientScript.IsStartupScriptRegistered("TimerScript"))
    {
    ClientScript.RegisterStartupScript(this.GetType(), "TimerScript", script);
    }
    }

    [WebMethod(EnableSession = true)]
    public static int UpdateSessionTimer(int seconds)
    {
    HttpContext.Current.Session["Date"] = DateTime.Now.AddSeconds(seconds);
    return seconds;
    }
    }

    Tuesday, October 9, 2018 7:49 PM
  • User475983607 posted

    You are missing a jQuery reference.  Place the script tag after the form tag or place the scripts inside the jQuery ready event. 

    Remember to do basic troubleshooting by opening dev tools (F12) and viewing the console for errors.  You should be seeing  Uncaught ReferenceError: $ is not defined.

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            </div>
        </form>
    
        <script>
    
            var timerDefault = 1 * 60;
    
            function SetTimer(seconds) {
    
                setTimeout(function () {
                    alert('Timeout!');
                    RestTimer(timerDefault);
                }, 1000 * seconds);
            }
    
            function RestTimer(seconds) {
    
    
                var data = { seconds: seconds };
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/UpdateSessionTimer",
                    data: JSON.stringify(data),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        SetTimer(response.d);
                        $('#<%=Label1.ClientID%>').text(response.d);
                    }
                });
            }
        </script>
    
    </body>
    </html>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 9, 2018 8:29 PM
  • User-471420332 posted

    I don't have words for you... you are super man in this forum...

    Wednesday, October 10, 2018 5:03 AM