0

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?

Rubia Gardini
  • 815
  • 5
  • 16
  • 30
  • I have a similar solution ... not sure if this will solve .. but try offline_access,email instead of email in your login button. – MoXplod Nov 03 '11 at 18:25

1 Answers1

1

This line make everything works fine with Facebook Birthday

var birthdate = DateTime.ParseExact(me.birthday, "MM/dd/yyyy", CultureInfo.InvariantCulture);
Rubia Gardini
  • 815
  • 5
  • 16
  • 30