Click here to Skip to main content
Click here to Skip to main content

Login and Logout from Facebook in Windows Phone 7

, 12 Jun 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Logout from Facebook.

Introduction

This tip describes how to Logout a Facebook user which is authenticated or connected with a Windows 7 phone application.

Background

Last week, when I was developing a Windows Phone 7 application with Facebook integration, at some point I needed code to logout from an authenticated or connected Facebook user. I did a lot of search on Google but no solution was found. So I did a tricky thing in my Windows Phone 7 application.

Login to Facebook

This block will describe how to integrate a Facebook login with a Windows Phone 7 application:

private static readonly Uri FacebookCookieUri = 
          new Uri("https://login.facebook.com/login.php");
private HttpWebRequest _webRequest;
private CookieContainer _cookieContainer = new CookieContainer();

private FacebookClient _asyncFbClient;
private string _appID = "xxxxxxxx";
private string _appSecret = "xxxxxxxxxxxxxx";

private void button1_Click(object sender, RoutedEventArgs e)
{
    string[] extendedPermissions = new[] { "user_about_me", "publish_stream" };

    var oauth = new FacebookOAuthClient { AppId = _appID, AppSecret = _appSecret };
    var parameters = new Dictionary<string, object>
                    {
                        {"response_type", "token"},
                        {"display", "touch"}                                        
                    };
    if (extendedPermissions != null && extendedPermissions.Length > 0)
    {
        var scope = new StringBuilder();
        scope.Append(string.Join(",", extendedPermissions));
        parameters["scope"] = scope.ToString();
    }

    var loginUrl = oauth.GetLoginUrl(parameters);
    webBrowser1.Navigated += 
      new EventHandler<System.Windows.Navigation.NavigationEventArgs>(CheckForAuth);
    webBrowser1.Navigate(loginUrl);
    webBrowser1.Visibility = Visibility.Visible;
}

private void CheckForAuth(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
    FacebookOAuthResult result;
    if (FacebookOAuthResult.TryParse(e.Uri, out result))
    {
        if (result.IsSuccess)
        {
            webBrowser1.Visibility = Visibility.Collapsed;
            IsolatedStorageSettings Settings = IsolatedStorageSettings.ApplicationSettings;
            if (Settings.Contains("MyFacebookAccessToken"))
                Settings["MyFacebookAccessToken"] = result.AccessToken;
            else
                Settings.Add("MyFacebookAccessToken", result.AccessToken);
            //      MessageBox.Show(result.AccessToken);
            Settings.Save();
            _asyncFbClient = new FacebookClient(result.AccessToken);
            _asyncFbClient.GetCompleted += 
              new EventHandler<FacebookApiEventArgs>(_asyncFbClient_GetCompleted);
            _asyncFbClient.GetAsync("/me");
        }
        else
        {
            webBrowser1.Visibility = Visibility.Visible;
        }
    }
}

void _asyncFbClient_GetCompleted(object sender, FacebookApiEventArgs e)
{
    FacebookUser _fbUser = e.GetResultData<FacebookUser>();

    Deployment.Current.Dispatcher.BeginInvoke(() =>
    {
        MessageBox.Show(_fbUser.ID);
        //  fbName.Text = _fbUser.Name;
        //    BitmapImage bi = new BitmapImage(new Uri(
        //         "https://graph.facebook.com/" + _fbUser.ID + "/picture"));
        //   fbAvatar.Source = bi;
        // HideFacebookLogin.Begin();
    });
    _asyncFbClient.GetCompleted -= _asyncFbClient_GetCompleted;
}

Logout from Facebook

private void button2_Click(object sender, RoutedEventArgs e)
{
    webBrowser1.Navigated += 
      new EventHandler<System.Windows.Navigation.NavigationEventArgs>(CheckForout);
    webBrowser1.Navigate(new Uri("http://m.facebook.com/logout.php?confirm=1"));
    webBrowser1.Visibility = Visibility.Visible;
}

private void CheckForout(object sender, System.Windows.Navigation.NavigationEventArgs e)
{

    string fbLogoutDoc = webBrowser1.SaveToString();

    Regex regex = new Regex
    ("\\<a href=\\\"/logout(.*)\\\".*data-sigil=\\\"logout\\\"");
    MatchCollection matches = regex.Matches(fbLogoutDoc);
    if (matches.Count > 0)
    {
        string finalLogout = string.Format("http://m.facebook.com/logout{0}", 
            matches[0].Groups[1].ToString().Replace("amp;", "")); 
         webBrowser1.Navigate(new Uri(finalLogout));
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sahil Mehta
Software Developer (Junior)
India India
No Biography provided

Comments and Discussions

 
QuestionThis wasn't an article three days ago... PinprotectorOriginalGriff14-Jun-13 22:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.141015.1 | Last Updated 12 Jun 2013
Article Copyright 2013 by Sahil Mehta
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid