Thursday, April 14, 2016

Blank view when trying to add facebook login

Leave a Comment

I have followed this guide to implement facebook login and while importing the project from Github I've run into an issue. When I run the project from github it works fine however if I try to copy the code into my existing project I get a white view with no button.

The view:

<Page x:Class="IWork4You.LoginView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:IWork4You" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid>     <WebView x:Name="RequestView" Visibility="Collapsed" Width="400" Height="800" NavigationCompleted="RequestView_OnNavigationCompleted"/>     <StackPanel Margin="0, 0, 0, 0" x:Name="AppContent">         <Button Content="Login" Click="OnLoginClicked" HorizontalAlignment="Center" VerticalAlignment="Center" />         <TextBlock x:Name="MyName" Style="{StaticResource SubheaderTextBlockStyle}" />         <Button Content="Invite friends" Click="OnInviteFriendsClicked" x:Name="InviteFriends" Visibility="Collapsed" />          <TextBlock Text="Invited friends" Style="{StaticResource HeaderTextBlockStyle}" x:Name="FriendsHeader" Visibility="Collapsed"/>         <ListView x:Name="Friends" Margin="0, 20, 0, 0" Visibility="Collapsed">             <ListView.ItemTemplate>                 <DataTemplate>                     <StackPanel>                         <TextBlock Text="{Binding Path=FullName}" Style="{StaticResource BodyTextBlockStyle}" />                     </StackPanel>                 </DataTemplate>             </ListView.ItemTemplate>         </ListView>     </StackPanel> </Grid> 

Code:

namespace IWork4You {     /// <summary>     /// An empty page that can be used on its own or navigated to within a Frame.     /// </summary>     public sealed partial class LoginView : Page     {         public string AccessToken;         public DateTime TokenExpiry;         public string ClientId = "xxx";      private async Task Login()     {         //Client ID of the Facebook App (retrieved from the Facebook Developers portal)         //Required permissions         var scope = "public_profile, email";          var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();         var fb = new FacebookClient();         var loginUrl = fb.GetLoginUrl(new         {             client_id = ClientId,             redirect_uri = redirectUri,             response_type = "token",             scope = scope         });          Uri startUri = loginUrl;         Uri endUri = new Uri(redirectUri, UriKind.Absolute);           WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri);         await ParseAuthenticationResult(result);       }      public async Task ParseAuthenticationResult(WebAuthenticationResult result)     {         switch (result.ResponseStatus)         {             //connection error             case WebAuthenticationStatus.ErrorHttp:                 Debug.WriteLine("Connection error");                 break;             //authentication successfull             case WebAuthenticationStatus.Success:                 var pattern = string.Format("{0}#access_token={1}&expires_in={2}",                     WebAuthenticationBroker.GetCurrentApplicationCallbackUri(), "(?<access_token>.+)",                     "(?<expires_in>.+)");                 var match = Regex.Match(result.ResponseData, pattern);                  var access_token = match.Groups["access_token"];                 var expires_in = match.Groups["expires_in"];                  AccessToken = access_token.Value;                 TokenExpiry = DateTime.Now.AddSeconds(double.Parse(expires_in.Value));                  await ShowUserInfo();                  InviteFriends.Visibility = Visibility.Visible;                  break;             //operation aborted by the user             case WebAuthenticationStatus.UserCancel:                 Debug.WriteLine("Operation aborted");                 break;             default:                 break;         }      }      private async Task ShowUserInfo()     {         FacebookClient client = new FacebookClient(AccessToken);         dynamic user = await client.GetTaskAsync("me");         MyName.Text = string.Format("I'm {0}", user.name);     }      private async void OnLoginClicked(object sender, RoutedEventArgs e)     {         await Login();     }      private void OnInviteFriendsClicked(object sender, RoutedEventArgs e)     {         AppContent.Visibility = Visibility.Collapsed;         FacebookClient client = new FacebookClient(AccessToken);         dynamic parameters = new ExpandoObject();         parameters.app_id = ClientId;         parameters.message = "Invite your friends";         parameters.title = "Invite friends";         parameters.redirect_uri = "https://wp.qmatteoq.com/";          Uri dialogUrl = client.GetDialogUrl("apprequests", parameters);          RequestView.Visibility = Visibility.Visible;         RequestView.Navigate(dialogUrl);     }      private async void RequestView_OnNavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)     {         if (args.Uri.DnsSafeHost == "wp.qmatteoq.com")         {             sender.Visibility = Visibility.Collapsed;             AppContent.Visibility = Visibility.Visible;              FacebookClient client = new FacebookClient(AccessToken);             dynamic result = client.ParseDialogCallbackUrl(args.Uri);              if (result.error_code == null)             {                 var items = (IDictionary<string, object>)result;                  ObservableCollection<FacebookUser> invitedFriends = new ObservableCollection<FacebookUser>();                  foreach (KeyValuePair<string, object> value in items)                 {                     if (value.Key != "request")                     {                         string query = string.Format("/{0}", value.Value);                         dynamic user = await client.GetTaskAsync(query);                         FacebookUser facebookUser = new FacebookUser();                         facebookUser.FullName = user.name;                         invitedFriends.Add(facebookUser);                     }                 }                  Friends.Visibility = Visibility.Visible;                 FriendsHeader.Visibility = Visibility.Visible;                 Friends.ItemsSource = invitedFriends;             }             else             {                 MessageDialog dialog = new MessageDialog("The user has canceled the operation");                 await dialog.ShowAsync();             }         }     } } } 

I know I am doing something wrong here I just can't figure out what it is.

1 Answers

Answers 1

Maybe I'm missing it but you don't seem to be calling InitializeComponent() anywhere.

Something like

public LoginView() {    InitializeComponent(); } 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment