// TODO: Should we handle the data changing? 
        //public FacebookSessionLocalSettingsCacheProvider()
        //{
        //    Windows.Storage.ApplicationData.Current.DataChanged += Current_DataChanged;
        //}

        //void Current_DataChanged(ApplicationData sender, object args)
        //{
            
        //}

        //public event Windows.Foundation.TypedEventHandler<FacebookSession, object> SessionChanged;

        // NOTE: This provider must handle changes in the app data over different versions of a Store App. 
        // If we update the SDK and the data format changes, we should automatically migrate to prevent
        // app crashes and poor user experience (i.e. forced to login after app updates).

        public override FacebookSession GetSessionData()
        {
            var settings = ApplicationData.Current.RoamingSettings;
            var composite = (ApplicationDataCompositeValue)settings.Values[key];
            
            if (composite == null)
            {
                return null;
            }

            var session = new FacebookSession
            {
                AccessToken = (string)composite["AccessToken"],
                FacebookId = (string)composite["FacebookId"],
            };

            var expires = (string)composite["Expires"];
            if (!string.IsNullOrEmpty(expires))
            {
                DateTime date;
                if (DateTime.TryParse(expires, out date))
                {
                    session.Expires = date;
                }
            }

            var perms = (string)composite["CurrentPermissions"];
            if (!string.IsNullOrEmpty(perms))
            {
                var p = perms.Split(',');
                session.CurrentPermissions.AddRange(p);
            }

            return session;
        }
 public override void SaveSessionData(FacebookSession data)
 {
     var settings = ApplicationData.Current.RoamingSettings;
     var composite = new ApplicationDataCompositeValue();
     composite["AccessToken"] = data.AccessToken;
     composite["CurrentPermissions"] = string.Join(",", data.CurrentPermissions);
     composite["Expires"] = data.Expires.ToString();
     composite["FacebookId"] = data.FacebookId;
 }
 public override void SaveSessionData(FacebookSession data)
 {
     var serializer = new XmlSerializer(typeof(FacebookSession));
     var store = IsolatedStorageFile.GetUserStoreForApplication();
     using (var stream = store.OpenFile(fileName, FileMode.Create))
     {
         serializer.Serialize(stream, data);
     }
 }
        public override void SaveSessionData(FacebookSession data)
        {
            var serializer = new XmlSerializer(typeof(FacebookSession));
            var store      = IsolatedStorageFile.GetUserStoreForApplication();

            using (var stream = store.OpenFile(fileName, FileMode.Create))
            {
                serializer.Serialize(stream, data);
            }
        }
        public override void SaveSessionData(FacebookSession data)
        {
            var settings  = ApplicationData.Current.RoamingSettings;
            var composite = new ApplicationDataCompositeValue();

            composite["AccessToken"]        = data.AccessToken;
            composite["CurrentPermissions"] = string.Join(",", data.CurrentPermissions);
            composite["Expires"]            = data.Expires.ToString();
            composite["FacebookId"]         = data.FacebookId;
            settings.Values[key]            = composite;
        }
Ejemplo n.º 6
0
 public void Logout()
 {
     try
     {
         FacebookSessionCacheProvider.Current.DeleteSessionData();
     }
     finally
     {
         this.CurrentSession = null;
     }
 }
Ejemplo n.º 7
0
        void logIn(bool show_ui)
        {	
			try{
				Deployment.Current.Dispatcher.BeginInvoke(async () =>
				{
					bool is_opened = false;
					string access_token = null;
					try
					{
						if (!show_ui)
						{
							session = FacebookSessionIsolatedStorageCacheProvider.Current.GetSessionData();
							if (session.AccessToken.Length > 0)
							{
								is_opened = true;
								access_token = session.AccessToken;
							}
						}
						else
						{

							session = await FacebookSessionClient.LoginAsync("publish_stream");
							FacebookSessionIsolatedStorageCacheProvider.Current.SaveSessionData(session);

							is_opened = true;
							access_token = session.AccessToken;
						}
					}
					catch (Exception)
					{

					}

					if (is_opened && access_token != null)
					{
						ADFacebookWP8Impl.sessionOpened(session.AccessToken);
						await updateMyInfo();
						await updateFriendsInfo();
					}
					else
					{
						ADFacebookWP8Impl.sessionClosed();
					}
				});
			} catch (Exception e)
			{
				ADFacebookWP8Impl.sessionClosed();
			}
			
        }
 private async Task Authenticate()
 {
     string message = String.Empty;
     try
     {
         session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream");
         App.AccessToken = session.AccessToken;
         App.FacebookId = session.FacebookId;
         App.fbSession = session;
         Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Pages/FrmFacebookPost.xaml", UriKind.Relative)));
     }
     catch (InvalidOperationException e)
     {
         message = "Login failed! Exception details: " + e.Message;
         MessageBox.Show(message);
     }
 }
