Authentication Using Facebook, Google and Microsoft Account in WP8.0 App (MVVM)

This sample shows how to connect a Windows Phone 8.0 app to Facebook, Google and Microsoft accounts. The main features: Login/Logout and an about page with feedback, share in social networks, review and share by email.

Download C# (19.9 MB)

Introduction

This sample shows how to connect a Windows Phone 8.0 app to Facebook, Google and Microsoft account.

Main Features: Login/Logout and an about page with feedback, share in social networks, review and share by email.

Building the Sample

You only need Visual Studio 2012/Visual Studio 2013 and Windows 8/Windows 8.1, both the RTM version.

This sample requires the installation for Live SDK (Downloads).
 
Description

This sample shows how to connect a Windows Phone 8.0 app to Facebook, Google and Microsoft accounts.

Main Features

  • Login/Logout (for logout I added a workarround to fix the logout providers from the SDKs!)
  • An About page with feedback, share in social networks, review and share by email (not important here, but is incluided in code)

Note: This sample uses MVVM Light and Cimbalino Windows Phone Toolkit.

For this sample the following was used:

For each provider it is necessry to get the app id/client id/client secret in their websites.

For Google go to https://console.developers.google.com/project and create a new project (APIs & auth > credentials).

Installed

For Facebook go to Facebook Developers and create a new app.

For Live SDK go to Sign in and create one or use an existing app.

Before you start you should change the Constant file to add client ids / client secret / app id, without it the app fails!!

This file is inside the Resource folder.

C#

  1.  /// <summary>   
  2. /// Defines the constants strings used in the app.   
  3. /// </summary>   
  4. public class Constants   
  5. {   
  6. /// <summary>   
  7. /// The facebook app id.   
  8. /// </summary>   
  9. public const string FacebookAppId = "<app id>";        
  10. /// <summary>   
  11. /// The google client identifier.   
  12. /// </summary>   
  13. public const string GoogleClientId = "<client id>";      
  14.   
  15. /// <summary>   
  16. /// The google token file name.   
  17. /// </summary>  
  18.   
  19. public const string GoogleTokenFileName = "Google.Apis.Auth.OAuth2.Responses.TokenResponse-user";        
  20. /// <summary>   
  21. /// The google client secret.   
  22. /// </summary>  
  23.   
  24. public const string GoogleClientSecret = "<client secret>";        
  25. /// <summary>   
  26. /// The microsoft client identifier.   
  27. /// </summary>   
  28. public const string MicrosoftClientId = "<client id>";   
  29. ...   
  30. }  

Now let's see how to connect to each provider. For help, I created a SessionService that managed the Login and Logout using a provider value, this is nice because in LoginView I set the buttons to the same command and for each command I set the provider in commandparameter. With it the LoginView and LoginViewModel are clearer and simpler. Another thing is for example if I need to connect to my server to accept the user I can do it in the session manager after the authentication, without adding the code to each provider.

The classes created:

  • FacebookService has all code related with authentication with Facebook account
  • MicrosoftService has all code related with authentication with Microsoft account
  • GoogleService has all code related with authentication with Google account
  • SessionService call the methods login or logout for the provide requested

The FacebookService is:

C#


  1.  /// <summary>   
  2. /// Defines the Facebook Service.   
  3. /// </summary>  
  4.   
  5. public class FacebookService : IFacebookService   
  6. {   
  7.     private readonly ILogManager _logManager;   
  8.     private readonly FacebookSessionClient _facebookSessionClient;      
  9.   
  10.     /// <summary>   
  11.     /// Initializes a new instance of the <see cref="FacebookService"/> class.   
  12.     /// </summary>   
  13.     /// <param name="logManager">   
  14.     /// The log manager.   
  15.     /// </param>  
  16.   
  17.     public FacebookService(ILogManager logManager)   
  18.     {   
  19.         _logManager = logManager;   
  20.         _facebookSessionClient = new FacebookSessionClient(Constants.FacebookAppId);   
  21.     }  
  22.   
  23.     /// <summary>   
  24.     /// The login sync.   
  25.     /// </summary>   
  26.     /// <returns>   
  27.     /// The <see cref="Task"/> object.   
  28.     /// </returns>  
  29.   
  30.     public async Task<Session> LoginAsync()   
  31.     {   
  32.         Exception exception;   
  33.         Session sessionToReturn = null;   
  34.         try   
  35.         {   
  36.             var session = await _facebookSessionClient.LoginAsync("user_about_me,read_stream");   
  37.             sessionToReturn = new Session   
  38.             {   
  39.                 AccessToken = session.AccessToken,   
  40.                 Id = session.FacebookId,   
  41.                 ExpireDate = session.Expires,   
  42.                 Provider = Constants.FacebookProvider   
  43.             };   
  44.             return sessionToReturn;   
  45.         }     
  46.         catch (InvalidOperationException)   
  47.         {   
  48.             throw;   
  49.         }   
  50.         catch (Exception ex)   
  51.         {   
  52.             exception = ex;   
  53.         }   
  54.         await _logManager.LogAsync(exception);   
  55.         return sessionToReturn;   
  56.     }  
  57.       /// <summary>   
  58.     /// Logouts this instance.   
  59.     /// </summary>  
  60.   
  61.     public async void Logout()   
  62.     {   
  63.         Exception exception = null;   
  64.         try   
  65.         {   
  66.             _facebookSessionClient.Logout();   
  67.             // clean all cookies from browser, is a workarround   
  68.             await new WebBrowser().ClearCookiesAsync();   
  69.         }   
  70.         catch (Exception ex)   
  71.         {   
  72.             exception = ex;   
  73.         }   
  74.         if (exception != null)   
  75.         {   
  76.             await _logManager.LogAsync(exception);   
  77.         }   
  78.     }   
  79. }  

Note: In logout I added a workarround to clear all cookies in browser, if I don´t this in the first time you can login with account you want but in the next time it will use the account used in last login.

The GoogleService is:

C#

  1.  /// <summary>   
  2. /// The google service.   
  3. /// </summary>  
  4.   
  5. public class GoogleService : IGoogleService   
  6. {   
  7.     private readonly ILogManager _logManager;   
  8.     private readonly IStorageService _storageService;   
  9.     private UserCredential _credential;   
  10.     private Oauth2Service _authService;   
  11.     private Userinfoplus _userinfoplus;      
  12.   
  13.     /// <summary>   
  14.     /// Initializes a new instance of the <see cref="GoogleService" /> class.   
  15.     /// </summary>   
  16.     /// <param name="logManager">The log manager.</param>   
  17.     /// <param name="storageService">The storage service.</param>  
  18.   
  19.     public GoogleService(ILogManager logManager, IStorageService storageService)   
  20.     {   
  21.         _logManager = logManager;   
  22.         _storageService = storageService;   
  23.     }      
  24.   
  25.     /// <summary>   
  26.     /// The login async.   
  27.     /// </summary>   
  28.     /// <returns>   
  29.     /// The <see cref="Task"/> object.   
  30.     /// </returns>  
  31.   
  32.     public async Task<Session> LoginAsync()   
  33.     {   
  34.         Exception exception = null;   
  35.         try   
  36.         {   
  37.             // Oauth2Service.Scope.UserinfoEmail   
  38.             _credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets   
  39.             {   
  40.                 ClientId = Constants.GoogleClientId,   
  41.                 ClientSecret = Constants.GoogleClientSecret   
  42.             }, new[] { Oauth2Service.Scope.UserinfoProfile }, "user", CancellationToken.None);      
  43.   
  44.             var session = new Session   
  45.             {   
  46.                 AccessToken = _credential.Token.AccessToken,   
  47.                 Provider = Constants.GoogleProvider,   
  48.                 ExpireDate =   
  49.                 _credential.Token.ExpiresInSeconds != null   
  50.                 ? new DateTime(_credential.Token.ExpiresInSeconds.Value)   
  51.                 : DateTime.Now.AddYears(1),   
  52.                 Id = string.Empty   
  53.             };   
  54.             return session;   
  55.         }   
  56.         catch (TaskCanceledException taskCanceledException)   
  57.         {   
  58.             throw new InvalidOperationException("Login canceled.", taskCanceledException);   
  59.         }   
  60.         catch (Exception ex)   
  61.         {   
  62.             exception = ex;   
  63.         }   
  64.         await _logManager.LogAsync(exception);   
  65.         return null;   
  66.     }   
  67.     /// <summary>   
  68.     /// Gets the user information.   
  69.     /// </summary>   
  70.     /// <returns>   
  71.     /// The user info.   
  72.     /// </returns>  
  73.   
  74.     public async Task<Userinfoplus> GetUserInfo()   
  75.     {   
  76.         _authService = new Oauth2Service(new BaseClientService.Initializer()   
  77.         {   
  78.             HttpClientInitializer = _credential,   
  79.             ApplicationName = AppResources.ApplicationTitle,   
  80.         });   
  81.         _userinfoplus = await _authService.Userinfo.V2.Me.Get().ExecuteAsync();   
  82.         return _userinfoplus;   
  83.     }  
  84.   
  85.     /// <summary>   
  86.     /// The logout.   
  87.     /// </summary>   
  88.     public async void Logout()   
  89.     {   
  90.         await new WebBrowser().ClearCookiesAsync();   
  91.         if (_storageService.FileExists(Constants.GoogleTokenFileName))   
  92.         {   
  93.             _storageService.DeleteFile(Constants.GoogleTokenFileName);   
  94.         }   
  95.     }   

