Session does not stay alive - c#

I am using the following article to keep my session alive in my asp.net application.
How to Keep Session Alive
But when I checked the session variable value using alert in javascript I didn't find anything. alert('<%=Session["Heartbeat"]%>');
Actually In my webpage there is no postback. All the work I am doing from Jquery Ajax. When there is any postback only then the solution of that article works.
But I want to keep my session alive without any postback.
Please help guys.....

alert('<%=Session["Heartbeat"]%>'); will not work without fully postback, because <%=Session["Heartbeat"]%> is a server-side code.
In order for Session to keep alive, all you need is just a simple Ajax call to server.
Easiest way to implement ASHX generic handler, and call it via Ajax. For example,
Ping.ashx
<%# WebHandler Language="C#" CodeBehind="Ping.ashx.cs" Class="PROJECT_NAMESPACE.Ping" %>
Ping.ashx.cs
public class Ping : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Ping");
}
public bool IsReusable { get { return false; }}
}

Please try this example :-
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function KeepSession() {
// A request to server
$.post("http://servername:port/appName/SessionCheck.aspx");
//now schedule this process to happen in some time interval, in this example its 1 min
setInterval(KeepSession, 60000);
}
// First time call of function
KeepSession();
</script>

Related

Check is aspx session expired via jquery ajax request

I use asp.net to manage the session state of my site. I also use jquery and $.ajax(...) for synchronous and asynchronous requests.
Normally, in asp.net if a users session times out, it can be detected via a full or partial post-back. However, suppose a partial or full-post-back does not occur because I am using jquery ajax calls to a static c# web method. Whats the best what to know if the session timeout?
i would create a javascript interval to make a ajax request from time to time, something like this:
<script>
$(document).ready(function () {
setInterval(function (){
$.ajax({
url: 'WebMethodhere',
type: 'GET',
success: function (result) {
if(result!='true')
{
//It means that the Session expired, so do somethig
}
}
})
},3000);
});
</script>
I used 3000ms in this example, but the time it's up to you.
And your webmethod could be really simple:
if(Session["WhateverSession"]==null)
{
return false;
}
else
{
return true;
}
There are couple of approaches to achieve it.
Approach #1: Create a generic handler and implement the IReadOnlySessionStateinterface to access session variables from this handler. Use a ajax get request and access this generic handler which provides whether session is active or not.
Approach #2: Decorate a public method of your page with [WebMethod] (using System.Web.Services) and access this method through ajax get request which provides whether session is active or not.
But all these approaches should be used just to check session is active or expired. But if the session is active, it'll renew your session - it may not be desirable. Please check that option also.
The easiest solution was to force a post back at certain intervals.
<meta http-equiv="refresh" content="1800">

Timer with javascript and C#

I need to create a timer in an ASP.NET web page.
I have tested some JavaScript code like:
window.onload = function WindowLoad(event) {
setTimeout(function () { alert("DoIT") }, 60000);
}
and it works like expected but when I replace the alert with a call to a C# function like:
window.onload = function WindowLoad(event) {
setTimeout(function () { <% doIt(); %> }, 60000);
}
the function works on the load of the page and not after the specified period.
<% doIt() %> runs during the server side process, not on client. If you want to do something on the server side you should create a webmethod and make a post to it.
Try this blog post, this should be what you are looking for: http://deebujacob.blogspot.com/2012/01/aspnet-ajax-web-method-call-using.html
It's like other people sad you can not call server side functions directly from javascript you have to make a request, that's is way good God gave as ajax :)

pattern for sending server side events to a webpage