Ejemplo n.º 9
0
        public async Task Authenticate()
        {

            try
            {
                _session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream");
                App.AccessToken = _session.AccessToken;
                App.FacebookId = _session.FacebookId;

                Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)));
            }
            catch (InvalidOperationException e)
            {
                var message = "Login failed! Exception details: " + e.Message;
                MessageBox.Show(message);
            }
        }
Ejemplo n.º 10
0
        private async Task AuthenticateFacebook()
        {
            try
            {
                FacebookSession = await App.FacebookSessionClient.LoginAsync("user_about_me");
                App.FacebookAccessToken = FacebookSession.AccessToken;
                App.FacebookId = FacebookSession.FacebookId;
                App.IsFacebookAuthenticated = true;

                Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Register.xaml", UriKind.Relative)));

            }
            catch (InvalidOperationException e)
            {

            }
        }
Ejemplo n.º 11
0
        private async Task Authenticate()
        {
            string message = String.Empty;
            try
            {
                session = await App.FacebookSessionClient.LoginAsync("ads_management, ads_read, basic_info, create_event, create_note, email, export_stream, friends_about_me, friends_actions.books, friends_actions.music, friends_actions.news, friends_actions.video, friends_activities, friends_birthday, friends_checkins, friends_education_history, friends_events, friends_games_activity, friends_groups, friends_hometown, friends_interests, friends_likes, friends_location, friends_notes, friends_online_presence, friends_photo_video_tags, friends_photos, friends_questions, friends_relationship_details, friends_relationships, friends_religion_politics, friends_status, friends_subscriptions, friends_videos, friends_website, friends_work_history, manage_friendlists, manage_notifications, manage_pages, photo_upload, public_profile, publish_actions, publish_checkins, publish_stream, read_friendlists, read_insights, read_mailbox, read_page_mailboxes, read_requests, read_stream, rsvp_event, share_item, sms, status_update, user_about_me, user_actions.books, user_actions.music, user_actions.news, user_actions.video, user_activities, user_birthday, user_checkins, user_education_history, user_events, user_friends, user_games_activity, user_groups, user_hometown, user_interests, user_likes, user_location, user_notes, user_online_presence, user_photo_video_tags, user_photos, user_questions, user_relationship_details, user_relationships, user_religion_politics, user_status, user_subscriptions, user_videos, user_website, user_work_history, video_upload, xmpp_login");
                App.AccessToken = session.AccessToken;
                App.FacebookId = session.FacebookId;

                Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Pages/LandingPage.xaml", UriKind.Relative)));
            }
            catch (InvalidOperationException e)
            {
                message = "Login failed! Exception details: " + e.Message;
                MessageBox.Show(message);
            }
        }
        private async Task Authenticate()
        {
            string message = String.Empty;
            try
            {
                session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream");
                App.AccessToken = session.AccessToken;
                App.FacebookId = session.FacebookId;

                Frame.Navigate(typeof(LandingPage));
            }
            catch (InvalidOperationException e)
            {
                message = "Login failed! Exception details: " + e.Message;
                MessageDialog dialog = new MessageDialog(message);
                dialog.ShowAsync();
            }
        }