Note: In the logout for the Google provider there isn´t a logout method, the solution is to remove all cookies and remove the file created in the login operation.

The MicrosoftService is:

C#

  1. /// <summary>  
  2. /// The microsoft service.  
  3. /// </summary>  
  4.   
  5. public class MicrosoftService : IMicrosoftService  
  6. {   
  7.     private readonly ILogManager _logManager;  
  8.     private LiveAuthClient _authClient;  
  9.     private LiveConnectSession _liveSession;   
  10.   
  11.     /// <summary>  
  12.     /// Defines the scopes the application needs.  
  13.     /// </summary>  
  14.   
  15.     private static readonly string[] Scopes = { "wl.signin""wl.basic""wl.offline_access" };  
  16.   
  17.     /// <summary>  
  18.     /// Initializes a new instance of the <see cref="MicrosoftService"/> class.  
  19.     /// </summary>  
  20.     /// <param name="logManager">  
  21.     /// The log manager.  
  22.     /// </param>  
  23.   
  24.     public MicrosoftService(ILogManager logManager)  
  25.     {  
  26.        _logManager = logManager;  
  27.     }  
  28.   
  29.     /// <summary>  
  30.     /// The login async.  
  31.     /// </summary>  
  32.     /// <returns>  
  33.     /// The <see cref="Task"/> object.  
  34.     /// </returns>  
  35.   
  36.     public async Task<Session> LoginAsync()  
  37.     {  
  38.         Exception exception = null;  
  39.         try  
  40.         {  
  41.             _authClient = new LiveAuthClient(Constants.MicrosoftClientId);  
  42.             var loginResult = await _authClient.InitializeAsync(Scopes);  
  43.             var result = await _authClient.LoginAsync(Scopes);  
  44.             if (result.Status == LiveConnectSessionStatus.Connected)  
  45.             {  
  46.                 _liveSession = loginResult.Session;  
  47.                 var session = new Session  
  48.                 {  
  49.                     AccessToken = result.Session.AccessToken,  
  50.                     ExpireDate = result.Session.Expires.DateTime,  
  51.                     Provider = Constants.MicrosoftProvider,  
  52.                 };  
  53.                 return session;  
  54.             }  
  55.         }  
  56.         catch (LiveAuthException ex)  
  57.         {  
  58.            throw new InvalidOperationException("Login canceled.", ex);  
  59.         }  
  60.         catch (Exception e)  
  61.         {  
  62.         exception = e;  
  63.         }  
  64.         await _logManager.LogAsync(exception);  
  65.         return null;  
  66.     }  
  67.   
  68.     /// <summary>  
  69.     /// The logout.  
  70.     /// </summary>  
  71.   
  72.     public async void Logout()  
  73.     {  
  74.         if (_authClient == null)  
  75.         {  
  76.             _authClient = new LiveAuthClient(Constants.MicrosoftClientId);  
  77.             var loginResult = await _authClient.InitializeAsync(Scopes);  
  78.         }  
  79.         _authClient.Logout();  
  80.     }  
  81. }   