I am wondering if there are any design patterns that allow server side events to be passed to a website?
The best I can think of is having some state on the server that is updated when the event is triggered, then maybe call back to the server via ajax every so often to check the state, and return what I need. Is this suitable? Is there a better way of doing this?
My application is written in ASP.NET MVC4.
There are a couple of ways of handling this depending on how you would like to tackle it and what technologies you would like to introduce to your stack.
Firstly, a periodic ajax call to a controller method on your server that will report the current state of the server is perfectly fine, for example: If a long running task is started on your server, returning some kind of indication of its progress via a controller method and polling that method periodically is perfectly reasonable.
The other method is to use a technology called SignalR, which essentially allows your server to call javascript functions on your client, I would certainly recommend looking into it.
Small example:
Server:
public class Chat : Hub
{
public void Send(string message)
{
// Call the addMessage method on all clients
Clients.All.addMessage(message);
}
}
Client:
<script src="http://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-1.0.0-alpha2.min.js" type="text/javascript"></script>
<!-- If this is an MVC project then use the following -->
<!-- <script src="~/signalr/hubs" type="text/javascript"></script> -->
<script src="/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.client.addMessage = function (message) {
$('#messages').append('<li>' + message + '</li>');
};
$("#broadcast").click(function () {
// Call the chat method on the server
chat.server.send($('#msg').val());
});
// Start the connection
$.connection.hub.start();
});
</script>
<div>
<input type="text" id="msg" />
<input type="button" id="broadcast" value="broadcast" />
<ul id="messages">
</ul>
</div>
The above example was taken from here:
https://github.com/SignalR/SignalR/wiki/QuickStart-Hubs
The SignalR website can be found here:
http://signalr.net/
I really love SignalR... it will probably provide the best experience for both you the programmer and the user too.
Hope this helps.
Sounds like you should be looking at the SignalR Project. This allows bi directional server communication.
You can wait for server event using long polling/comet it mean that you should send ajax request to server and ajax request not executed at once, request will wait for server event until timeout expired.
Alternatively you can to listening server's events using ajax call server events like this, without signalR framework, for example:
[SessionState(SessionStateBehavior.ReadOnly)]
public class HomeController : Controller
{
static readonly ManualResetEvent Starter = new ManualResetEvent(false);
public ActionResult Index()
{
return View();
}
public String RiseServerEvent()
{
Starter.Set();
return "";
}
public async Task<String> WaitForServerEvent()
{
string contents = null;
var result = Task.Factory.StartNew(() =>
{
var reg = ThreadPool.RegisterWaitForSingleObject
(Starter, (state, #out) =>
{
contents = DateTime.Now.TimeOfDay.ToString();
}, "Some Data", -1, true);
Starter.WaitOne(10000);
contents = DateTime.Now.TimeOfDay.ToString();
});
await result;
return contents;
}
}

Detect ajax submit

I need to run a specific javascript function only when the page is submitted using ajax.
I've tried the following:
ScriptManager.RegisterOnSubmitStatement(Page, Page.GetType(),
"scriptName", "MyFunction();");
But it seems to run during normal post-backs as well. I've also tried replacing the Page object with the UpdatePanel control but without any difference.
Is it perhaps possible inside the javascript function MyFunction() to detect if it is an ajax or normal submit?
You can utilize Sys.WebForm.PageRequestManager two events
1) add_initializeRequest --> When an ajax post back is initiated
2) add_endRequest --> when an ajax post back is finished.
PageRequestManager also provides a function "get_isInAsyncPostBack()" which tells that if page is still in process of an existing ajax postback.
Example:
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Only one async request at a time
if (prm.get_isInAsyncPostBack()) {
prm.abortPostBack();
}
//Call the function or process you want to perform on ajax request begin
});
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () {
//Call the fucntion or process you want to perform on ajax request end
});
Any question, feel free to ask
This code solved the problem. Thanks to #user1341446 for pointing me in the right direction.
Register the javascript function on submit:
ScriptManager.RegisterOnSubmitStatement(Page, Page.GetType(),
"scriptName", "MyFunction();");
Inside the function detect if ajax submit:
function MyFunction()
{
var isAjaxSubmit = false;
if (typeof (Sys) != "undefined")
isAjaxSubmit =
Sys.WebForms.PageRequestManager.getInstance()._postBackSettings.async;
}

Load .NET Resources Client-Side on each request

I have the following JavaScript snippet:
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(ajaxBeginRequest);
prm.add_endRequest(ajaxEndRequest);
function ajaxBeginRequest(sender, args) {
$.blockUI({ message: '<h1><img src="/images/ajax_loading.gif" /> <%= MyNameSpace.SomeWhereElse.Shared.RandomLoadingMessage() %></h1>' });
}
function ajaxEndRequest(sender, args) {
$.unblockUI();
}
</script>
Right now the C# line runs at page load and gives me one random message, but it is constant through the page execution until the page is refreshed. What I'd like it to do is give me a different message on each ajax Request
Any suggestions for this?
You can make a ajax call to a web service (called script service) to get the message on each invocation. See this article where it explains how to call script services using ASP.NET generated proxies as well as using jquery methods. You can use either method.

Categories