Facebook C# SDK, problems getting user email - datetime

I'm using Facebook C# SDK and got a sample on how to set up a login and get some user information to register im my website. However, I stuck in email information. It's always null.
I've checked some posts related in here, but none solve my problem. All the information I need is coming right, only email and birthday is missing.
My code in shtml partial page is like this:
<div id="fb-root"></div>
<fb:login-button id="fblogin" onlogin="window.open('http://' + location.host + '/Facebook/LogOn', '_self')" perms='email'></fb:login-button>
<script>
window.fbAsyncInit = function () {
FB.init({
appId: '#Facebook.FacebookApplication.Current.AppId',
cookie: true,
xfbml: true,
oauth: true
});
function facebooklogin() {
FB.login(function (response) {
if (response.authResponse) {
// user authorized
//window.location.reload();
window.open("http://" + location.host + "/Facebook/LogOn", "_self")
} else {
// user cancelled
}
}, { scope: '#ViewBag.ExtendedPermissions' });
};
$(function () {
// make the button is only enabled after the facebook js sdk has been loaded.
$('#fblogin').attr('disabled', false).click(facebooklogin);
});
};
(function () {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
} ());
</script>
And my code in Facebook Controller:
public ActionResult LogOn()
{
var fbWebContext = new FacebookWebContext(); // or FacebookWebContext.Current;
if (fbWebContext.IsAuthorized())
{
var fb = new FacebookWebClient();
dynamic me = fb.Get("me");
//Creating new User with Facebook credentials
var id = 0;
var nickname = me.first_name;
var password = "";
var email = me.email;
var picture = string.Format("http://graph.facebok.com/{0}/picture?type=large", me.id);
var thumbnail = string.Format("http://graph.facebok.com/{0}/picture?type=normal", me.id);
var fullName = me.name;
var gender = "";
if (me.gender == "male") gender = "Masculino";
if (me.gender == "female") gender = "Feminino";
var birthdate = Convert.ToDateTime(me.birthday);
//Does the user already exist?
if (DAUser.UserAlreadyExists(email))
{
ViewBag.Message = "O seu e-mail já foi cadastrado em nosso site. Por favor, cadastre outro e-mail.";
return View("~/Views/Shared/Erro.cshtml");
}
else
{
id = DAUser.Create(nickname, email, password, "facebook");
}
//Updating created user information
User user = db.User.Find(id);
TryUpdateModel(user);
user.Picture = picture;
user.Thumbnail = thumbnail;
user.Nickname = nickname;
user.FullName = fullName;
user.Gender = gender;
if (!String.IsNullOrEmpty(birthdate))
{
user.Birthdate = Convert.ToDateTime(birthdate);
}
db.SaveChanges();
Session["loginType"] = "Facebook";
return RedirectToAction("Mural", "Home");
}
else
{
ViewBag.Message = "Não foi possível completar o seu login via Facebook.";
return View("~/Views/Shared/Erro.cshtml");
}
}
If I put these lines, as shown in the sample:
[FacebookAuthorize(Permissions = ExtendedPermissions)]
if (fbWebContext.IsAuthorized(ExtendedPermissions.Split(',')))
My app stop works.
Anybody has a solution? O another sample codes to get authorized to request email and birthday?
Edit
The problem was this line:
}, { scope: '#ViewBag.ExtendedPermissions' });
In my App should be:
}, { scope: 'email,user_birthday,user_hometown' }); //alter to get permission to access user data
I didn't set a scope (perms) to facebook access... but now, I have another question.
My culture DateTime is dd/MM/yyyy and Facebook birthday is set up as MM/dd/yyyy, I tried this:
var birthdate = DateTime.Parse(me.birthday, CultureInfo.CreateSpecificCulture("pt-BR"));
Cuz my culture in Brazilian, but I still get DateTime error:
String was not recognized as a valid DateTime.
Anyone know how to solve that?

This line make everything works fine with Facebook Birthday
var birthdate = DateTime.ParseExact(me.birthday, "MM/dd/yyyy", CultureInfo.InvariantCulture);

Related

Fetch LinkedIn Data using JS givs error "message": "Unknown authentication scheme"

