I am working in C#.Net. I want to kill the session values when the browser is closed. (i.e) In my application, i want to display online visitors count. If the user clicks logout button means, it works fine. rather than if he close the browser, the session value not cleared.
if the browser close is done, the session value should be killed....
My Global.ascx code...
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
Application["OnlineUsers"] = 0;
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
Application.Lock();
Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
Application.Lock();
Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
Application.UnLock();
}
My Home.aspx code...
Visitors online: <%= Application["OnlineUsers"].ToString() %>
If i run my application in IE, the online count will be 1. If i runs in Firefox, the online count should be incresed to 2. If i close the Firefox browser, the count in IE should be changed to 1.
This is my Requirement....
The Http protocol is a connectionless one, so unless you are planning to use websockets, the only two ways to kill the user session should be by a direct request by the user (i.e. pressing a logout link), or a session timeout.
You should not rely on the browser to kill the session. The user can forget to close the browser, or he may have javascript disabled. Instead, provide means to the user to close the session and set your session timeout to a reasonable value adjusted to your users activity.
if (!Session.IsNewSession && Request.UrlReferrer == null)
{
}
if we type or paste url, this code will redirect to login page
You could trigger javascript, like this:
<SCRIPT language="JavaScript">
<!--
function loadOut()
{
window.location="http://www.yoursite.com/loadout.php?sid=235346317";
}
//-->
</SCRIPT>
<body onBeforeUnload="loadOut()">
Your javascript could perform an AJAX call, or whatever.
This will also work, I think, when the user leaves your site.
Is this what you were searching for?
How about this:
<body onunload="doUnload()">
Then the javascript, would be something like:
function doUnload()
{
$.post("unset_session.php", { action: "unset" },
function(data) {
// Callback if wanted
});
}
Then in your php, just unset the session data, or destroy the session
<?php
if ($_POST['action'] == 'unset')
{
// Unset or Destroy the Session
session_destroy();
}
?>
I did this in my .net app for IE, when user click browser right up corner X button, I want to force user logout. Hope that helps.
In master page:
<script type="text/javascript">
window.onbeforeunload = function (e) {
//alert("Killing the session on the server!!");
if ((window.event.clientX < 0) || (window.event.clientY < 0)) {
document.getElementById('<%= FORCE_LOGOUT_BTN.ClientID %>').click();
}
}
</script>
In .net site.master page:
<asp:Button ID="FORCE_LOGOUT_BTN" runat="server" CssClass="noShow"OnClick="ForceLogOut" Width="10px" />
Have to use CssClass, set Visible=false not working, since object will become null. Css noShow is: visibility:hidden;
In site.master.cs
public void ForceLogOut(object sender, EventArgs e)
{
FormsAuthentication.SignOut(); // since I use Form authentication
Session.Abandon();
}
Related
I have 2 pages home.aspx and admin.aspx
After successfully logging into admin.aspx when i click back button of browser, it does redirect to home.aspx but that i don't want.
I am checking session variable persistence on home.aspx but for some reason its not working!!
Here's the code
home.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (Session["aname"] != null)//should work as session will not be null!
{
Response.Redirect("admin.aspx");
}
} //.....some code..after this
if (dt.Rows.Count != 0)
{
Session["aname"] = TextBox11.Text;
Response.Redirect("admin.aspx");
}
admin.aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["aname"] == null)
{
Response.Redirect("home.aspx");
}
} //some code after this..
protected void logoutbutton_Click(object sender, EventArgs e)
{
Session["aname"] = null;
Session.Abandon();
Session.Clear();
Response.Redirect("home.aspx");
}
NOTE:(things working fine)
1.login working sucessfully
2.logout working sucessfully
3.back button is disabled once loggedout(not going on admin.aspx)
Issue:
When logged in i.e. on admin.aspx ,on clicking back button it redirects to home.aspx which i don't want. i expect it to remain on same admin.aspx
ok.. finally trying all your solutions..this code worked on adding in my masterpage (in head tags)
<script type = "text/javascript" >
function preventBack(){window.history.forward();}
setTimeout("preventBack()", 0);
window.onunload=function(){null};
</script>
full details on this page
You can push the Window History forward to prevent the back button. This has work for me in most cases. Include this JavaScript on your Admin.aspx page.
$(function() {
window.history.forward();
});
Ok, I want to allow user to be able to use the page only when browser is Chrome or IE8-9.
I doing so from code behind as you can see. And also trying to set viability of main div to none.
protected void Page_Load(object sender, EventArgs e)
{
System.Web.HttpBrowserCapabilities browser = Request.Browser;
if (browser.Type.ToString().ToLower().StartsWith("ie"))
{
if (Convert.ToDecimal(browser.Version) < 8 || Convert.ToDecimal(browser.Version) > 9)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "pop", "<script>alert('Your browser is not supported. Please use Chrome or IE7,IE8,IE9');</script>", false);
pagecontainer.Attributes["style"] = "visible:none";
return;
}
}
else if (!browser.Type.ToString().ToLower().StartsWith("chrome"))
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "pop", "<script>alert('Your browser is not supported. Please use Chrome or IE7,IE8,IE9');}</script>", false);
pagecontainer.Attributes["style"] = "visible:none";
return;
}
//blah blah
}
<div id="pagecontainer" runat="server" >Page Content Goes Here</div>
But it does not seem to be hiding the div.
I know I can always redirect user to a warning page or something but lets say I do not want to do so. What are my alternatives?
remove this line:
pagecontainer.Attributes["style"] = "visible:none";
and use this one instead:
pagecontainer.Attributes.Add("style", "display:none;");
I am developing a Web app for conducting a Online examination. I want to stop the contestants from refreshing the page in the browser. If they do I want to navigate them to a page which says they are disqualified. How can I implement this?
The following code snippet detects 'Refresh' in page_load function
bool IsPageRefresh = false;
protected void Page_Load(object sender, EventArgs e)
{
//this section of code checks if the page postback is due to genuine submit by user or by pressing "refresh"
if (!IsPostBack)
{
ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
{
IsPageRefresh = true;
}
Session["SessionId"] = System.Guid.NewGuid().ToString();
ViewState["ViewStateId"] = Session["SessionId"].ToString();
}
}
You can then use the 'IsPageRefresh' boolean flag in the code-behind to determine if it's a postback due to genuine User submit action or by browser 'Refresh'.
I have some trouble understanding this one so here it is.
I'm trying to set a cookie and display the value on the page using ASP.NET + C#.
here's my code:
protected void lbChangeToSmall_Click(object sender, EventArgs e)
{
Response.Cookies["fontSize"].Value = "small";
}
and
<asp:LinkButton runat="server" id="lbChangeToSmall" Text="A" CssClass="txt-sm" OnClick="lbChangeToSmall_Click"></asp:LinkButton>
And finally
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Write( Request.Cookies["fontSize"].Value);
}
}
When I click on the button, nothing is displayed on the page, but the cookie is actually set. If I refresh the page, the cookie displays.
So it seems that the cookie is set correctly but the application is not able to read it right away.
I tried to get rid of the if(postBack):
protected void Page_Load(object sender, EventArgs e)
{
Response.Write( Request.Cookies["virgilFontSize"].Value);
}
but it didn't change a thing.
What am I doing wrong?
Thanks!
The lblChangeToSmall_Click event is fired after the Page_Load event. Therefore the cookie write won't be available on the Request until the subsequent postback.
It will be avaialable on the client immediately though.
The first time, the request has no cookies (yet); it will only have them the second time around, after the response has set them. So your code has to deal with the possibility that Request.Cookies just may not have a "fontSize" entry, and provide the proper default when that is the case. For example:
HttpCookie cookie = Request.Cookies.Get("fontSize");
// Check if cookie exists in the current request.
if (cookie == null)
{
Response.Write( "Defaulting to 'small'.");
}
else
{
Response.Write( Request.Cookies["fontSize"].Value);
)
I have a problem: when i call a Response.Redirect() from the MasterPage it doesn't work.
Well, debugging i can see that until the Pre_Render() method the target page is loaded, but then is rendered the previous page.
Here's some code to better explain:
(from MasterPageMain.master.cs)
protected void Page_Init(object sender, EventArgs e)
{
string m_QueryStringValue = Request.QueryString.Get("action");
if ((!string.IsNullOrEmpty(m_QueryStringValue)) && (m_QueryStringValue.ToLower() == "send"))
{
if (Session["to"] != null && Session["to"] is List<string>) this.SendPageByMail();
else
{
Session.Add("AddressToSend", Request.RawUrl);
Response.Redirect("~/chooseRecipients.aspx");
}
}
}
I have a javascript that adds the querystring adding "action=send" when i click on the Send button.
If i am on page "~/somethingInterestingToSend()" -for example- i want to get on the recipient selection page, but when i click the Send button i see always the same page.
What coul be the mistake?
If you want to redirect not logged in users to a login-page you should check the Request.RawUrl() like this:
string strURL=Request.RawUrl.ToUpper();
if (!strURL.Contains("LOGIN.ASPX") && !strURL.Contains("LOGOUT.ASPX")
&& !strURL.Contains("ERROR.ASPX") && !strURL.Contains("UNDERCONSTRUCTION.ASPX"))
{
Response.Redirect("~/Login.aspx", false);
}
All other sites will be redirected.
I am not sure I fully understand your description of the problem, but here are a few things to consider:
You mention a send button. If this is an , clicking it fires a javascript postback to the server. This postback is to the original URL. I'm not sure what you are modifying with Javascript, but I don't think it would change the postback URL (and querystring).
If you need to perform logic to redirect you might want to execute in the button click event on the server.
If you don't need to execute any logic on the server, you could to the redirect with javascript:
window.location = "chooseRecipients.aspx";
Can't test this theory (running from memory at the moment), but give this a shot:
(sorry, cleaned up the code a bit as well)
protected void Page_Init(object sender, EventArgs e)
{
string m_QueryStringValue = Request.QueryString.Get("action") ?? "";
if (m_QueryStringValue.ToLower() == "send")
{
if ( (Session["to"] as List<string>) != null)
{
this.SendPageByMail();
}
else
{
Session.Add("AddressToSend", Request.RawUrl);
Response.Redirect("~/chooseRecipients.aspx", false);
HttpContext.Current.ApplicationInstance.CompleteRequest()
}
}
}
I don't know if its the root of your problem but I'd change 2 things. I'd change your code to:
Response.Redirect("~/chooseRecipients.aspx", false);
and move the logic to PageLoad