Asp.net - Session Time out (close confirm message) - asp.net

Implemented this for session time out which is working fine:
var sessionTimeoutWarning = "1";
var sessionTimeout = "2";
var timeOnPageLoad = new Date();
var sessionWarningTimer = null;
var redirectToWelcomePageTimer = null;
//For warning
var sessionWarningTimer = setTimeout('SessionWarning()', parseInt(sessionTimeoutWarning) * 60 * 1000);
//To redirect to the welcome page
var redirectToWelcomePageTimer = setTimeout('RedirectToWelcomePage()', parseInt(sessionTimeout) * 60 * 1000);
//Session Warning
function SessionWarning() {
var minutesForExpiry = (parseInt(sessionTimeout) - parseInt(sessionTimeoutWarning));
//var minutesForExpiry = "1";
var message = "Your session will expire in another " + minutesForExpiry + " mins. Do you want to extend the session?";
//Confirm the user if he wants to extend the session
answer = confirm(message);
//if yes, extend the session.
if (answer) {
//Clear the RedirectToWelcomePage method
if (redirectToWelcomePageTimer != null) {
clearTimeout(redirectToWelcomePageTimer);
}
var currentTime = new Date();
var timeForExpiry = timeOnPageLoad.setMinutes(timeOnPageLoad.getMinutes() + parseInt(sessionTimeout));
if (Date.parse(currentTime) > timeForExpiry) {
alert("Session expired. You will be redirected to welcome page");
window.location = "../login.aspx";
}
else {
timeOnPageLoad = new Date();
sessionWarningTimer = setTimeout('SessionWarning()', parseInt(sessionTimeoutWarning) * 60 * 1000);
redirectToWelcomePageTimer = setTimeout('RedirectToLoginPage()', parseInt(sessionTimeout) * 60 * 1000);
}
}
else {
timeOnPageLoad = new Date();
sessionWarningTimer = setTimeout('SessionWarning()', parseInt(sessionTimeoutWarning) * 60 * 1000);
redirectToWelcomePageTimer = setTimeout('RedirectToLoginPage()', parseInt(sessionTimeout) * 1);
}
}
//Session timeout
function RedirectToLoginPage() {
window.location = "../login.aspx";
}
Query: when the confirm message comes up, how can we track/enable that if user didn't clicked in 5 mins on that confirmation message then I want to close that automtically and display new popup that session has expired.
Please advise

You don't have control on the alert box once you have opened it. What most you can do is to refresh the page after 5 minutes of showing alert box. So you can write setTimeout after showing alert box and then redirect a page where you can display popup that session has expired.

Related

Paypal fail after first success testing asp mvc