I have followed this exemple https://www.c-sharpcorner.com/blogs/fetch-linkedin-data-using-javascript to fetch data like updates/post from a company specific .
I am getting the following error.
{
"errorCode": 0,
"message": "Unknown authentication scheme",
"requestId": "MXRLWYPBNU",
"status": 401,
"timestamp": 1539160527230
}
The company have added my profile as a company admin so I should have the authentication to get the data.
What am I doing wrong ?
Alright here is my code:`
<script type="text/javascript" src="https://platform.linkedin.com/in.js">
api_key: 8616po0krrhh2k
scope: r_basicprofile r_emailaddress
onLoad: onLinkedInLoad,
</script>
$(document).ajaxSend(function (event, jqxhr, settings) {
if (settings.url == "https://www.linkedin.com/uas/oauth/authenticate") {
settings.url = "https://www.linkedin.com/uas/oauth/authorize"
}});
function onLinkedInLoad() {
IN.Event.on(IN, "auth", onLinkedInAuth());}
function onSuccess(data) {
console.log(data); }
function onError(error) {
console.log(error);
}
function onLinkedInAuth() {
var cpnyID = 86104; //the Company ID for which we want updates
IN.API.Raw("/companies/" + cpnyID + "/updates?event-type=status-
update&start=0&count=10&format=json").result(displayCompanyUpdates);
console.log("After auth");
}
function displayCompanyUpdates(result) {
var div = document.getElementById("displayUpdates");
var el = "<ul>";
var resValues = result.values[0];
for (var i in resValues) {
var share = resValues[i].updateContent.companyStatusUpdate.share;
var isContent = share.content;
var isTitled = isContent,
isLinked = isContent,
isDescription = isContent,
isThumbnail = isContent,
isComment = isContent;
if (isTitled) {
var title = isContent.title;
} else {
var title = "News headline";
}
var comment = share.comment;
if (isLinked) {
var link = isContent.shortenedUrl;
} else {
var link = "#";
}
if (isDescription) {
var description = isContent.description;
} else {
var description = "No description";
}
if (share) {
var content = "< a target = '_blank' href = " + link + " > " + comment + "
</a><br>";
el += "<li><div>" + content + "</div></li>";
}
console.log(share);
}
el += "</ul>";
document.getElementById("displayUpdates").innerHTML = el;
}
<div id="displayUpdates"></div>`
well one obvious problem i see with your code, is that you added the wrong scopes for the call you want to make.
for company API calls you need the following scope : rw_company_admin

Using firebase as a Web client for a login system in app & when tested it I add username & password for a user and when I pressed login erver error

var ROOT_URL = "https://exampleapp.firebaseio.com/"; // Change to your Firebase App
var FIREBASE_CREDENTIAL = "yourAppSecret"; // Change to your Firebase App Secret
var firebase = {
register : function (email, password, callback) {
var emailReplace = email.replace(/\./g, ",");
var beginRegister = function () {
requestObj = { "email" : email, "password" : password };
var requestJSON = JSON.stringify(requestObj);
var wcRegister = new SMF.Net.WebClient(
{ URL : ROOT_URL + "Users/" + emailReplace + ".json?auth=" + FIREBASE_CREDENTIAL,
httpMethod : "POST",
requestHeaders : ['Content-Type:application/json', 'X-HTTP-Method-Override:PATCH'],
requestBody : requestJSON,
onSyndicationSuccess : function (e) {
//Registered, do something callback();
}, onServerError : function (e) {
//Do something
}
});
wcRegister.run(true);
};
var isTaken = new SMF.Net.WebClient({ URL : ROOT_URL + "Users/" + emailReplace + ".json?auth=" + FIREBASE_CREDENTIAL,
httpMethod : "GET",
requestHeaders : ["Content-Type:application/json"],
onSyndicationSuccess : function (e) {
var response = JSON.parse(isTaken.responseText);
if (response !== null) {
//Email is taken, do something
} else {
beginRegister();
//Email is not taken, continue
}
},
onServerError : function (e) {
//Server Error, do something
}
});
isTaken.run(true);
},
login : function (email, password, callback) {
var emailReplace = email.replace(/\./g, "%2C");
var wcLogin = new SMF.Net.WebClient({ URL : ROOT_URL + "Users/" + emailReplace + ".json?auth=" + FIREBASE_CREDENTIAL,
httpMethod : "GET",
requestHeaders : ["Content-Type:application/json"],
onSyndicationSuccess : function (e) {
var responseText = JSON.parse(wcLogin.responseText);
if (responseText) {
if (password === responseText.password) {
//User logged, do something
callback();
} else {
//Password is wrong, do something
}
} else {
//User doesn't exist, do something
}
},
onServerError : function (e) {
//Server error, do something
}
});
wcLogin.run(true);
}
}
This is the code I used to create a Web client and the software I am using is Smartface App Studio. Using firebase as a Web client for a login system in app & when tested it I add username & password for a user and when I pressed login it said server error.Thank you☺😊😀

