Saturday, August 4, 2018

Display Remaining Session Time and alert before Expire

Hello Readers,
Sometimes we have such a need that we have to show remaining time of session timeout and give
alert to the user before a particular time. So, we’ll see the code for the same requirement.
I am using ASP.NET MVC framework and Jquery as scripting language.
Step: 1 Add following code in web.config file:
<system.web>
<sessionState timeout="20"></sessionState>
</system.web>
Note: Give timeout value as per required session out time.
Step: 2 Add following code in MVC View at top. This is the code to fetch session timeout details.
@{
var conf = System.Web.Configuration.WebConfigurationManager.
OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.
ApplicationVirtualPath);
var section = (System.Web.Configuration.SessionStateSection)conf.
GetSection("system.web/sessionState");
       string timeout = section.Timeout.TotalMinutes.ToString();
}
Step: 3 Add a div to the view, to which we will make alert dialog for user.
Here we’ll give alert before 5 minutes.
<div id="sessionDialog" style="display: none">
Your session is about to expire in 5 minutes. Press Resume to keep alive.
<input type="button" id="btnResume" value="Resume"
onclick="ResumeSession(@timeout);" />
<input type="button" id="btnContinue" value="Continue"
onclick="ContinueSession();" />
</div>
Step: 4 Add a <p> tag in which we’ll show remaining timings of the session.
<p id="Sess"></p>
Step: 5 Add code in <script> tag
<script>
var Rtm = 0;
       var isContinue = false;
       function OpenInputDialog(x) {
           clearInterval(x);
           var fL = 0;
           $("#sessionDialog").dialog({
               autoOpen: false,
               modal: true,
               title: "Session Warning!",
               dialogClass: 'dialog1',
               closeOnEscape: true,
               close: function () {
                   $(this).dialog("close");
               },
               show: { effect: "clip", duration: 300 }
           });
           
           $("#sessionDialog").dialog("open");
           
       };
       function fn_SessionCount(tt)
       {
           if(!go)
               return;
           var t= 0;
           t= tt-1;
           var time = 0;
           time = 60;
var x = setInterval(function () {
  document.getElementById("Sess").innerHTML = "";
  document.getElementById("Sess").innerHTML = t+" Minutes "
+ time+" Seconds";
               time -= 1;
               if(time == 0)
               {
                   t -= 1;
                   time = 60;
               }
               if (t < 2) {
                   Rtm = t+1;
                   if(isContinue == false)
                   {
                       OpenInputDialog(x);
                   }
               }
               if(t == 0 && time == 1)
               {
                   clearInterval(x);
                   location.href = '../Login/Logout';
               }
           }, 1000);
       }
       function ResumeSession(tm)
       {
           var ss =0;
           debugger
           $.ajax({
               url: '../Login/SessionTimeout',
               data:{time:tm+""},
               dataType: "json",
               type: "GET",
               async:false,
               success: function (data) {
                   $("#sessionDialog").dialog("close");
                   ss=1;
               },
               error: function () {
                   alert(" An error occurred.");
               }
           });
           if (ss==1) {
               fn_SessionCount(@timeout);
       }
   }
   function ContinueSession()
   {
       go = true;
       isContinue = true;
       $("#sessionDialog").dialog("close");
       fn_SessionCount(Rtm);
   }
</script>
Step: 6 Add style for dialog box.
<style>
.dialog1 {
       background-color:lightblue;
       /* Give your desired design for dialog box */
    }
</style>
Step: 7 Call the function on page load.
$(document).ready(function () {     
     go = true;
     fn_SessionCount(@timeout);  
});
Save & build the code and run.
I hope it will help.
Subscribe my youtube channel HERE for programming related tutorials.
Feel free to mail me - Singhrudrapratap29@gmail.com
Happy coding.
Rudra Pratap Singh
Software Engineer

Thursday, November 2, 2017

How to save data temporarily before permanent saving in database?



Sometimes, we are asked to create a code in such a manner that we have to show the data to the user temporarily and after getting confirmation from user it get saved in the database table. 

To achieve this, we can use data table as a temporary storage to show data to the user. I am presenting logic here to save data temporarily. It is in C# language.

DataTable - A DataTable is an in-memory representation of a single database table which has collection of rows and columns. To know more about data table, CLICK HERE.

The code is:
static void Main(string[] args)
        {
            string[] ar = { "John", "Shelly", "Kelly", "Steve" }; // Example Collection
            int i = 0; // we will use it for ID column value
            DataTable dt = new DataTable(); // New Instance of Data Table
            // Adding new columns
            dt.Columns.Add("Id");
            dt.Columns.Add("Name");
            dt.AcceptChanges(); // Save changes
            foreach (string it in ar) // Loop to save data
            {
                i++; // This variable is used to insert ID value with increment
                DataRow dtr = dt.NewRow();
                dtr["Id"] = i;
                dtr["Name"] = it;
                dt.Rows.Add(dtr); // Adding Data row to the data table
                dt.AcceptChanges(); // save changes
            }
            foreach (DataRow dr in dt.Rows) // Loop to display
            {
                Console.WriteLine("Id is {0} and {1}",dr["Id"],dr["Name"]);
            }


        }
Output is:




To delete any data row by indexing, we can use following code-

dt.Rows.RemoveAt(1); // here 1 is index number means second data
To delete data with condition –
for (int j = 0; j < dt.Rows.Count; j++)
           {
               DataRow dr = dt.Rows[j];
               if (Convert.ToInt32(dr["Id"]) == 3) // condition to check record having ID = 3
               {
                    dr.Delete(); // deleting record
               }
               dt.AcceptChanges();
           }
 

Happy Coding

My You Tube Channel – Click Here
Rudra Pratap Singh
Software Engineer

How to Get Organic Views on Your Channel/Content

 Hi Friends, This post will be very short and specific in the information.  If you are a content creator and want some help in getting organ...