detect first page load jquery session - asp.net

Once the user logs in, i am displaying an alert to user based on a check on page load method. Now when the user navigates to other aspx pages and clicks on home again, I don’t want him to see the alert again. I want to achieve this with jquery and session variable. In a way I want to check first page load by jquery using a session variable.

I could do this with Session and RegisterStartupScript
User Login code
public void doLogin(string userName, string pwd)
{
// validate user
// check to see whether need to show alert
Session["ShowAlert"]=true;
Response.Redirect("Home.aspx");
}
in Home.aspx
Option 1
protected void Page_Load(object sender, EventArgs e)
{
if(Session["ShowAlert"]!=null)
{
String scriptName = "PopupScript";
if (!IsClientScriptBlockRegistered(csname1))
{
StringBuilder cstext = new StringBuilder();
cstext.Append("<script type=\"text/javascript\"> function showUserAlert() {");
cstext.Append("alert('message');} ");
cstext.Append("</script>");
RegisterStartupScript(cstext, cstext.ToString());
Session.Remove("ShowAlert");
}
}
}
Option 2:
Just define a javascript variable var in the page and use it in $(function(){...})
protected void Page_Load(object sender, EventArgs e)
{
if(Session["ShowAlert"]!=null)
{
String scriptName = "PopupScript";
if (!IsClientScriptBlockRegistered(csname1))
{
StringBuilder cstext = new StringBuilder();
cstext.Append("<script type=\"text/javascript\">");
cstext.Append("var showAlert=true;");
cstext.Append("</script>");
RegisterClientScriptBlock(cstext, cstext.ToString());
Session.Remove("ShowAlert");
}
}
}
JS
$(document).ready(function(){
if(showAlert)
{
alert('ShowMessage');
}
});

I made this exact feature a couple of weeks ago, but used a mySQL database instead of using sessions. If you are wanting to display the alert to the user only once EVER (or as close to forever as possible) or just once a week etc, then you should use cookies instead of sessions.
Otherwise, you can detect when the page has loaded simply with jQuery:
$().ready(function(){
if(!$.session.get("viewed_page")){
alert("some message");
$.session.set("viewed_page", true);
}
});

No need for session here.
You can use the session cookie itself.
$(function (){
if (document.cookie.indexOf("yourToken")>-1)
{}
else
{
// show the window , and set a cookie
}
});

Related

asp.net is there a way to trigger Session_End like event when cookie expires?

hope this is not a too basic of a question. I was wondering just like Session_end event is triggered when a session is expired, is there a way when using formsauthentication and a cookie expires then is there any event that is triggered? Or is there a possibility to find out when a cookie has expired (not when a new request is made) and then take custom actions?
Thanks in advance
I don't think there is a direct way to know this. We use to do this JavaScript hack at the master page. Please note that are setting the cookieExpiryTime manually.
var timeoutID,
cookieExpiryTime = 20 * 60 * 60; //20 minutes
function HandleSessionExpiry() {
timeoutID = window.setTimeout(function () {
window.location.href = 'http://www.example.com/Login.aspx?action=logout';
}, cookieExpiryTime);
}
window.onload = HandleSessionExpiry;
This works fine if the page is not making any AJAX request, but is there are AJAX requests, we need to write two functions on global ajaxStart and ajaxStop. ( Using jQuery here for this )
$(document).ajaxStart(function () {
window.clearTimeout(timeoutID);
});
$(document).ajaxStop(function () {
HandleSessionExpiry();
});
And the Page_Load of Login.aspx we did this.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if(! String.IsNullOrEmpty(Request.QueryString["!action"])
&& Request.QueryString["!action"] == "logout")
{
Session.Abandon();
}
}
}

asp.net send the response about 15 minute

i want when the client send to my web page request,my web page get the request and active timer and wait about 15 minute and check client so connect and response the json string.
my server code is:
string name, count;
protected void Page_Load(object sender, EventArgs e)
{
name = Request.QueryString["name"];
count = Request.QueryString["count"];
Timer1.Interval = 15000;
Timer1.Enabled = true;
}
protected void Timer1_Tick(object sender, EventArgs e)
{
if (Response.IsClientConnected)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
string json=jss.Serialize("در خواست شما تایید شد");
Response.Clear();
Response.Write(json);
Response.End();
}
else
{
Response.End();
}
}
how can i do this?
From your comment : " thanks,i want for example customer send my server a order and when the system manager accept the order,response to client:your order accepted"
You will need to include jQuery to do this bit.
As you have the name and count in the query string, which I take it will help you identify the customer (or change it to an order ID), then you can use the following on your .aspx page in a javascript block:
$(document).ready(function(){
setTimeout(function()
{
location.reload();
}, (15 * 60 * 1000)); // (that's 15 mins that I couldn't be bothered to work out...)
});
Your server side code could then be:
protected void Page_Load(object sender, EventArgs e)
{
var name = Request.QueryString["name"];
var count = Request.QueryString["count"];
if(OrderAccepted(name, count))
{
// display message to user
}
}
private bool OrderAccepted(string name, string count)
{
// do what you need to do to find out if the order is accepted.
}
You may also want to try and have the javascript only run if the order is not accepted so that it doesn't keep running. But a 15 min interval is a decent long period, and most people will close their browsers once they know the order is accepted.
Hope this helps.
You cannot achieve what you are trying to do through "only" server-side (compiled C#) code.
The problem is that you want the client to send a request every fifteen minutes - to get the latest JSON - but you are trying to tell the server to do that.
There are many better ways to accomplish what you are trying to do (ie, better than a fifteen-minute timer) but here is one way you can achieve that through JavaScript:
First, expose your server's API call (the call that gets the JSON).
Then, in a script node on the client (ie in a script tag in the HTML you send down), define the following function:
function refreshDataAndUpdatePage() {
$.ajax({
url: 'your/url/to/the/action',
success: function (data) {
// use data JSON to update page.
// then, call this function again recursively after a timeout of 15 minutes = 900 s = 900,000 ms
setTimeout(refreshDataAndUpdatePage, 900000);
}
}
And of course, call it somewhere.

Logout of Facebook Through Linkbutton

I have been looking through quite a few posts on StackOverflow and on the internet on being able to log a user out of Facebook through an ASP.NET LinkButton.
I have tried implementing solutions from the following posts:
Facebook Logout button in asp.net web application
How to logout from facebook connect in asp.net?
Facebook Logout Confusion
Code
ASPX Page
<asp:LinkButton ID="LogoutButton" CssClass="log-out fb" OnClick="LogoutButton_Click" runat="server">Logout</asp:LinkButton>
JavaScript
$(".log-out.fb").click(function () {
FB.logout(function (response) {
//Logged out
FB.Auth.setAuthResponse(null, 'unknown');
});
});
HTML Output
<a id="MainContent_LogoutButton" class="log-out fb" href="javascript:__doPostBack('ctl00$MainContent$LogoutButton','')" style="width: 66px; ">Logout</a>
I definitely know that the jQuery click event is getting fired when debugging via Firebug. The jQuery code works fine when used in conjunction with a standard HTML anchor, so there is no reason for it not to work on a ASP.NET LinkButton.
Any help would be appreciated.
Thanks for all your help. But I managed to find a way to log out a user by using the following link:
https://www.facebook.com/logout.php?next=YOUR_URL&access_token=ACCESS_TOKEN
I created a callback page similar to the one from this article. Once I received the "access token", I managed to log the user out.
Here is my code for my callback page:
protected void Page_Load(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(Request["code"]) && !Page.IsPostBack)
{
FacebookCallback();
}
}
private void FacebookCallback()
{
var client = new RestClient { Authority = "https://graph.facebook.com/oauth/" };
var request = new RestRequest { Path = "access_token" };
request.AddParameter("client_id", ConfigurationManager.AppSettings["facebook.appid"]);
request.AddParameter("redirect_uri", ConfigurationManager.AppSettings["facebook.logout.callbackurl"]);
request.AddParameter("client_secret", ConfigurationManager.AppSettings["facebook.appsecret"]);
request.AddParameter("code", Request["code"]);
RestResponse response = client.Request(request);
// A little helper to parse the querystrings.
StringDictionary result = QueryStringHelper.ParseQueryString(response.Content);
string aToken = result["access_token"];
LogUserOut(aToken);
}
private void LogUserOut(string sToken)
{
string url = String.Format("https://www.facebook.com/logout.php?next=http://{0}/Default.aspx&access_token={1}", ConfigurationManager.AppSettings["site.url"], sToken);
Response.Redirect(url);
}
I hope this helps others if they encounter the same issue.

Calling a non static method in Server Side by a Client Side Function

I can get an object from the server side by using static receive callbackresult methods from server side.
But I want to run a non-static method in my page which populates an ajax accordion by calling a client side function.
The object I am calling from server side is a complex object which I can't use in client side if I get it by callbackresults.
Is there any other solution that I can run a non static method in an aspx file by a client side control ?
Codes I am using so far ...
function ReceiveServerData(arg, context) {
//Message.innerText = "Date from server: " + arg;
}
#region ICallbackEventHandler Members
public void RaiseCallbackEvent(String eventArgument)
{
// Processes a callback event on the server using the event
// argument from the client.
Insert(); // this is running, but doesnt work !
//printAlternativesFromAirport(eventArgument);
}
public string GetCallbackResult()
{
// Returns the results of a callback event to the client.
return null;
}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cm = Page.ClientScript;
String cbReference = cm.GetCallbackEventReference(this, "arg",
"ReceiveServerData", "");
String callbackScript = "function CallServer(arg, context) {" +
cbReference + "; }";
cm.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
}
yes, you need to create a handler that will create the entire context needed for the page, which will run a full page life cycle ect, and is more recommended when you want to retrieve something like a user control or something big.
public void ProcessRequest(HttpContext context)
{
context.Response.Write(RenderView("~/_controltemplates/15/myDir/Templates/myUC.ascx"));
}
public static string RenderView(string path)
{
try
{
Page pageHolder = new Page();
UserControl viewControl = (UserControl)pageHolder.LoadControl(path);
pageHolder.Controls.Add(viewControl);
StringWriter result = new StringWriter();
Log.Application.Debug(LOGPREFIX + "RenderView before Execute");
HttpContext.Current.Server.Execute(pageHolder, result, true);
return result.ToString();
}
catch (Exception ex)
{
Log.Application.ErrorException(LOGPREFIX, ex);
throw;
}
}
but i think that it is not what you need, instead i would advice you to make an entity (class) to handle that insert function that will not need any httpContext and run it from a simple handler.
another solution you might need, since maybe you do need all the postback info but do not want to make a full postback is to use AjaxPanel or even clear the Response and send "OK" instead.

Asp.net Webform Display Alert and redirect

I'm currently stuck. I have a webform with a button that registers or saves a record.
What i'd like to is have it display a javascript alert and then redirect to a page.
Here is the code i am using
protected void Save(..)
{
// Do save stuff
DisplayAlert("The changes were saved Successfully");
Response.Redirect("Default.aspx");
}
This code just redirects without giving the prompt Saved Successfully.
Here is my DisplayAlert Code
protected virtual void DisplayAlert(string message)
{
ClientScript.RegisterStartupScript(
this.GetType(),
Guid.NewGuid().ToString(),
string.Format("alert('{0}');", message.Replace("'", #"\'").Replace("\n", "\\n").Replace("\r", "\\r")),
true
);
}
Can anyone help me find a solution to this?
Thanks
You can't do a Response.Redirect because your javascript alert will never get displayed. Better to have your javascript code actually do a windows.location.href='default.aspx' to do the redirection after the alert is displayed. Something like this:
protected virtual void DisplayAlert(string message)
{
ClientScript.RegisterStartupScript(
this.GetType(),
Guid.NewGuid().ToString(),
string.Format("alert('{0}');window.location.href = 'default.aspx'",
message.Replace("'", #"\'").Replace("\n", "\\n").Replace("\r", "\\r")),
true);
}
The DisplayAlert method adds the client script to the currently executing page request. When you call Response.Redirect, ASP.NET issues a HTTP 301 redirect to the browser, therefore starting a new page request where the registered client script no longer exists.
Since your code is executing on the server-side, there is no way to display the alert client-side and perform the redirect.
Also, displaying a JavaScript alert box can be confusing to a user's mental workflow, an inline message would be much more preferable. Perhaps you could add the message to the Session and display this on the Default.aspx page request.
protected void Save(..)
{
// Do save stuff
Session["StatusMessage"] = "The changes were saved Successfully";
Response.Redirect("Default.aspx");
}
Then in Default.aspx.cs code behind (or a common base page class so this can happen on any page, or even the master page):
protected void Page_Load(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty((string)Session["StatusMessage"]))
{
string message = (string)Session["StatusMessage"];
// Clear the session variable
Session["StatusMessage"] = null;
// Enable some control to display the message (control is likely on the master page)
Label messageLabel = (Label)FindControl("MessageLabel");
messageLabel.Visible = true;
messageLabel.Text = message;
}
}
The code isn't tested but should point you in the right direction
This works perfect:
string url = "home.aspx";
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Saved Sucessfully.');window.location.href = '" + url + "';",true);
protected void Save(..)
{
// Do save stuff
ShowMessageBox();
}
private void ShowMessageBox()
{
string sJavaScript = "<script language=javascript>\n";
sJavaScript += "var agree;\n";
sJavaScript += "agree = confirm('Do you want to continue?.');\n";
sJavaScript += "if(agree)\n";
sJavaScript += "window.location = \"http://google.com\";\n";
sJavaScript += "</script>";
Response.Write(sJavaScript);
}

Resources