template rendered is not working properly in meteor JS

template rendered is not working
when user successfully login in to system i redirect to profile page that time data is not get but if i visit another page and come back to profile page that time it is working fine. also when i reload page that time also it is not working
here is code
Template.profile.rendered = function(){
var user_email = {};
user_email.mail = Session.get('email');
var imgName = Session.get('image');
Meteor.call("imgSend",imgName,function(error, result){
$('.user_profile_image').attr("src",result)
});
Meteor.call("getLinkMeta",user_email,function(error, result){
var link_all_info = [];
var walldata = [];
var total = result.length;
var processed = 0;
var t = result.forEach(function (entry){
var link_info = {};
link_info.link_id = entry._id;
Meteor.call("getCommentList",link_info, function (error, res){
if(error){
console.log("e");
}else{
entry.comments = res;
}
processed++
if(processed == total){
//walldata=result;
}
});
});
Template.profile.walldata = function(){
return result;
};
//return result;
});
}
Router.route('profile', {
path: '/profile',
data: function() {
/* Meteor.subscribe("Users");
Meteor.subscribe("Link");
Meteor.subscribe("Linkfav");
Meteor.subscribe("LinkLike");
Meteor.subscribe("LinkComment"); */
$("body").removeClass('home');
this.render('profile');
setTimeout(function(){
$('#username').html(Session.get('first_name'));
$('#profile_username').html(Session.get('first_name'));
$('#setting_name').val(Session.get('first_name'));
$('#setting_username').val(Session.get('first_name'));
$('#setting_email').val(Session.get('email'));
$('#user_id').val(Session.get('id'));
$('.setting_day').val(Session.get('day'));
$('.setting_month').val(Session.get('month'));
$('.setting_year').val(Session.get('year'));
if(Session.get('image')!= ''){
$('.user_profile_image').attr("src",Session.get('image'));
}
if(Session.get('gender') == 0){
$('#user_gender').html('Male');
}else{
$('#user_gender').html('Female');
}
$('#day').html(Session.get('day'));
$('#month').html(Session.get('month'));
$('#year').html(Session.get('year'));
},100);
},onBeforeAction:function(){
if(Session.get('email')){
this.next();
}else {
//this.next();
this.redirect('/');
}
}
});
When you refresh/reload the page Session values are get undefined. You can get the current user email using meteor.user(). You just have to replace you session.get('email') like this.
var user_email = {};
user_email.mail = Meteor.user().emails[0].address;
I hope that is what you are looking for.

Keep login infomation after login in sencha touch 2