Ejemplo n.º 13
0
        private async System.Threading.Tasks.Task Authenticate()
        {
            while (sesion == null)
            {
                string message;
                try
                {
                    sesion = await App.FacebookSessionClient.LoginAsync("email,publish_checkins,publish_actions,friends_online_presence");
                    message = "You are now logged in";
                }
                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }

                //MessageBox.Show(message);
            }
        }
        /// <summary>
        /// Maps a deep link Uri to a navigation within this application
        /// </summary>
        /// <param name="uri">Deep link Uri to map</param>
        /// <returns>Navigation Uri within this app</returns>
        public override Uri MapUri(Uri uri)
        {
            bool response =  Task.Run(() => AppAuthenticationHelper.IsFacebookLoginResponse(uri)).Result;

            // if URI is a facebook login response, handle the deep link (once per invocation)
            if (response)
            {
                FacebookSession session = new FacebookSession();

                try
                {
                    session.ParseQueryString(HttpUtility.UrlDecode(uri.ToString()));

                    // Handle success case

                    // do something with the custom state parameter
                    if (session.State != "custom_state_string")
                    {
                        MessageBox.Show("Unexpected state: " + session.State);
                    }
                    else
                    {
                        // save the token and continue (token is retrieved and used when the app is lauched)
                        SessionStorage.Save(session);
                    }
                }
                catch (Facebook.FacebookOAuthException exc)
                {
                    if (!this.facebookLoginHandled)
                    {
                        // Handle error case
                        MessageBox.Show("Not signed in: " + exc.Message);

                        this.facebookLoginHandled = true;
                    }
                }

                return new Uri("/MainPage.xaml", UriKind.Relative);
            }

            // by default, navigate to the requested uri
            return uri;
        }
        private async Task Authenticate()
        {
            try
            {
                if (!NetworkInterface.GetIsNetworkAvailable())
                {
                    NavigationService.Navigate(!string.IsNullOrEmpty(ReferrerPage)
                        ? new Uri("/" + ReferrerPage, UriKind.Relative)
                        : new Uri("/MainPage.xaml", UriKind.Relative));
                }
                else
                {
                    App.FacebookSessionClient = new FacebookSessionClient(Constants.AppId);
                    Session = await App.FacebookSessionClient.LoginAsync("friends_birthday,friends_photos,email,user_mobile_phone,user_friends,friends_about_me,friends_status,read_friendlists");
                    App.AccessToken = Session.AccessToken;
                    App.FacebookId = Session.FacebookId;

                    if (!string.IsNullOrEmpty(ReferrerPage))
                    {
                        Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/" + ReferrerPage, UriKind.Relative)));
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/FacebookConnect.xaml?" + UriParameter.IsSyncScneario + "=" + IsSync, UriKind.Relative)));
                    }
                }
            }
            catch (InvalidOperationException e)
            {
                AppLog.WriteToLog(DateTime.Now, "Login failed !  Error : " + e.Message + ". Stack : " + e.StackTrace, LogLevel.Error);
                MessageBox.Show(AppResources.FbLoginFailedText, AppResources.FbLoginFailedTitle, MessageBoxButton.OK);
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            }
            catch(Exception ex)
            {
                AppLog.WriteToLog(DateTime.Now, "Login failed !  Error : " + ex.Message + ". Stack : " + ex.StackTrace, LogLevel.Error);
                MessageBox.Show(AppResources.FbLoginFailedText, AppResources.FbLoginFailedTitle, MessageBoxButton.OK);
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Initializes a new instance of the FacebookSession class from a query string with key/value pairs
        /// </summary>
        /// <param name="queryString">
        /// Query to parse
        /// </param>
        public static void ParseQueryString(this FacebookSession session, string queryString)
        {
            if (string.IsNullOrWhiteSpace(queryString))
            {
                throw new InvalidDataException();
            }

            // parse out errors, if any
            var error            = GetQueryStringValueFromUri(queryString, ErrorKey);
            var errorDescription = GetQueryStringValueFromUri(queryString, ErrorDescriptionKey);
            var errorReason      = GetQueryStringValueFromUri(queryString, ErrorReasonKey);

            int errorCodeValue = 0;

            int.TryParse(GetQueryStringValueFromUri(queryString, ErrorCodeKey), out errorCodeValue);

            if (string.IsNullOrEmpty(error) && errorCodeValue == 0)
            {
                // parse out string values
                session.AccessToken = GetQueryStringValueFromUri(queryString, AccessTokenKey);
                session.State       = GetQueryStringValueFromUri(queryString, StateKey);

                // parse out other types
                long expiresInValue;
                if (long.TryParse(GetQueryStringValueFromUri(queryString, ExpiresInKey), out expiresInValue))
                {
                    session.Expires = DateTime.UtcNow + TimeSpan.FromSeconds(expiresInValue);
                }
            }
            else
            {
                throw new FacebookOAuthException(
                          string.Format("{0}: {1}", error, errorDescription),
                          errorReason,
                          errorCodeValue,
                          0);
            }
        }
Ejemplo n.º 17
0
        public static async void Authenticate()
        {
            string message = String.Empty;             
            try
            {
                Console.Write("I am being called ");

                _facebookSession = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream");
                //IsolatedStorageSettings.ApplicationSettings["FacebookAccessToken"] = _facebookSession.AccessToken;
                //IsolatedStorageSettings.ApplicationSettings["FacebookId"] = _facebookSession.FacebookId;
                appSettings.Add("FacebookAccessToken", _facebookSession.AccessToken);
                appSettings.Add("FacebookId", _facebookSession.FacebookId);
                //SaveSettings();
               // IsolatedStorageSettings.ApplicationSettings.Save();
                App.RootFrame.Navigate(new Uri("/ContactsView.xaml", UriKind.Relative));
            }
            catch (InvalidOperationException e)
            {
                MessageBox.Show("Login failed! Exception details: " + e.Message);
                 
            }             
            
        }
        // TODO: Should we handle the data changing?
        //public FacebookSessionLocalSettingsCacheProvider()
        //{
        //    Windows.Storage.ApplicationData.Current.DataChanged += Current_DataChanged;
        //}

        //void Current_DataChanged(ApplicationData sender, object args)
        //{

        //}

        //public event Windows.Foundation.TypedEventHandler<FacebookSession, object> SessionChanged;

        // NOTE: This provider must handle changes in the app data over different versions of a Store App.
        // If we update the SDK and the data format changes, we should automatically migrate to prevent
        // app crashes and poor user experience (i.e. forced to login after app updates).

        public override FacebookSession GetSessionData()
        {
            var settings  = ApplicationData.Current.RoamingSettings;
            var composite = (ApplicationDataCompositeValue)settings.Values[key];

            if (composite == null)
            {
                return(null);
            }

            var session = new FacebookSession
            {
                AccessToken = (string)composite["AccessToken"],
                FacebookId  = (string)composite["FacebookId"],
            };

            var expires = (string)composite["Expires"];

            if (!string.IsNullOrEmpty(expires))
            {
                DateTime date;
                if (DateTime.TryParse(expires, out date))
                {
                    session.Expires = date;
                }
            }

            var perms = (string)composite["CurrentPermissions"];

            if (!string.IsNullOrEmpty(perms))
            {
                var p = perms.Split(',');
                session.CurrentPermissions.AddRange(p);
            }

            return(session);
        }
Ejemplo n.º 19
0
        internal async Task <FacebookSession> LoginAsync(string permissions, bool force)
        {
            if (LoginInProgress)
            {
                throw new InvalidOperationException("Login in progress.");
            }
            LoginInProgress = true;
            try
            {
                var session = FacebookSessionCacheProvider.Current.GetSessionData();
                if (session == null)
                {
                    // Authenticate
                    var authResult = await PromptOAuthDialog(permissions, WebAuthenticationOptions.None);

                    FacebookClient client     = new FacebookClient(authResult.AccessToken);
                    var            parameters = new Dictionary <string, object>();
                    parameters["fields"] = "id";
                    var result = await client.GetTaskAsync("me", parameters);

                    var dict = (IDictionary <string, object>)result;
                    session = new FacebookSession
                    {
                        AccessToken = authResult.AccessToken,
                        Expires     = authResult.Expires,
                        FacebookId  = (string)dict["id"],
                    };
                }
                else
                {
                    // Check if we are requesting new permissions
                    bool newPermissions = false;
                    if (!string.IsNullOrEmpty(permissions))
                    {
                        var p = permissions.Split(',');
                        newPermissions =
                            session.CurrentPermissions.Join(p, s1 => s1, s2 => s2, (s1, s2) => s1).Count() != p.Length;
                    }
                    // Prompt OAuth dialog if force renew is true or
                    // if new permissions are requested or
                    // if the access token is expired.
                    if (force || newPermissions || session.Expires <= DateTime.UtcNow)
                    {
                        var authResult = await PromptOAuthDialog(permissions, WebAuthenticationOptions.None);

                        if (authResult != null)
                        {
                            session.AccessToken = authResult.AccessToken;
                            session.Expires     = authResult.Expires;
                        }
                    }
                }
                // Set the current known permissions
                if (!string.IsNullOrEmpty(permissions))
                {
                    var p = permissions.Split(',');
                    session.CurrentPermissions = session.CurrentPermissions.Union(p).ToList();
                }
                // Save session data
                FacebookSessionCacheProvider.Current.SaveSessionData(session);
            }
            catch (Exception x)
            {
                string msg = x.Message;
            }
            finally
            {
                LoginInProgress = false;
            }
            return(CurrentSession);
        }
 public abstract void SaveSessionData(FacebookSession data);
 /// <summary>
 /// Saves an access token an access token and its expiry
 /// </summary>
 /// <param name="response">A valid login response with access token and expiry</param>
 public static void Save(FacebookSession session)
 {
     SaveEncryptedSettingValue(accessTokenSettingsKeyName, session.AccessToken);
     SaveEncryptedSettingValue(accessTokenExpirySettingsKeyName, session.Expires.Ticks.ToString());
     SaveEncryptedSettingValue(stateSettingsKeyName, session.State);
 }
        internal async Task<FacebookSession> LoginAsync(string permissions, bool force)
        {
            if (this.LoginInProgress)
            {
                throw new InvalidOperationException("Login in progress.");
            }

            this.LoginInProgress = true;
            try
            {
                var session = FacebookSessionCacheProvider.Current.GetSessionData();
                if (session == null)
                {
                    // Authenticate
                    var authResult = await PromptOAuthDialog(permissions, WebAuthenticationOptions.None);

                    FacebookClient client = new FacebookClient(authResult.AccessToken);
                    var parameters = new Dictionary<string, object>();
                    parameters["fields"] = "id";

                    var result = await client.GetTaskAsync("me", parameters);
                    var dict = (IDictionary<string, object>)result;

                    session = new FacebookSession
                    {
                        AccessToken = authResult.AccessToken,
                        Expires = authResult.Expires,
                        FacebookId = (string)dict["id"],
                    };
                  
                }
                else
                {
                    // Check if we are requesting new permissions
                    bool newPermissions = false;
                    if (!string.IsNullOrEmpty(permissions))
                    {
                        var p = permissions.Split(',');
                        newPermissions = session.CurrentPermissions.Join(p, s1 => s1, s2 => s2, (s1, s2) => s1).Count() != p.Length;
                    }

                    // Prompt OAuth dialog if force renew is true or
                    // if new permissions are requested or 
                    // if the access token is expired.
                    if (force || newPermissions || session.Expires <= DateTime.UtcNow)
                    {
                        var authResult = await PromptOAuthDialog(permissions, WebAuthenticationOptions.None);
                        if (authResult != null)
                        {
                            session.AccessToken = authResult.AccessToken;
                            session.Expires = authResult.Expires;
                        }
                    }
                }

                // Set the current known permissions
                if (!string.IsNullOrEmpty(permissions))
                {
                    var p = permissions.Split(',');
                    session.CurrentPermissions = session.CurrentPermissions.Union(p).ToList();
                }

                // Save session data
                FacebookSessionCacheProvider.Current.SaveSessionData(session);
                this.CurrentSession = session;
            }
            finally
            {
                this.LoginInProgress = false;
            }

            return this.CurrentSession;
        }
 public void Logout()
 {
     try
     {
         FacebookSessionCacheProvider.Current.DeleteSessionData();
     }
     finally
     {
         this.CurrentSession = null;
     }
 }
Ejemplo n.º 24
0
 public abstract void SaveSessionData(FacebookSession data);