I am trying to implement PayPal to my web app.
The very first time PayPal payment works fine!
But if I try second time, it fails. Can I only test once???
When PayPal succeeds I see this link:
https://localhost:44333/Paypal/PaymentWithPayPal?guid=94987&paymentId=PAY-1DM32358RW0519317LDPKCYY&token=EC-1G993722W11620224&PayerID=8QXDDJEKRZKZW
When PayPal fails I see this link:
https://localhost:44333/Paypal/PaymentWithPayPal?guid=52246&paymentId=PAY-9V465873R0219235GLDPKDNA&token=EC-1F105391KF572764B&PayerID=8QXDDJEKRZKZW
This is my PayPalController:
public class PayPalController : Controller
{
[Authorize]
// GET: PayPal
public ActionResult Index()
{
return View();
}
public ActionResult PaymentWithPaypal()
{
//getting the apiContext as earlier
APIContext apiContext = Configuration.GetAPIContext();
try
{
string payerId = Request.Params["PayerID"];
if (string.IsNullOrEmpty(payerId))
{
//this section will be executed first because PayerID doesn't exist
//it is returned by the create function call of the payment class
// Creating a payment
// baseURL is the url on which paypal sendsback the data.
// So we have provided URL of this controller only
string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority +
"/Paypal/PaymentWithPayPal?";
//guid we are generating for storing the paymentID received in session
//after calling the create function and it is used in the payment execution
var guid = Convert.ToString((new Random()).Next(100000));
//CreatePayment function gives us the payment approval url
//on which payer is redirected for paypal account payment
var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);
//get links returned from paypal in response to Create function call
var links = createdPayment.links.GetEnumerator();
string paypalRedirectUrl = null;
while (links.MoveNext())
{
Links lnk = links.Current;
if (lnk.rel.ToLower().Trim().Equals("approval_url"))
{
//saving the payapalredirect URL to which user will be redirected for payment
paypalRedirectUrl = lnk.href;
}
}
// saving the paymentID in the key guid
Session.Add(guid, createdPayment.id);
return Redirect(paypalRedirectUrl);
}
else
{
// This section is executed when we have received all the payments parameters
// from the previous call to the function Create
// Executing a payment
var guid = Request.Params["guid"];
var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
if (executedPayment.state.ToLower() != "approved")
{
return View("FailureView");
}
}
}
catch (Exception ex)
{
Logger.Log("Error" + ex.Message);
return View("FailureView");
}
return View("SuccessView");
}
private PayPal.Api.Payment payment;
private Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId)
{
var paymentExecution = new PaymentExecution() { payer_id = payerId };
this.payment = new Payment() { id = paymentId };
return this.payment.Execute(apiContext, paymentExecution);
}
private Payment CreatePayment(APIContext apiContext, string redirectUrl)
{
var userId = User.Identity.GetUserId();
var userEmail = User.Identity.GetUserName();
//similar to credit card create itemlist and add item objects to it
var itemList = new ItemList() { items = new List<Item>() };
itemList.items.Add(new Item()
{
name = "Premium Monthly $99.00",
currency = "USD",
price = "99",
quantity = "1",
description = userEmail + " Pays Premium Monthly $99.00 on " + DateTime.Now.ToString("F")
});
var payer = new Payer() { payment_method = "paypal" };
// Configure Redirect Urls here with RedirectUrls object
var redirUrls = new RedirectUrls()
{
cancel_url = redirectUrl,
return_url = redirectUrl
};
// similar as we did for credit card, do here and create details object
var details = new Details()
{
subtotal = "99.00"
};
// similar as we did for credit card, do here and create amount object
var amount = new Amount()
{
currency = "USD",
total = "99.00", // Total must be equal to sum of shipping, tax and subtotal.
details = details
};
var transactionList = new List<Transaction>();
transactionList.Add(new Transaction()
{
description = userEmail + "Paid Premium Monthly $99.00 on " + DateTime.Now.ToString("F"),
invoice_number = "890918",
amount = amount,
item_list = itemList
});
this.payment = new Payment()
{
intent = "sale",
payer = payer,
transactions = transactionList,
redirect_urls = redirUrls
};
// Create a payment using a APIContext
return this.payment.Create(apiContext);
}
}
Please help!

A button to start in highcharts

Here is my charts, dynamically update. Now im trying to add a button which, to start the dynamic charts.
Ideally, i wish the data to be initialized when i press the button, however it seems that the data could not be initialized simultaneously with the method.Or let's be simply, is it possible to add a button that i could control, when to start the chart and, when to stop or pause?
var time = null;
var bol = false;
var chart;
var data = [];
// function play(){
// var time = (new Date()).getTime(), i;
// for(i = -1999; i <= 0; i += 1){
// data.push([
// time + i *1000,
// Math.round(Math.random() * 100)
// ]);
// }
// }
data = (function () {
var data = [], time = (new Date()).getTime(), i;
for (i = -1999; i <= 0; i += 1) {
data.push([time + i * 1000, Math.round(Math.random() * 100)]);
}
return data;
}());

SignalR and .NET