I make an small web-application using Sencha touch 2. I have already done with login page. The purpose of second page is get current User session who post Products. This is login page
onSignInCommand: function (view, username, password) {
var me = this;
var loginView = this.getLoginView();
if (username.length == 0 || password.length == 0) {
loginView.showSignInMessage("Please enter your username and password.");
return;
}
loginView.setMasked({
xtype: "loadmask",
message:"Signing in..."
});
//Set ajax
Ext.Ajax.request({
url: "./ajax/Account.ashx",
params: {
type: "login",
username: username,
password: password
},
success: function (response) {
var loginResponse = Ext.JSON.decode(response.responseText);
if (loginResponse.success) {
me.sessionToken = loginResponse.sessionToken;
me.showSignInSuccess();
} else {
me.sessionToken = null;
me.showSignInFailedMessage(loginResponse.message);
}
},
failure: function () {
me.sessionToken = null;
me.showSignInFailedMessage('Login failed. Please try again later.');
}
});
}
And server-side:
private void Login(HttpContext context)
{
var resultStt = "";
var userid = context.Request["username"];
var password = context.Request["password"];
if(!string.IsNullOrEmpty(userid) && !string.IsNullOrEmpty(password))
{
var user = new Select() .From<User>()
.Where("UserID").IsEqualTo(userid)
.And("UserPassword").IsEqualTo(password)
.ExecuteSingle<User>();
if(user!=null)
{
context.Session.Add("PickerUser",user);
resultStt = " {\"success\":true, \"user\":{ \"userId\":"+user.UserID+", \"sessionId\":\"" + context.Session.SessionID + "\"}}";
}
else
{
resultStt = " {\"success\":false, \"message\":\"Login failed. Please enter the correct credentials.\"}";
}
}
context.Response.Write(resultStt);
}
The second page that i need get a list procducts created by user
store: {
autoload:true,
...
proxy: {
type: "ajax",
url: "./ajax/process.ashx?type=loadassigned",
reader:{
type:"json",
rootProperty: "data"
}
}
},
Can not get session because the ajax was loaded at the time of startup app
var currenUser = context.Session["PickerUser"] as User;
You could remove the config:
autoLoad: true
And call this in your login success handler function:
Ext.getStore('yourStoresId').load({
callback: function() {
console.log('my store has loaded');
}
});

Calling ajax webservice from OnComplete of an ajax webservice call not firing OnComplete 2nd time

I have an ajaxified .NET webservice that I call from javascript(mootools) on my ASP.NET content page with a Masterpage firstly to check if the user has associated journalists, secondly to delete the user if no journalists are associated.
Both calls to the webservice work, but the onComplete for the second does not in IE8.
Using FF 3.5.3 I get a "deleteUserInt is not defined" error in firebug.
I have read around that this can be a sytax error, but cannot seem to see it.
Please help.
var userId;
var siteName;
var siteFolder;
function userInternalHasUserExternals() {
siteName = document.location.href.split("/")[document.location.href.split("/").length - 1];
siteFolder = document.location.href.replace(siteName, "");
var jsonRequest = new Request.JSON({ url: siteFolder + "Service1.asmx/UserInternalHasUserExternals",
onComplete: onComplete,
onFailure: onError,
urlEncoded: false,
headers: { "Content-type": "application/json" }
});
userId = document.getElementById("<%= HiddenId.ClientID %>").innerText;
jsonRequest.send(JSON.encode({ 'userInternalId': userId }));
}
function onComplete(results) {
var fullname = document.getElementById("<%= fullnameTextBox.ClientID %>").value;
if (results != null && results["d"] != null && results["d"]) {
alert("Du kan ikke slette " + fullname + ". Kontoen har journalister tilknyttet.");
return false;
}
var deleteUser = confirm("Er du sikker på du vil slette " + fullname + "?");
if (deleteUser) {
deleteUserInt();
window.location = window.siteFolder + "CreateUserInternal.aspx?IsDeleted=true";
}
else
window.location = window.siteFolder + "EditUserInternal.aspx?UserInternalId=" + window.userId;
}
function deleteUserInt() {
var request;
request = new Request.JSON({ url: window.siteFolder + "Service1.asmx/DeleteUserInternal",
onComplete: onDeleted,
onFailure: onError,
urlEncoded: false,
headers: { "Content-type": "application/json" }
});
request.send(JSON.encode({ 'userInternalId': window.userId }));
}
function onDeleted(args) {
if (args != null && args["d"] != null && args["d"])
window.location = window.siteFolder + "CreateUserInternal.aspx?IsDeleted=true";
else
alert("Der skete en fejl. Kontakt venligst site administrator.");
}
function onError() {
alert("Something bad happened!");
}
This was "solved" after I moved my javascript out in a file and found an error using innerText instead of innerHTML.
The IE8 missing function being called also "fixed" itself after being moved.
Of course I had to pass the ClientIds, which I used in my aspx page as parameters to the new method, but that worked fine for me.
For some reason Firefox jumps the gun when I have 2 a confirm and then an alert.

Resources