The SessionService is:

C#

  1.  /// <summary>   
  2. /// The service session.   
  3. /// </summary>  
  4.   
  5. public class SessionService : ISessionService   
  6. {   
  7.     private readonly IApplicationSettingsService _applicationSettings;   
  8.     private readonly IFacebookService _facebookService;   
  9.     private readonly IMicrosoftService _microsoftService;   
  10.     private readonly IGoogleService _googleService;   
  11.     private readonly ILogManager _logManager;  
  12.   
  13.     /// <summary>   
  14.     /// Initializes a new instance of the <see cref="SessionService" /> class.   
  15.     /// </summary>   
  16.     /// <param name="applicationSettings">The application settings.</param>   
  17.     /// <param name="facebookService">The facebook service.</param>   
  18.     /// <param name="microsoftService">The microsoft service.</param>   
  19.     /// <param name="googleService">The google service.</param>   
  20.     /// <param name="logManager">The log manager.</param>  
  21.   
  22.     public SessionService(IApplicationSettingsService applicationSettings,   
  23.     IFacebookService facebookService,   
  24.     IMicrosoftService microsoftService,   
  25.     IGoogleService googleService, ILogManager logManager)   
  26.     {   
  27.         _applicationSettings = applicationSettings;   
  28.         _facebookService = facebookService;   
  29.         _microsoftService = microsoftService;   
  30.         _googleService = googleService;   
  31.         _logManager = logManager;   
  32.     }  
  33.   
  34.     /// <summary>   
  35.     /// Gets the session.   
  36.     /// </summary>   
  37.     /// <returns>The session object.</returns>  
  38.   
  39.     public Session GetSession()   
  40.     {   
  41.         var expiryValue = DateTime.MinValue;   
  42.         string expiryTicks = LoadEncryptedSettingValue("session_expiredate");   
  43.         if (!string.IsNullOrWhiteSpace(expiryTicks))   
  44.         {   
  45.             long expiryTicksValue;   
  46.             if (long.TryParse(expiryTicks, out expiryTicksValue))   
  47.             {   
  48.                 expiryValue = new DateTime(expiryTicksValue);   
  49.             }   
  50.         }   
  51.         var session = new Session   
  52.         {   
  53.             AccessToken = LoadEncryptedSettingValue("session_token"),   
  54.             Id = LoadEncryptedSettingValue("session_id"),   
  55.             ExpireDate = expiryValue,   
  56.             Provider = LoadEncryptedSettingValue("session_provider")   
  57.         };  
  58.   
  59.         _applicationSettings.Set(Constants.LoginToken, true);   
  60.         _applicationSettings.Save();   
  61.         return session;   
  62.     }  
  63.   
  64.     /// <summary>   
  65.     /// The save session.   
  66.     /// </summary>   
  67.     /// <param name="session">   
  68.     /// The session.   
  69.     /// </param>  
  70.   
  71.     private void Save(Session session)   
  72.     {  
  73.   
  74.         SaveEncryptedSettingValue("session_token", session.AccessToken);   
  75.         SaveEncryptedSettingValue("session_id", session.Id);   
  76.         SaveEncryptedSettingValue("session_expiredate", session.ExpireDate.Ticks.ToString(CultureInfo.InvariantCulture));   
  77.         SaveEncryptedSettingValue("session_provider", session.Provider);   
  78.         _applicationSettings.Set(Constants.LoginToken, true);   
  79.         _applicationSettings.Save();   
  80.     }  
  81.   
  82.     /// <summary>   
  83.     /// The clean session.   
  84.     /// </summary>  
  85.   
  86.     private void CleanSession()   
  87.     {   
  88.         _applicationSettings.Reset("session_token");   
  89.         _applicationSettings.Reset("session_id");   
  90.         _applicationSettings.Reset("session_expiredate");   
  91.         _applicationSettings.Reset("session_provider");   
  92.         _applicationSettings.Reset(Constants.LoginToken);   
  93.         _applicationSettings.Save();   
  94.     }  
  95.   
  96.     /// <summary>   
  97.     /// The login async.   
  98.     /// </summary>   
  99.     /// <param name="provider">   
  100.     /// The provider.   
  101.     /// </param>   
  102.     /// <returns>   
  103.     /// The <see cref="Task"/> object.   
  104.     /// </returns>  
  105.   
  106.     public async Task<bool> LoginAsync(string provider)   
  107.     {   
  108.         Exception exception = null;   
  109.         try   
  110.         {   
  111.             Session session = null;   
  112.             switch (provider)   
  113.             {   
  114.                 case Constants.FacebookProvider:   
  115.                 session = await _facebookService.LoginAsync();   
  116.                 break;   
  117.                 case Constants.MicrosoftProvider:   
  118.                 session = await _microsoftService.LoginAsync();   
  119.                 break;   
  120.                 case Constants.GoogleProvider:   
  121.                 session = await _googleService.LoginAsync();   
  122.                 break;   
  123.             }   
  124.             if (session != null)   
  125.             {   
  126.                 Save(session);   
  127.             }   
  128.             return true;   
  129.         }   
  130.         catch (InvalidOperationException e)   
  131.         {   
  132.             throw;   
  133.         }   
  134.         catch (Exception ex)   
  135.         {   
  136.             exception = ex;   
  137.         }   
  138.         await _logManager.LogAsync(exception);   
  139.         return false;   
  140.     }   
  141.     /// <summary>   
  142.     /// The logout.   
  143.     /// </summary>  
  144.   
  145.     public async void Logout()   
  146.     {   
  147.         Exception exception = null;   
  148.         try   
  149.         {   
  150.             var session = GetSession();   
  151.             switch (session.Provider)   
  152.             {   
  153.                 case Constants.FacebookProvider:  
  154.                 _facebookService.Logout();   
  155.                 break;   
  156.                 case Constants.MicrosoftProvider:   
  157.                 _microsoftService.Logout();   
  158.                 break;   
  159.                 case Constants.GoogleProvider:   
  160.                 _googleService.Logout();   
  161.                 break;   
  162.             }   
  163.             CleanSession();   
  164.         }   
  165.         catch (Exception ex)   
  166.         {   
  167.             exception = ex;   
  168.         }   
  169.         if (exception != null)   
  170.         {   
  171.             await _logManager.LogAsync(exception);   
  172.         }   
  173.     }  
  174.   
  175.     /// <summary>   
  176.     /// Loads an encrypted setting value for a given key.   
  177.     /// </summary>   
  178.     /// <param name="key">   
  179.     /// The key to load.   
  180.     /// </param>   
  181.     /// <returns>   
  182.     /// The value of the key.   
  183.     /// </returns>  
  184.   
  185.     private string LoadEncryptedSettingValue(string key)   
  186.     {   
  187.         string value = null;   
  188.         var protectedBytes = _applicationSettings.Get<byte[]>(key);   
  189.         if (protectedBytes != null)   
  190.         {   
  191.             byte[] valueBytes = ProtectedData.Unprotect(protectedBytes, null);   
  192.             value = Encoding.UTF8.GetString(valueBytes, 0, valueBytes.Length);   
  193.         }   
  194.         return value;   
  195.     }      
  196.   
  197.     /// <summary>   
  198.     /// Saves a setting value against a given key, encrypted.   
  199.     /// </summary>   
  200.     /// <param name="key">   
  201.     /// The key to save against.   
  202.     /// </param>   
  203.     /// <param name="value">   
  204.     /// The value to save against.   
  205.     /// </param>   
  206.     /// <exception cref="System.ArgumentOutOfRangeException">   
  207.     /// The key or value provided is unexpected.   
  208.     /// </exception>  
  209.   
  210.     private void SaveEncryptedSettingValue(string key, string value)   
  211.     {   
  212.         if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(value))   
  213.         {   
  214.             byte[] valueBytes = Encoding.UTF8.GetBytes(value);   
  215.             // Encrypt the value by using the Protect() method.   
  216.             byte[] protectedBytes = ProtectedData.Protect(valueBytes, null);   
  217.             _applicationSettings.Set(key, protectedBytes);   
  218.             _applicationSettings.Save();   
  219.         }   
  220.     }   
  221. }   