I'm basically trying to dynamically create a list element and update it across multiple clients. I'm using SignalR library of .NET. Following is my code.
$(function () {
// Reference the auto-generated proxy for the hub.
var listSync = $.connection.myHub1;
console.log("List Sync ");
// Create a function that the hub can call back to display messages and toggle.
listSync.client.addNewItemToPage = function (name, url) {
console.log("List Sync 3");
var play_list = document.getElementById('playlist');
var empty = document.getElementById('empty');
if (empty != null) {
empty.remove();
}
var pli = document.createElement("li");
var ptag = document.createElement('a');
var icon = document.createElement('i');
icon.setAttribute('class', "fa fa-toggle-right");
ptag.setAttribute('href', "#");
ptag.setAttribute('class', "play_track");
ptag.appendChild(icon);
ptag.innerHTML += name;
ptag.type = url;
pli.appendChild(ptag);
play_list.appendChild(pli);
//handler to play songs by playlist
var favLinks = document.getElementsByClassName('play_track');
for (var j = 0; j < favLinks.length; j++) {
var favLink = favLinks[j];
favLink.onclick = function (e) {
e.preventDefault();
xurl = this.type;
myFunc();
}
}
};
// Start the connection.
$.connection.hub.start().done(function () {
window.listFunc = function listFunc(name, url) {
console.log("List Sync 1");
// Call the Send method on the hub.
listSync.server.update_playlist(name, url);
console.log("List Sync 2");
}
});
});
The problem is it doesn't go into the function listSync.client.addNewItemToPage. Can someone please tell me why?

Javascript: cookie doesn't expire

I'm trying to expire a cookie right after it has set, due to cookielaw restrictions in UK and NL.
Here is the code I now use:
(function ($) {
$(document).ready(function(){
if (!CookieControl.maySendCookies()) {
var now = new Date();
var expirationDate = new Date();
expirationDate.setDate(now.getDate() - 7);
alert(getCookieValue('has_js'));
document.cookie='has_js=1;expires=' + expirationDate.toGMTString();
alert(getCookieValue('has_js'));
}
});
})(jQuery);
The getCookieValue function is a function from another document to check it the cookie is actually gone. Before I expire the cookie, the value is 1, as it should be. However, when I have expired the cookie by using document.cookie='has_js=1;expires=' + expirationDate.toGMTString(); I check the value again, and it is still there.
I seriously cannot figure out why it is not being removed. I cannot wait for sessions or whatever to expire, that is not according to NL law.
Anyone any suggestions?
CMS: Drupal / Domain: localhost
it may be related to path, i don't know, but you can use below scripts:
function getCookieValue(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
return unescape(c.substring(nameEQ.length, c.length));
}
return null;
}
function setCookieValue(name, value, days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = name + "=" + escape(value) + expires + "; path=/";
}
function delCookieValue(name) {
Set_Cookie(name, '', -1);
}
$(document).ready(function(){
if (!CookieControl.maySendCookies()) {
delCookieValue("has_js");
}
});

Auto save of form

