Click here to Skip to main content
15,889,216 members
Articles / Mobile Apps / Windows Phone 7
Tip/Trick

Login and Logout from Facebook in Windows Phone 7

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
12 Jun 2013CPOL 19.8K   209   2   1
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:

C#
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

C#
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)


Written By
Software Developer (Junior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

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

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

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