Logout of Facebook Through Linkbutton - asp.net

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.

Related

Ajax in asp web forms doesn't get called

I have many buttons and when the user clicks on one, I want it to update a label with ajax.
I implemented ajax in my template like so:
<form runat="server">
<asp:ScriptManager ID="ScriptManagerPull" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div runat="server" id="SiteContent">
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
The buttons are generated dynamically;
foreach (MyDTO myDTO in List) {
Button ButtonPull = new Button();
ButtonPull.Text = "Pull";
ButtonPull.ID = articleDTO.ArticleID.ToString();
ButtonPull.ControlStyle.CssClass = "btn btn-default";
ButtonPull.Click += new EventHandler(Pull_Click);
SiteContent.Controls.Add(ButtonPull);
}
Now the problem is that the event doesn't get called when a user clicks on button. This doesn't work:
protected void Pull_Click(object sender, EventArgs e) {
// Button button = sender as Button;
LabelTest.Text = "Cool";
}
How can I do that?
Thanks.
I am assuming you do not simply want to call the click event but perhaps pass some data from the client to the server via AJAX. The most straightforward way to do this, without ScriptManager, UpdatePantel and all that is like this. I have created one button and it has no click event handler on the server side. But it has one on the client side.
protected void Page_Load(object sender, EventArgs e)
{
Button ButtonPull = new Button();
ButtonPull.Text = "Pull";
ButtonPull.ID = "Button1";
ButtonPull.ControlStyle.CssClass = "btn btn-default";
this.Form.Controls.Add(ButtonPull);
// You can pass anything you want to the server. Here I am passing 1111
// You can pass things from the client side as well. Whole JSON objects as well
ButtonPull.OnClientClick = "callServer(1111);return false;"; // return false so button does not postback
}
I have also added this method to my page's code behind. This is a web method which receives an id as int and appends it to a string and returns that string to the client.
[WebMethod]
[ScriptMethod(UseHttpGet = true,
ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public static string GetStuffFromServer(int id)
{
return "Works like a charm! And id is " + id ;
}
And finally added this to my view. When the button is clicked on the client side, it will call this function and pass 1111 as we instructed it above when we created the button. Inside this function we are using jQuery ajax call to call the server method GetSuffFromServer. If all goes well the server will return and we will go into success here and alert the data returned from the server. Again, the server can return anything needed. And this method can send anything needed to the server.
<script>
function callServer(id) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "default.aspx/GetStuffFromServer?id=" + id,
success: function (data)
{
alert(data.d);
},
error: function (data) { alert(data);}
});
}
</script>
One last thing in App_Start folder's RouteConfig.cs file change this line:
settings.AutoRedirectMode = RedirectMode.Permanent;
to this:
settings.AutoRedirectMode = RedirectMode.Off;
This change is because I am using a friendly url when calling the web method: default.aspx/GetStuffFromServer?id=

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();
}
}
}

Unit Test log in redirected to correct url - Redirect of a button click event

I have a button click event which on successful login calls a private method, which in turn redirects the user to a page depending on the user's role. I am testing if a user of a particular role is redirected properly to the page. Please help me test this.
public void LogonUser(object sender, EventArgs e)
{
bool expired;
String userName;
UserAuthentication userAuth = new UserAuthentication();
userAuth.GetUserLoginInfo(UserID.Value, out userName, out expired);
string returnUrl = Request.QueryString[PhysicianProfileAppConstants.QueryStringKeys.ReturnUrl];
if (SuperUserControllerAttribute.IsSuperUserController(returnUrl)
&& !this.currentUserService.GetCurrentUser().IsSuperUser)
{
this.MissingSuperUserDiv.Visible = true;
return;
}
if (!CheckForceChangeFormVisibility(expired))
{
OnSuccessfullLogin();
}
}
private void OnSuccessfullLogin()
{
var userInfo = this.userEntityService.GetUserByLoginId(userId);
if (userInfo.IsSelfService == true)
{
if (userInfo.Physicians.Count() == 1)
{
var url = "/" + userInfo.Physicians.First().Id;
Response.Redirect(url);
}
}
Response.Redirect(Request.QueryString["ReturnUrl"] ?? FormsAuthentication.DefaultUrl);
}
Separate your domain logic from your UI - see e.g. http://martinfowler.com/eaaDev/uiArchs.html and http://msdn.microsoft.com/en-us/magazine/cc188690.aspx for a detailed discussion. With this approach, your button click will just call a method in another class, a "presenter", that's isolated from the UI details, that you can then easily unit test. To make sure your UI is wired up correctly to your presenter, you can use an automated integration test using something like Selenium, or use a manual smoke test, since this approach makes the UI code so simple it's unlikely to be broken once you have it working.

detect first page load jquery session

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
}
});

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