I have form in ASP.NET 3.5. Where lot of data elements and where i have Save and Submit buttions. I need to auto save my form every 2 min. What is the best way to implement this kind of functionility in ASP.NET.
I struggled for awhile with the same problem. The trouble was that I didn't want to save into the usual database tables because that would've required validation (validating integers, currencies, dates, etc). And I didn't want to nag the user about that when they may be trying to leave.
What I finally came up with was a table called AjaxSavedData and making Ajax calls to populate it. AjaxSavedData is a permanent table in the database, but the data it contains tends to be temporary. In other words, it'll store the user's data temporarily until they actually complete the page and move onto the next one.
The table is composed of just a few columns:
AjaxSavedDataID - int:
Primary key.
UserID - int:
Identify the user (easy enough).
PageName - varchar(100):
Necessary if you're working with multiple pages.
ControlID - varchar(100):
I call this a ControlID, but it's really just the ClientID property that .NET exposes for all of the WebControls. So if for example txtEmail was inside a user control named Contact then the ClientID would be Contact_txtEmail.
Value - varchar(MAX):
The value the user entered for a given field or control.
DateChanged - datetime:
The date the value was added or modified.
Along with some custom controls, this system makes it easy for all of this to "just work." On our site, the ClientID of each textbox, dropdownlist, radiobuttonlist, etc is guaranteed to be unique and consistent for a given page. So I was able to write all of this so that the retrieval of the saved data works automatically. In other words, I don't have to wire-up this functionality every time I add some fields to a form.
This auto-saving functionality will be making its way into a very dynamic online business insurance application at techinsurance.com to make it a little more user friendly.
In case you're interested, here's the Javascript that allows auto-saving:
function getNewHTTPObject() {
var xmlhttp;
/** Special IE only code */
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end
#*/
/** Every other browser on the planet */
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
function AjaxSend(url, myfunction) {
var xmlHttp = getNewHTTPObject();
url = url + "&_did=" + Date();
xmlHttp.open("GET", url, true);
var requestTimer = setTimeout(function() { xmlHttp.abort(); }, 2000);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState != 4)
return;
var result = xmlHttp.responseText;
myfunction(result);
};
xmlHttp.send(null);
}
// Autosave functions
var SaveQueue = []; // contains id's to the DOM object where the value can be found
var SaveQueueID = []; // contains id's for binding references (not always the same)
function ArrayContains(arr, value) {
for (i = 0; i < arr.length; i++) {
if (arr[i] == value)
return true;
}
return false;
}
function GetShortTime() {
var a_p = "";
var d = new Date();
var curr_hour = d.getHours();
if (curr_hour < 12)
a_p = "AM";
else
a_p = "PM";
if (curr_hour == 0)
curr_hour = 12;
else if (curr_hour > 12)
curr_hour = curr_hour - 12;
var curr_min = d.getMinutes();
curr_min = curr_min + "";
if (curr_min.length == 1)
curr_min = "0" + curr_min;
return curr_hour + ":" + curr_min + " " + a_p;
}
function Saved(result) {
if (result == "OK") {
document.getElementById("divAutoSaved").innerHTML = "Application auto-saved at " + GetShortTime();
document.getElementById("divAutoSaved").style.display = "";
}
else {
document.getElementById("divAutoSaved").innerHTML = result;
document.getElementById("divAutoSaved").style.display = "";
}
}
function getQueryString(name, defaultValue) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == name) {
return pair[1];
}
}
return defaultValue;
}
function urlencode(str) {
return escape(str).replace(/\+/g, '%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/#/g, '%40');
}
function AutoSave() {
if (SaveQueue.length > 0) {
var url = "/AjaxAutoSave.aspx?step=" + getQueryString("step", "ContactInformation");
for (i = 0; i < SaveQueue.length; i++) {
switch (document.getElementById(SaveQueue[i]).type) {
case "radio":
if (document.getElementById(SaveQueue[i]).checked)
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
break;
case "checkbox":
if (document.getElementById(SaveQueue[i]).checked)
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
default:
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
}
}
SaveQueue = [];
SaveQueueID = [];
AjaxSend(url, Saved);
}
}
function AddToQueue(elem, id) {
if (id == null || id.length == 0)
id = elem.id;
if (!ArrayContains(SaveQueueID, id)) {
SaveQueue[SaveQueue.length] = elem.id;
SaveQueueID[SaveQueueID.length] = id;
}
}
Add this to your page to make this work:
window.setInterval("AutoSave()", 5000);
And to apply this to a Textbox, DropdownList, Listbox, or Checkbox you just need to add this attribute:
onchange="AddToQueue(this)"
...or this for a RadioButtonList or CheckBoxList:
onchange="AddToQueue(this, '" + this.ClientID + "')"
I'm sure this Javascript could be simplified quite a bit if you used JQuery so you might want to consider that. But in any case, AJAX is the thing to use. It's what Google uses to auto-save your email message in gmail, and the same thing is in blogger when you're writing a new post. So I took that concept and applied it to a huge ASP.NET application with hundreds of form elements and it all works beautifully.
Use the Timer class and the Tick method.

Resources