FacebookWebContext.Current is always null - c#

I am trying to edit some code written about two years ago.
Basically, it is Facebook connect, where users can register my website using Facebook application. My javascript code for Facebook connect is :
<div id="fb-root"></div>
<script src="http://connect.facebook.net/tr_TR/all.js"></script>
<script>
FB.init({ appId: '<%=Facebook.FacebookApplication.Current.AppId %>', status: true, cookie: true, xfbml: true });
FB.Event.subscribe('auth.login', function (response) {
window.location.href = UrlAmpReplace('<%=this.FacebookLoginURL %>');
});
FB.Event.subscribe('auth.logout', function (response) {
window.location.href = UrlAmpReplace('<%=this.FacebookLogoutURL %>');
});
</script>
If the user clicks the Facebook button, there a Facebook popup page appears and asks for authenticaion & authorication. After that one, user redirects my own registration page where I use Facebook.Web.dll as following :
var fb = new FacebookWebClient(FacebookWebContext.Current);
var result = (IDictionary<string, object>)fb.Get("/me");
this.smFacebookUserID = FacebookWebContext.Current.Session.UserId;
... do some action..
My problem is; FacebookWebContext.Current always returns null and I cannot process further.Do you have any idea what i am missing?

I found a solution for my problem, I think the problem is related with the FB js event I was using(auth.login).
So here is what I did :
Instead of the following js method :
FB.Event.subscribe('auth.login', function (response) {
window.location.href = UrlAmpReplace('<%=this.FacebookLoginURL %>');
});
I have used the following :
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
var accessToken = response.authResponse.accessToken;
window.location.href = 'myURL.aspx?token='+accessToken;
}
});
Then in my myURL.aspx, using accessToken from querystring, I can reach :
var client = new FacebookClient(accessToken);

Related

Passing parameter to window.location.href fails

I am trying to pass the currently logged in Azure AD user identity into the ajax method so it can be used as the input parameter in the window.location.href
#section Scripts {
<script type="text/javascript">
$("#button").click(function () {
var orderedQuantity = $("#txt").val();
var orderId = $("#orderId").val();
var data = {
orderId: orderId,
orderedQuantity: orderedQuantity,
}
var loggedUser = #User.Identity.Name;
$.ajax({
type: 'POST',
url: '#Url.Action("EditItem", "Orders")',
data: data,
dataType: "json",
success: function (result) {
if (result.status === "NotAvailable") {
$("#errorMessage").val("Enter a valid Quantity");
}
else {
var url = '#Url.Action("Index", "Orders")';
window.location.href = url + "?custEmail="+loggedUser;
}
},
error: function (error) {
alert(error);
}
});
});
</script>
I am storing the #User.Identity.Name; in the loggedUser variable and using it as the input paramter in the window.location.href = url + "?custEmail="+loggedUser;. It throws error like Uncaught SyntaxError: Invalid or unexpected token
Can anyone say if I am missing anything here.. I am passing the input paramter to the Orders page like this in other places and it fails in ajax method. I even tried to like below
var loggedUser = User.Identity.Name;
It even errors out like Uncaught ReferenceError: User is not defined
Can anyone suggest what is that I am missing here
Please add quotation marks like below:
var loggedUser = "#User.Identity.Name"; //or `#User.Identity.Name`

How to redirect after session timeout in MVC .Net?