Now is time to build the User Interface, and because I am using MVVM, I created a LoginViewModel to bind to the LoginView.

The LoginViewModel is:

C#

  1.  /// <summary>   
  2. /// The login view model.   
  3. /// </summary>  
  4.   
  5. public class LoginViewModel : ViewModelBase   
  6. {   
  7.     private readonly ILogManager _logManager;   
  8.     private readonly IMessageBoxService _messageBox;   
  9.     private readonly INavigationService _navigationService;   
  10.     private readonly ISessionService _sessionService;   
  11.     private bool _inProgress;      
  12.   
  13.     /// <summary>   
  14.     /// Initializes a new instance of the <see cref="LoginViewModel"/> class.   
  15.     /// </summary>   
  16.     /// <param name="navigationService">   
  17.     /// The navigation service.   
  18.     /// </param>   
  19.     /// <param name="sessionService">   
  20.     /// The session service.   
  21.     /// </param>   
  22.     /// <param name="messageBox">   
  23.     /// The message box.   
  24.     /// </param>   
  25.     /// <param name="logManager">   
  26.     /// The log manager.   
  27.     /// </param>  
  28.   
  29.     public LoginViewModel(INavigationService navigationService,   
  30.     ISessionService sessionService,   
  31.     IMessageBoxService messageBox,   
  32.     ILogManager logManager)   
  33.     {   
  34.         _navigationService = navigationService;   
  35.         _sessionService = sessionService;   
  36.         _messageBox = messageBox;   
  37.         _logManager = logManager;   
  38.         LoginCommand = new RelayCommand<string>(LoginAction);   
  39.     }      
  40.   
  41.     /// <summary>   
  42.     /// Gets or sets a value indicating whether in progress.   
  43.     /// </summary>   
  44.     /// <value>   
  45.     /// The in progress.   
  46.     /// </value>  
  47.   
  48.     public bool InProgress   
  49.     {   
  50.        get { return _inProgress; }   
  51.        set { Set(() => InProgress, ref _inProgress, value); }   
  52.     }   
  53.     
  54.     /// <summary>   
  55.     /// Gets the facebook login command.   
  56.     /// </summary>   
  57.     /// <value>   
  58.     /// The facebook login command.   
  59.     /// </value>  
  60.   
  61.     public ICommand LoginCommand { getprivate set; }   
  62.     
  63.     /// <summary>   
  64.     /// Facebook's login action.   
  65.     /// </summary>   
  66.     /// <param name="provider">   
  67.     /// The provider.   
  68.     /// </param>  
  69.   
  70.     private async void LoginAction(string provider)   
  71.     {   
  72.         Exception exception = null;   
  73.         bool isToShowMessage = false;   
  74.         try   
  75.         {   
  76.             InProgress = true;   
  77.             var auth = await _sessionService.LoginAsync(provider);   
  78.             if (!auth)   
  79.             {   
  80.                 await _messageBox.ShowAsync(AppResources.LoginView_LoginNotAllowed_Message,   
  81.                 AppResources.MessageBox_Title,   
  82.                 new List<string>   
  83.                 {   
  84.                     AppResources.Button_OK   
  85.                 });   
  86.             }   
  87.             else   
  88.             {   
  89.                 _navigationService.NavigateTo(new Uri(Constants.MainView, UriKind.Relative));   
  90.             }   
  91.             InProgress = false;   
  92.         }   
  93.         catch (InvalidOperationException e)   
  94.         {   
  95.             InProgress = false;   
  96.             isToShowMessage = true;   
  97.         }   
  98.         catch (Exception ex)   
  99.         {   
  100.             exception = ex;   
  101.         }   
  102.         if (isToShowMessage)   
  103.         {   
  104.             await _messageBox.ShowAsync(AppResources.LoginView_AuthFail, AppResources.ApplicationTitle, new List<string> { AppResources.Button_OK });   
  105.         }  
  106.         if (exception != null)   
  107.         {   
  108.             await _logManager.LogAsync(exception);   
  109.         }   
  110.     }   
  111. }   

Note: in LoginAction the parameter provider is the value of the CommandParameter received in the LoginCommand, this is set in the login page.

The LoginPage.xaml is:

XAML

  1.  <phone:PhoneApplicationPage x:Class="AuthenticationSample.WP80.Views.LoginView"   
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
  4. xmlns:Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP8"   
  5. xmlns:controls="clr-namespace:Facebook.Client.Controls;assembly=Facebook.Client"   
  6. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"   
  7. xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"   
  8. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"   
  9. xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"   
  10. xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"   
  11. xmlns:converters="clr-namespace:Cimbalino.Phone.Toolkit.Converters;assembly=Cimbalino.Phone.Toolkit"   
  12. Orientation="Portrait"   
  13. SupportedOrientations="Portrait"   
  14. shell:SystemTray.IsVisible="True"   
  15. mc:Ignorable="d">   
  16.   <phone:PhoneApplicationPage.DataContext>   
  17.     <Binding Mode="OneWay"   
  18.     Path="LoginViewModel"   
  19.     Source="{StaticResource Locator}" />   
  20.   </phone:PhoneApplicationPage.DataContext>   
  21.   <phone:PhoneApplicationPage.Resources>   
  22.     <converters:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>   
  23.   </phone:PhoneApplicationPage.Resources>   
  24.   <phone:PhoneApplicationPage.FontFamily>   
  25.     <StaticResource ResourceKey="PhoneFontFamilyNormal" />   
  26.   </phone:PhoneApplicationPage.FontFamily>   
  27.   <phone:PhoneApplicationPage.FontSize>   
  28.     <StaticResource ResourceKey="PhoneFontSizeNormal" />   
  29.   </phone:PhoneApplicationPage.FontSize>   
  30.   <phone:PhoneApplicationPage.Foreground>   
  31.     <StaticResource ResourceKey="PhoneForegroundBrush" />   
  32.   </phone:PhoneApplicationPage.Foreground>   
  33.   <!-- LayoutRoot is the root grid where all page content is placed -->   
  34.   <Grid x:Name="LayoutRoot" Background="Transparent">   
  35.     <Grid.RowDefinitions>   
  36.       <RowDefinition Height="Auto" />   
  37.       <RowDefinition Height="*" />   
  38.     </Grid.RowDefinitions>        
  39.     <!-- TitlePanel contains the name of the application and page title -->   
  40.     <StackPanel x:Name="TitlePanel"   
  41.     Grid.Row="0"   
  42.     Margin="12,17,0,28">   
  43.       <TextBlock Margin="12,0"   
  44.       Style="{StaticResource PhoneTextNormalStyle}"   
  45.       Text="{Binding LocalizedResources.ApplicationTitle,   
  46. Mode=OneWay,   
  47. Source={StaticResource LocalizedStrings}}" />   
  48.       <TextBlock Margin="9,-7,0,0"   
  49.       Style="{StaticResource PhoneTextTitle1Style}"   
  50.       Text="{Binding LocalizedResources.LoginView_Title,   
  51. Mode=OneWay,   
  52. Source={StaticResource LocalizedStrings}}" />   
  53.     </StackPanel>        
  54.     <!-- ContentPanel - place additional content here -->   
  55.     <Grid x:Name="ContentPanel"   
  56.     Grid.Row="1"   
  57.     Margin="24,0,0,-40">   
  58.       <Grid.RowDefinitions>   
  59.         <RowDefinition Height="Auto" />   
  60.         <RowDefinition Height="Auto" />   
  61.         <RowDefinition Height="Auto" />   
  62.         <RowDefinition Height="Auto" />   
  63.         <RowDefinition Height="Auto" />   
  64.       </Grid.RowDefinitions>   
  65.       <TextBlock Grid.Row="0"   
  66.       Style="{StaticResource PhoneTextTitle2Style}"   
  67.       Text="{Binding LocalizedResources.LoginView_UserAccount,   
  68. Mode=OneWay,   
  69. Source={StaticResource LocalizedStrings}}" />   
  70.       <Button Grid.Row="1"   
  71.       Margin="10"   
  72.       Command="{Binding LoginCommand}"   
  73.       CommandParameter="facebook"   
  74.       Content="Facebook" />   
  75.       <Button Grid.Row="2"   
  76.       Margin="10"   
  77.       Command="{Binding LoginCommand}"   
  78.       CommandParameter="microsoft"   
  79.       Content="Microsoft" />   
  80.       <Button Grid.Row="3"   
  81.       Margin="10"   
  82.       Command="{Binding LoginCommand}"   
  83.       CommandParameter="google"   
  84.       Content="Google" />   
  85.     </Grid>   
  86.     <Grid Visibility="{Binding InProgress, Converter={StaticResource BooleanToVisibilityConverter}}"   
  87.     Grid.Row="0"   
  88.     Grid.RowSpan="2">   
  89.       <Rectangle   
  90.       Fill="Black"   
  91.       Opacity="0.75" />   
  92.       <TextBlock   
  93.       HorizontalAlignment="Center"   
  94.       VerticalAlignment="Center"   
  95.       Text="{Binding LocalizedResources.LoginView_AuthMessage,   
  96. Mode=OneWay,   
  97. Source={StaticResource LocalizedStrings}}" />   
  98.       <ProgressBar IsIndeterminate="True" IsEnabled="True" Margin="0,60,0,0"/>   
  99.     </Grid>   
  100.   </Grid>   
  101. </phone:PhoneApplicationPage> 

Login User Interface

Run

Source Code Files
  • IFacebookService interface for FacebookService
  • IGoogleService interface for GoogleService
  • ILogManager interface for LogManager
  • IMicrosoftService interface for MicrosoftService
  • ISessionProvider interface for all providers interface (common methods)
  • ISessionService for SessionService
  • Session class for save the information about the session (provider, token, expired date)
  • FacebookService class that has all logic about the login / logout using Facebook provider
  • GoogleService class that has all logic about the login / logout using Google provider
  • MicrosoftService class that has all logic about the login / logout using Microsoft provider
  • SessionService class for manage login/logout (it will use all services provides described before)
  • LoginViewModel class for binding to LoginView.xaml
  • LoginView class that represent the page for login
  • MainViewModel class for binding to MainView.xaml
  • MainView class that appear after the login is ok
  • AboutViewModel class for binding to the AboutView.xaml
  • AboutView class that represents the about page
  • ViewModelLocator class contains static references to all the view model in application and provides an entry point for the bindings.

Build the Sample

  1. Start Visual Studio Express 2012 for Windows 8 and select File > Open > Project/Solution.
  2. Go to the directory in which you unzipped the sample. Go to the directory named for the sample, and double-click the Visual Studio Express 2012 for Windows 8 Solution (.sln) file.
  3. Press F7 or use Build > Build Solution to build the sample.

Note: you can use Visual Studio 2013 in Windows 8.1.

Run the sample

To debug the app and then run it, press F5 or use Debug > Start Debugging. To run the app without debugging, press Ctrl+F5 or use Debug > Start Without Debugging.

Related Samples


Similar Articles