I want to redirect my page after 2 minutes of inactivity, for this I am using the below code to ping the controller every 2.5 minutes and if the session has expired I redirect to the original login page:
`<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
var ReqTime =#Session.Timeout
ReqTime = ReqTime * 60 * 1000 + (.5 * 60 * 1000);
$(function () {
setInterval(CheckSession, ReqTime);
});
function CheckSession() {
$.post('#Url.Action("SessionInfo","Home")', null, function () {
console.log("Time");
});
}
</script>
Controller:
public ActionResult SessionInfo()
{
if (Session["LoginUserName"]==null)
{
return RedirectToAction("Index","Home");
}
}
This code does not re-direct to the Home/Index. Can you tell me where I'm going wrong?
Try using Javascript instead ,since redirect from server side need a post back
You can check session by controller and return a value to figure out if session end or not
function CheckSession() {
$.ajax({
type: "GET",
url: "#Url.Action("SessionInfo", "Home")"
}).done(function (data) {
if (data === true) {
window.location.href = "#Url.Action("Index", "Home")";
}
}).fail(function (e) {
alert('Error');
});
}
Controller
public JsonResult SessionInfo()
{
if (Session["LoginUserName"] == null)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json(false, JsonRequestBehavior.AllowGet);
}
This code for explaining
By making those session checking ajax request you just extend life-span of the user session.
If you would like to inform browser that user session has end I recommend to implement a SignalR service to have direct communication ( push capability ) between server and the browser ( realtime ).
Implement a SignalR service,
Create a session_end method in your global.asax file, in the session_end send a message to user browser that your session has end.
Just it

issue with login through facebook , email is null c# [duplicate]

I'm trying to get some basic information using Facebook api, but so far I only get the user's name and id. As in { name: "Juan Fuentes", id: "123456" }
I need to get mor einformation, like email, first name, last name and birthday
This is my js code
function facebookLogin() {
FB.login(function(response) {
var token = response.authResponse.accessToken;
var uid = response.authResponse.userID;
if (response.authResponse) {
FB.api('/me', 'get', { access_token: token }, function(response) {
console.log(response);
});
FB.api('/'+uid, 'get', { access_token: token }, function(response) {
console.log(response);
});
}
},
{ scope: 'public_profile' }
);
}
And this is the button that activates it
<a id="fb-login" href="#" onclick="facebookLogin()"></a>
You need to manually specify each field since Graph API v2.4:
https://developers.facebook.com/docs/apps/changelog#v2_4
https://developers.facebook.com/docs/javascript/reference/FB.api
Declarative Fields
To try to improve performance on mobile networks, Nodes and Edges in v2.4 requires that you explicitly request the field(s) you need for your GET requests. For example, GET /v2.4/me/feed no longer includes likes and comments by default, but GET /v2.4/me/feed?fields=comments,likes will return the data. For more details see the docs on how to request specific fields.
E.g.
FB.api('/me', 'get', { access_token: token, fields: 'id,name,gender' }, function(response) {
console.log(response);
});
It's also possible to use this syntax for data from public_profile scope (tested in Graph API v2.9):
FB.api('/me?fields=birthday,link,gender,age_range', function(response) {
console.log(response);
});
You can test the possible values online in Graph API Explorer, just click "Get Token" button:
https://developers.facebook.com/tools/explorer/?method=GET&path=me%3Ffields%3Dbirthday%2Clink%2Cgender%2Cage_range&version=v2.9
Here is the complete Script:
jQuery(document).ready(function () {
openLoginPopup();
})
function openLoginPopup() {
FB.getLoginStatus(function (response) {
if (response.status == 'connected') {
getCurrentUserInfo(response);
} else {
FB.login(function (response) {
if (response.authResponse) {
getCurrentUserInfo(response);
} else {
console.log('Auth cancelled.');
}
}, {scope: 'email'});
}
});
}
function getCurrentUserInfo() {
FB.api('/me?fields=id,email,first_name,last_name,name', function (userInfo) {
console.log(userInfo.name + ': ' + userInfo.email);
});
}
window.fbAsyncInit = function () {
FB.init({
// appId: 'xxxxxxxxxxxxxxxxxxxxx', //livemode
appId: 'xxxxxxxxxxxx', //testmode
cookie: true, // Enable cookies to allow the server to access the session.
xfbml: true, // Parse social plugins on this webpage.
version: 'v4.0' // Use this Graph API version for this call.
});
};
(function (d, s, id) { // Load the SDK asynchronously
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id))
return;
js = d.createElement(s);
js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
Thanks.
Note that email is not always returned by a call to the me api with email as field, even if scope email was requested and granted, if e.g. the user signed up with a phone number:
https://developers.facebook.com/docs/facebook-login/permissions#reference-email

Is it possible to always ask user even if already connected using Facebook Javascript SDK

I have MVC5 project written in C# and I use Facebook Javascript SDK, I'm wondering if it's possible to always ask user when login using Facebook.
Example scenario:
User A login to my site using Facebook, and he doesn't logout. His session expired from my site but his Facebook will still logged in. User B using same computer to login using Facebook, since user A didn't logout his Facebook, user B will automatically logged in with User A Facebook account, I need something like "Is this your Facebook account?" prompt before letting user login. Is this provided by Facebook? I'm looking around but no luck so far, and 'FB.login' can't be call after 'response.status' is already 'connected'.
my code :
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
$('#btnFBlogin').click(function () {
FB.api('/me', function (response) {
location.href = BASE_URL + 'Membership/LogInWithFacebook';
});
})
} else {
$('#btnFBlogin').click(function () {
FB.login(function (response) {
if (response.status === 'connected') {
FB.api('/me', function (response) {
location.href = BASE_URL + 'Membership/LogInWithFacebook';
});
}
}, { scope: 'email,user_birthday' });
})
}
});
Any help will be appreciated.
The flow should be like this:
You should have a customized login button (not the default fb-login button), not sure but I guess you are using the customised button only.
On its click, check if the user is already connected using FB.getLoginStatus().
If yes, logout the user from facebook using FB.logout() and then login the user using FB.login()
If not, login the user using FB.login().
Code
$('#btnFBlogin').click(function () {
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
FB.logout(function(response) {
Login();
});
}else{
Login();
}
});
});
function Login(){
FB.login(function (response) {
if (response.status === 'connected') {
FB.api('/me', function (response) {
location.href = BASE_URL + 'Membership/LogInWithFacebook';
});
}
}, { scope: 'email,user_birthday' });
}

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

I want to redirect from one page to another page in ASP.NET MVC 3.0 using JavaScript/jQuery/Ajax. On button click event I have written JavaScript code like below.
function foo(id)
{
$.post('/Branch/Details/' + id);
}
My controller code is like this:
public ViewResult Details(Guid id)
{
Branch branch = db.Branches.Single(b => b.Id == id);
return View(branch);
}
When I click on a button it is calling the Details action inside BranchController, but it doesn't return to the Details view.
I didn't get any error or exception. It's showing status 200 OK in Firebug. What is wrong in my code and how can I redirect to the Details view page?
You are not subscribing to any success callback in your $.post AJAX call. Meaning that the request is executed, but you do nothing with the results. If you want to do something useful with the results, try:
$.post('/Branch/Details/' + id, function(result) {
// Do something with the result like for example inject it into
// some placeholder and update the DOM.
// This obviously assumes that your controller action returns
// a partial view otherwise you will break your markup
});
On the other hand if you want to redirect, you absolutely do not need AJAX. You use AJAX only when you want to stay on the same page and update only a portion of it.
So if you only wanted to redirect the browser:
function foo(id) {
window.location.href = '/Branch/Details/' + id;
}
As a side note:
You should never be hardcoding urls like this. You should always be using url helpers when dealing with urls in an ASP.NET MVC application. So:
function foo(id) {
var url = '#Url.Action("Details", "Branch", new { id = "__id__" })';
window.location.href = url.replace('__id__', id);
}
This could be done by using a hidden variable in the view and then using that variable to post from the JavaScript code.
Here is my code in the view
#Html.Hidden("RedirectTo", Url.Action("ActionName", "ControllerName"));
Now you can use this in the JavaScript file as:
var url = $("#RedirectTo").val();
location.href = url;
It worked like a charm fro me. I hope it helps you too.
You can use:
window.location.href = '/Branch/Details/' + id;
But your Ajax code is incomplete without success or error functions.
// in the HTML code I used some razor
#Html.Hidden("RedirectTo", Url.Action("Action", "Controller"));
// now down in the script I do this
<script type="text/javascript">
var url = $("#RedirectTo").val();
$(document).ready(function () {
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Controller/Action',
success: function (result) {
if (result.UserFriendlyErrMsg === 'Some Message') {
// display a prompt
alert("Message: " + result.UserFriendlyErrMsg);
// redirect us to the new page
location.href = url;
}
$('#friendlyMsg').html(result.UserFriendlyErrMsg);
}
});
</script>
<script type="text/javascript">
function lnkLogout_Confirm()
{
var bResponse = confirm('Are you sure you want to exit?');
if (bResponse === true) {
////console.log("lnkLogout_Confirm clciked.");
var url = '#Url.Action("Login", "Login")';
window.location.href = url;
}
return bResponse;
}
</script>
check the code below this will be helpful for you:
<script type="text/javascript">
window.opener.location.href = '#Url.Action("Action", "EventstController")', window.close();
</script>

Categories