void GetEmailRequestHandler(GraphRequestConnection connection, NSObject result, NSError error) { if (error != null) { completionSource.TrySetResult(new FacebookLoginResult { LoginState = FacebookLoginState.Failed, ErrorString = error.LocalizedDescription }); } else { loginResult.FirstName = Profile.CurrentProfile?.FirstName; loginResult.LastName = Profile.CurrentProfile?.LastName; loginResult.ImageUrl = Profile.CurrentProfile?.ImageUrl(ProfilePictureMode.Square, new CGSize()).ToString(); var dict = result as NSDictionary; var emailKey = new NSString(@"email"); if (dict != null && dict.ContainsKey(emailKey)) { loginResult.Email = dict[emailKey]?.ToString(); } loginResult.LoginState = FacebookLoginState.Success; completionSource.TrySetResult(loginResult); } }
async System.Threading.Tasks.Task doAGraphReqest_Photo(string text, string publishToken, EventHandler <bool> done) { try { BasicFacebookProfileInfo facebookProfile = await this.GetBasicProfileInfo(); var parameters = new NSDictionary("picture", UIImage.FromFile("logo-512x512.png").AsPNG(), "caption", text); string userID = facebookProfile.Id; string graphPath = "/" + userID + "/photos"; var request = new Facebook.CoreKit.GraphRequest(graphPath, parameters, publishToken, null, "POST"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(request, (connection, result1, error1) => { if (error1 != null) { done(this, false); return; } string id = (result1 as NSDictionary)["post_id"].ToString(); }); requestConnection.Start(); } catch (Exception) { done(this, false); } }
private void FacebookLoggedIn(string userId) { var fields = "?fields=id,name,email,first_name,last_name,picture"; var request = new GraphRequest("/" + userId + fields, null, Facebook.CoreKit.AccessToken.CurrentAccessToken.TokenString, null, "GET"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(request, (connection, result, error) => { if (error != null) { HideLoadingView(); //new UIAlertView("Error...", error.Description, null, "Ok", null).Show(); ShowMessageBox(Constants.STR_LOGIN_FAIL_TITLE, Constants.STR_LOGIN_FAIL_MSG); return; } var userInfo = (NSDictionary)result; var user = new User(); user.Firstname = userInfo["first_name"].ToString(); user.Lastname = userInfo["last_name"].ToString(); user.Email = userInfo["email"].ToString(); user.Password = userInfo["email"].ToString(); user.Type = Constants.TAG_VISIBLE_SPECIFIC; var tmp1 = (NSDictionary)userInfo["picture"]; var tmp2 = (NSDictionary)tmp1["data"]; ParseLogin(user); }); requestConnection.Start(); }
// Revoke all the permissions that you had granted, you will need to login again for ask the permissions again // You can also revoke a single permission, for more info, visit this link: // https://developers.facebook.com/docs/facebook-login/permissions/v2.3#revoking void RevokeAllPermissions(string userId) { // Create the request for delete all the permissions var request = new GraphRequest("/" + userId + "/permissions", null, AccessToken.CurrentAccessToken.TokenString, null, "DELETE"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(request, (connection, result, error) => { // Handle if something went wrong if (error != null) { ShowMessageBox("Error...", error.Description, "Ok", null, null); return; } // If the revoking was successful, logout from FB if ((result as NSDictionary) ["success"].ToString() == "1") { InvokeOnMainThread(() => { ShowMessageBox("Successful", "All permissions have been revoked", "Ok", null, null); var login = new LoginManager(); login.LogOut(); LoggedOut(); }); } else { InvokeOnMainThread(() => ShowMessageBox("Ups...", "A problem has ocurred", "Ok", null, null)); } }); requestConnection.Start(); }
/// <summary> /// Get user data from facebook /// </summary> /// <param name="callback"></param> public void GetUserData(IFacebookDataCallback callback) { this.FacebookDataCallback = callback; var accessToken = AccessToken.CurrentAccessToken; FacebookResult = new FacebookResult(); FacebookResult.Token = accessToken.TokenString; NSMutableDictionary keyValues = new NSMutableDictionary(); keyValues.Add(new NSString("fields"), new NSString(FacebookService.Fields)); GraphRequest graphRequest = new GraphRequest("me", keyValues, AccessToken.CurrentAccessToken.TokenString, null, HttpMethod.Get); GraphRequestConnection graphRequestConnection = new GraphRequestConnection(); graphRequestConnection.AddRequest(graphRequest, (connection, result, error) => { if (error != null) { FacebookDataCallback.OnDataReceivedError(error.ToString()); return; } JsonConvert.PopulateObject(result.ToString(), FacebookResult); FacebookDataCallback.OnUserDataReceived(FacebookResult); }); }
public PhotoViewController() : base(UITableViewStyle.Grouped, null, true) { // Add the image that will be publish var imageView = new UIImageView (new CGRect (0, 0, View.Frame.Width, 220)) { Image = UIImage.FromFile ("wolf.jpg") }; // Add a textbox that where you will be able to add a comment to the photo txtMessage = new EntryElement ("", "Say something nice!", ""); Root = new RootElement ("Post photo!") { new Section () { new UIViewElement ("", imageView, true) { Flags = UIViewElement.CellFlags.DisableSelection | UIViewElement.CellFlags.Transparent, }, txtMessage } }; // Create the request to post a photo into your wall NavigationItem.RightBarButtonItem = new UIBarButtonItem ("Post", UIBarButtonItemStyle.Plain, ((sender, e) => { // Disable the post button for prevent another untill the actual one finishes (sender as UIBarButtonItem).Enabled = false; // Add the photo and text that will be publish var parameters = new NSDictionary ("picture", UIImage.FromFile ("wolf.jpg").AsPNG (), "caption", txtMessage.Value); // Create the request var request = new GraphRequest ("/" + Profile.CurrentProfile.UserID + "/photos", parameters, AccessToken.CurrentAccessToken.TokenString, null, "POST"); var requestConnection = new GraphRequestConnection (); requestConnection.AddRequest (request, (connection, result, error) => { // Enable the post button (sender as UIBarButtonItem).Enabled = true; // Handle if something went wrong if (error != null) { new UIAlertView ("Error...", error.Description, null, "Ok", null).Show (); return; } // Do your magic if the request was successful new UIAlertView ("Yay!!", "Your photo was published!", null, "Ok", null).Show (); photoId = (result as NSDictionary) ["post_id"].ToString (); // Add a button to allow to delete the photo posted Root.Add (new Section () { new StyledStringElement ("Delete Post", DeletePost) { Alignment = UITextAlignment.Center, TextColor = UIColor.Red } }); }); requestConnection.Start (); })); }
// Post and delete the "Hello!" from user wall void PostHello() { // Verify if you have permissions to post into user wall, // if not, ask to user if he/she wants to let your app post things for them if (!AccessToken.CurrentAccessToken.HasGranted("publish_actions")) { AskPermissions("Post Hello", "Would you like to let this app to post a \"Hello\" for you?", new [] { "publish_actions" }, PostHello); return; } // Once you have the permissions, you can publish or delete the post from your wall GraphRequest request; if (!isHelloPosted) { request = new GraphRequest("me/feed", new NSDictionary("message", "Hello!"), AccessToken.CurrentAccessToken.TokenString, null, "POST"); } else { request = new GraphRequest(helloId, null, AccessToken.CurrentAccessToken.TokenString, null, "DELETE"); } var requestConnection = new GraphRequestConnection(); // Handle the result of the request requestConnection.AddRequest(request, (connection, result, error) => { // Handle if something went wrong if (error != null) { ShowMessageBox("Error...", error.Description, "Ok", null, null); return; } // Post the Hello! to your wall if (!isHelloPosted) { helloId = (result as NSDictionary) ["id"].ToString(); isHelloPosted = true; InvokeOnMainThread(() => { strPostHello.Caption = "Delete \"Hello\" from your wall"; Root.Reload(strPostHello, UITableViewRowAnimation.Left); ShowMessageBox("Success!!", "Posted Hello in your wall, MsgId: " + helloId, "Ok", null, null); }); } else // Delete the Hello! from your wall { helloId = ""; isHelloPosted = false; InvokeOnMainThread(() => { strPostHello.Caption = "Post \"Hello\" on your wall"; Root.Reload(strPostHello, UITableViewRowAnimation.Left); ShowMessageBox("Success", "Deleted Hello from your wall", "Ok", null, null); }); } }); requestConnection.Start(); }
void RequestUserData(Dictionary <string, object> fieldsDictionary) { string[] fields = new string[] { }; var extraParams = string.Empty; if (fieldsDictionary != null && fieldsDictionary.ContainsKey("fields")) { fields = fieldsDictionary["fields"] as string[]; if (fields.Length > 0) { extraParams = $"?fields={string.Join(",", fields)}"; } } //email,first_name,gender,last_name,birthday if (AccessToken.CurrentAccessToken != null) { Dictionary <string, object> userData = new Dictionary <string, object>(); var graphRequest = new GraphRequest($"/me{extraParams}", null, AccessToken.CurrentAccessToken.TokenString, null, "GET"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(graphRequest, (connection, result, error) => { if (error == null) { NSData responseData = NSJsonSerialization.Serialize(result, NSJsonWritingOptions.PrettyPrinted, out NSError jsonError); if (jsonError == null) { NSString responseString = NSString.FromData(responseData, NSStringEncoding.UTF8); var fbResponse = new FBEventArgs <string>(responseString, FacebookActionStatus.Completed); OnUserData?.Invoke(this, fbResponse); _userDataTcs?.TrySetResult(new FacebookResponse <string>(fbResponse)); } else { var fbResponse = new FBEventArgs <string>(null, FacebookActionStatus.Error, $" Facebook response parse failed - {jsonError.Code} - {jsonError.Description}"); OnUserData?.Invoke(this, fbResponse); _userDataTcs?.TrySetResult(new FacebookResponse <string>(fbResponse)); } } else { var fbArgs = new FBEventArgs <string>(null, FacebookActionStatus.Error, $"Facebook User Data Request Failed - {error.Code} - {error.Description}"); OnUserData?.Invoke(this, fbArgs); _userDataTcs?.TrySetResult(new FacebookResponse <string>(fbArgs)); } }); requestConnection.Start(); } else { var fbArgs = new FBEventArgs <string>(null, FacebookActionStatus.Canceled, "User cancelled facebook operation"); OnUserData?.Invoke(this, null); _userDataTcs?.TrySetResult(new FacebookResponse <string>(fbArgs)); } }
private void GetFacebookData() { GraphRequest gr = new GraphRequest("/me", null, "GET"); gr.Parameters.Add(NSObject.FromObject("fields"), NSObject.FromObject("id,name,email")); GraphRequestConnection rc = new GraphRequestConnection(); rc.AddRequest(gr, DataRequestHandler); rc.Start(); }
public async Task<List<string>> getFacebookFriends() { TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(); List<string> friendsIDs = new List<string>(); var request = new GraphRequest("/"+App.StoredUserFacebookId+"/friends", null, App.StoredToken, null, "GET"); var requestConnection = new GraphRequestConnection(); var fbEvents = new List<FaceBookEvent>(); requestConnection.AddRequest(request, (connection, result, error) => { if (error != null) { System.Diagnostics.Debug.WriteLine("Hnnn2"); new UIAlertView("Error...", error.Description, null, "Ok", null).Show(); return; } NSDictionary userInfo = (result as NSDictionary); NSObject IDs; var success = userInfo.TryGetValue(new NSString("data"), out IDs); String s = IDs.ToString(); try { while (s.Contains(" = ")) { int start = s.IndexOf(" = "); int end = s.IndexOf(";"); //System.Diagnostics.Debug.WriteLine(start + ", " + end + ":" + s.Substring((start + 3), (end - start-3)) + ":"); friendsIDs.Add(s.Substring((start + 3), (end - start - 3))); s = s.Substring(s.IndexOf("}")+1); //System.Diagnostics.Debug.WriteLine(s); } } catch (Exception e) {} //System.Diagnostics.Debug.WriteLine("HEY"); if (error != null) { } tcs.TrySetResult(true); }); requestConnection.Start(); await tcs.Task; return friendsIDs; }
private async void ProcessFacebookLogin() { LoginManagerLoginResult result = await loginManager.LogInWithReadPermissionsAsync(readPermissions.ToArray(), this); if (result.IsCancelled) { UserDialogs.Instance.Alert("User cancelled Facebook Login", "ThisRoof"); return; } if (result.GrantedPermissions != null && result.GrantedPermissions.Contains("email")) { string NAME = "name"; string ID = "id"; string EMAIL = "email"; string FIELDS = "fields"; string REQUEST_FIELDS = String.Join(",", new string[] { NAME, ID, EMAIL }); UserDialogs.Instance.ShowLoading(); var request = new GraphRequest("me", new NSDictionary(FIELDS, REQUEST_FIELDS), AccessToken.CurrentAccessToken.TokenString, null, "GET"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(request, (connection, graphResult, error) => { UserDialogs.Instance.HideLoading(); if (error != null || graphResult == null) { // Error Handler UserDialogs.Instance.Alert(String.Format("Facebook Login Error:{0}", error.Description), "ThisRoof"); } else { string email = (graphResult as NSDictionary) ["email"].ToString(); FBUserInfo userInfo = new FBUserInfo() { UserEmail = email, UserID = AccessToken.CurrentAccessToken.UserID, UserToken = AccessToken.CurrentAccessToken.TokenString }; ViewModelInstance.FacebookLoginCommand.Execute(userInfo); // after get user info we logout again. loginManager.LogOut(); } }); requestConnection.Start(); } else { UserDialogs.Instance.Alert("Email Permission is not allowed", "ThisRoof"); } }
void GetLikesRequestHandler(GraphRequestConnection connection, NSObject result, NSError error) { if (error != null) { _completionSource.TrySetResult(new LoginResult { LoginState = LoginState.Failed, ErrorString = error.LocalizedDescription }); } else { var likes = result.ValueForKey((NSString)"fan_count"); } }
void RequestUserData(Dictionary <string, object> fieldsDictionary) { string[] fields = new string[] { }; var extraParams = string.Empty; if (fieldsDictionary != null && fieldsDictionary.ContainsKey("fields")) { fields = fieldsDictionary["fields"] as string[]; if (fields.Length > 0) { extraParams = $"?fields={string.Join(",", fields)}"; } } //email,first_name,gender,last_name,birthday if (AccessToken.CurrentAccessToken != null) { Dictionary <string, object> userData = new Dictionary <string, object>(); var graphRequest = new GraphRequest($"/me{extraParams}", null, AccessToken.CurrentAccessToken.TokenString, null, "GET"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(graphRequest, (connection, result, error) => { if (error == null) { for (int i = 0; i < fields.Length; i++) { userData.Add(fields[i], $"{result.ValueForKey(new NSString(fields[i]))}"); } userData.Add("user_id", AccessToken.CurrentAccessToken.UserID); userData.Add("token", AccessToken.CurrentAccessToken.TokenString); var fbArgs = new FBEventArgs <Dictionary <string, object> >(userData, FacebookActionStatus.Completed); OnUserData(this, fbArgs); _userDataTcs?.TrySetResult(new FacebookResponse <Dictionary <string, object> >(fbArgs)); } else { var fbArgs = new FBEventArgs <Dictionary <string, object> >(null, FacebookActionStatus.Error, $"Facebook User Data Request Failed - {error.Code} - {error.Description}"); OnUserData(this, fbArgs); _userDataTcs?.TrySetResult(new FacebookResponse <Dictionary <string, object> >(fbArgs)); } }); requestConnection.Start(); } else { var fbArgs = new FBEventArgs <Dictionary <string, object> >(null, FacebookActionStatus.Canceled, "User cancelled facebook operation"); OnUserData(this, null); _userDataTcs?.TrySetResult(new FacebookResponse <Dictionary <string, object> >(fbArgs)); } }
private void FacebookLoggedIn(string userId) { ShowLoadingView("Getting some user data..."); var fields = "?fields=id,name,email,first_name,last_name,picture"; var request = new GraphRequest("/" + userId + fields, null, Facebook.CoreKit.AccessToken.CurrentAccessToken.TokenString, null, "GET"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(request, (connection, result, error) => { if (error != null) { HideLoadingView(); //new UIAlertView("Error...", error.Description, null, "Ok", null).Show(); new UIAlertView("Login Failed", "The social network login failed for your account", null, "Ok", null).Show(); return; } var userInfo = (NSDictionary)result; AppSettings.LoginType = (int)LoginType.Facebook; AppSettings.UserType = ""; AppSettings.UserFirstName = userInfo["first_name"].ToString(); AppSettings.UserLastName = userInfo["last_name"].ToString(); AppSettings.UserEmail = userInfo["email"].ToString(); var tmp1 = (NSDictionary)userInfo["picture"]; var tmp2 = (NSDictionary)tmp1["data"]; AppSettings.UserPhoto = tmp2["url"].ToString(); AppSettings.UserToken = GetMd5Hash(md5Hash, userInfo["email"].ToString()); ////we got all the data we need at this point, FB login successful UserTrackingReporter.TrackUser(Constant.CATEGORY_LOGIN, "Facebook login completed"); bool registerSuccessful = false; Task runSync = Task.Factory.StartNew(async() => { registerSuccessful = await RegisterUser(); }).Unwrap(); runSync.Wait(); if (!registerSuccessful) { GoToCreateAccountScreen(); return; } ShowHomeScreen(); }); requestConnection.Start(); }
public void GetUserInfo() { var request = new GraphRequest("/me", null, AccessToken.CurrentAccessToken.TokenString, string.Empty, "GET"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(request, (connection, result, error) => { Settings.FacebookProfileId = result.ValueForKeyPath(new NSString("id")).ToString(); Settings.FacebookProfileName = result.ValueForKeyPath(new NSString("name")).ToString(); Xamarin.Forms.MessagingCenter.Send(new object(), "connected"); }); requestConnection.Start(); }
public ListDetailViewController(string listId, string listName, FacebookListType type) : base(UITableViewStyle.Grouped, null, true) { Root = new RootElement(listName); // Ask for the members within the group var request = new GraphRequest("/" + listId + "/members?fields=id,name", null, AccessToken.CurrentAccessToken.TokenString, null, "GET"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(request, (connection, result, error) => { // Handle if something went wrong if (error != null) { new UIAlertView("Error...", error.Description, null, "Ok", null).Show(); return; } // Get the name and the userId of all the memebers NSArray membersData = (result as NSDictionary) ["data"] as NSArray; var listSection = new List <Section> (); // Add the name and the picture profile to the view for (nuint i = 0; i < membersData.Count; i++) { // Get the info of one of the members var memberData = membersData.GetItem <NSDictionary> (i); var pictureView = new ProfilePictureView(new CGRect(48, 0, 220, 220)) { ProfileId = memberData ["id"].ToString(), TranslatesAutoresizingMaskIntoConstraints = false }; listSection.Add(new Section(memberData ["name"].ToString()) { new UIViewElement("", pictureView, true) { Flags = UIViewElement.CellFlags.DisableSelection | UIViewElement.CellFlags.Transparent } }); } Root = new RootElement(listName) { listSection }; }); requestConnection.Start(); }
public Task <bool> PostPhoto(ImageSource image) { var tcsPhoto = new TaskCompletionSource <bool>(); var token = AccessToken.CurrentAccessToken?.TokenString; if (string.IsNullOrWhiteSpace(token)) { tcsPhoto.TrySetResult(false); } else { bool hasRights; if (!AccessToken.CurrentAccessToken.HasGranted("publish_actions")) { hasRights = RequestPublishPermissions(new[] { "publish_actions" }).Result; } else { hasRights = true; } if (hasRights) { var handler = image.GetHandler(); var nativeImage = handler.LoadImageAsync(image).Result; var parameters = new NSDictionary("picture", nativeImage.AsPNG()); var request = new GraphRequest("/" + AccessToken.CurrentAccessToken.UserID + "/photos", parameters, AccessToken.CurrentAccessToken.TokenString, null, "POST"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(request, (connection, result, error) => { if (error != null) { tcsPhoto.TrySetResult(false); return; } tcsPhoto.TrySetResult(true); }); requestConnection.Start(); } else { tcsPhoto.TrySetResult(hasRights); } } return(tcsPhoto.Task); }
void AddUserInfoSection(string userId) { // Ask for the info that the user allowed to show var fields = "?fields=id,name,email,birthday,about,hometown"; var request = new GraphRequest("/" + userId + fields, null, AccessToken.CurrentAccessToken.TokenString, null, "GET"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(request, (connection, result, error) => { // Handle if something went wrong with the request if (error != null) { new UIAlertView("Error...", error.Description, null, "Ok", null).Show(); return; } NSDictionary userInfo = (result as NSDictionary); var userSection = new Section(userInfo ["name"].ToString()); // Show the info user that allowed to show // If the user haven't assigned anything to his/her information, // it will be null even if the user allowed to show it. if (userInfo ["email"] != null) { userSection.Add(new StringElement("Email: " + userInfo ["email"].ToString())); } if (userInfo ["birthday"] != null) { userSection.Add(new StringElement("Birthday: " + userInfo ["birthday"].ToString())); } if (userInfo ["about"] != null) { userSection.Add(new StringElement("About: " + userInfo ["about"].ToString())); } if (userInfo ["hometown"] != null) { var hometownData = userInfo ["hometown"] as NSDictionary; userSection.Add(new StringElement("Hometown: " + hometownData ["name"])); } Root.Add(userSection); // Add the allowed actions that user have granted AddActionsSection(); }); requestConnection.Start(); }
public void DataRequestHandler(GraphRequestConnection connection, NSObject result, NSError err) { try { string fbId = result.ValueForKey(new NSString("id")).ToString(); string fbToken = AccessToken.CurrentAccessToken.TokenString; string fbEmail = result.ValueForKey(new NSString("email")).ToString(); _email = fbEmail; // Create a new cancellation token for this request _cts0 = new CancellationTokenSource(); AppController.LoginUser(_cts0, fbId, fbEmail, fbToken, // Service call success (data) => { AppController.Settings.LastLoginUsernameUsed = _email; AppController.Settings.AuthAccessToken = data.AuthAccessToken; AppController.Settings.AuthExpirationDate = data.AuthExpirationDate.GetValueOrDefault().ToLocalTime(); ((AppDelegate)UIApplication.SharedApplication.Delegate).RegisterToNotificationsHub(); var c = new ChatViewController(); c.Arguments = new UIBundle(); c.Arguments.PutString("Email", _email); this.NavigationController.PushViewController(c, true); }, // Service call error (error) => { UIToast.MakeText(error, UIToastLength.Long).Show(); }, // Service call finished () => { // Allow user to tap views ((MainViewController)this.MainViewController).UnblockUI(); }); } catch (Exception ex) { ((MainViewController)this.MainViewController).UnblockUI(); UIToast.MakeText("Error", UIToastLength.Long).Show(); } }
public Task <bool> PostText(string message) { var tcs = new TaskCompletionSource <bool>(); var token = AccessToken.CurrentAccessToken?.TokenString; if (string.IsNullOrWhiteSpace(token)) { tcs.TrySetResult(false); } else { bool hasRights; if (!AccessToken.CurrentAccessToken.HasGranted("publish_actions")) { hasRights = RequestPublishPermissions(new[] { "publish_actions" }).Result; } else { hasRights = true; } if (hasRights) { GraphRequest request = new GraphRequest("me/feed", new NSDictionary("message", message), AccessToken.CurrentAccessToken.TokenString, null, "POST"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(request, (connection, result, error) => { if (error != null) { tcs.TrySetResult(false); return; } tcs.TrySetResult(true); }); requestConnection.Start(); } else { tcs.TrySetResult(hasRights); } } return(tcs.Task); }
void GetEmailRequestHandler(GraphRequestConnection connection, NSObject result, NSError error) { if (error != null || _loginResult == null) { _completionSource?.TrySetResult(new LoginResult { LoginState = LoginState.Failed, ErrorString = _loginResult == null ? "Invalid login sequence": error?.LocalizedDescription }); } else { var dict = result as NSDictionary; if (dict != null) { var key = new NSString(@"email"); if (dict.ContainsKey(key)) { _loginResult.Email = dict[key]?.ToString(); } key = new NSString(@"first_name"); if (dict.ContainsKey(key)) { _loginResult.FirstName = dict[key]?.ToString(); } key = new NSString(@"last_name"); if (dict.ContainsKey(key)) { _loginResult.LastName = dict[key]?.ToString(); } key = new NSString(@"picture"); if (dict.ContainsKey(key)) { _loginResult.ImageUrl = dict[key]?.ValueForKeyPath(new NSString("data"))?.ValueForKey(new NSString("url"))?.ToString(); } } _loginResult.LoginState = LoginState.Success; _completionSource?.TrySetResult(_loginResult); } }
public ListDetailViewController (string listId, string listName, FacebookListType type) : base (UITableViewStyle.Grouped, null, true) { Root = new RootElement (listName); // Ask for the members within the group var request = new GraphRequest ("/" + listId + "/members?fields=id,name", null, AccessToken.CurrentAccessToken.TokenString, null, "GET"); var requestConnection = new GraphRequestConnection (); requestConnection.AddRequest (request, (connection, result, error) => { // Handle if something went wrong if (error != null) { new UIAlertView ("Error...", error.Description, null, "Ok", null).Show (); return; } // Get the name and the userId of all the memebers NSArray membersData = (result as NSDictionary) ["data"] as NSArray; var listSection = new List<Section> (); // Add the name and the picture profile to the view for (nuint i = 0; i < membersData.Count; i++) { // Get the info of one of the members var memberData = membersData.GetItem<NSDictionary> (i); var pictureView = new ProfilePictureView (new CGRect (48, 0, 220, 220)) { ProfileId = memberData ["id"].ToString (), TranslatesAutoresizingMaskIntoConstraints = false }; listSection.Add (new Section (memberData ["name"].ToString ()) { new UIViewElement ("", pictureView, true) { Flags = UIViewElement.CellFlags.DisableSelection | UIViewElement.CellFlags.Transparent } }); } Root = new RootElement (listName) { listSection }; }); requestConnection.Start (); }
// Delete the photo posted from your wall void DeletePost() { // Create the request to delete the post var request = new GraphRequest("/" + photoId, null, AccessToken.CurrentAccessToken.TokenString, null, "DELETE"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(request, (connection, result, error) => { // Handle if something went wrong if (error != null) { new UIAlertView("Error...", error.Description, null, "Ok", null).Show(); return; } // Do your magin is the request was successful new UIAlertView("Post Deleted", "Success", null, "OK", null).Show(); NavigationController.PopViewController(true); }); requestConnection.Start(); }
public ListViewController(FacebookListType type) : base(UITableViewStyle.Grouped, null, true) { var kindListName = type == FacebookListType.Friends ? "friendlists?fields=id,name" : "groups?fields=id,name"; Root = new RootElement(type == FacebookListType.Friends ? "Friendlists" : "Managed Groups"); // Depends of what you want to see, list all your groups or all your friendslist that you have var request = new GraphRequest("/" + Profile.CurrentProfile.UserID + "/" + kindListName, null, AccessToken.CurrentAccessToken.TokenString, null, "GET"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(request, (connection, result, error) => { // Handle if something went wrong if (error != null) { new UIAlertView("Error...", error.Description, null, "Ok", null).Show(); return; } // Get all the info of all the friends or group list that you belong NSArray listsData = (result as NSDictionary) ["data"] as NSArray; var listSection = new Section(); for (nuint i = 0; i < listsData.Count; i++) { var data = listsData.GetItem <NSDictionary> (i); listSection.Add(new StringElement(data ["name"].ToString(), () => { // Ask for all the FB user members that belong to the groups // For security reasons, FB doesn't let you see who is in your friendlist anymore if (type == FacebookListType.Groups) { NavigationController.PushViewController(new ListDetailViewController(data ["id"].ToString(), data ["name"].ToString(), type), true); } })); } Root.Add(listSection); }); requestConnection.Start(); }
// public IGraphRequest NewRequest(IAccessToken token, string path, string parameters, string httpMethod = default(string), string version = default(string)) { //// _token = (token as iOSAccessToken).ToNative (); //// Path = path; //// HttpMethod = httpMethod; //// Version = version; // // // Assume parameters are for the "field" key // // TODO: Let parameters be a Dictionary<string,string> bc there are more keys. // Foundation.NSDictionary dict = new Foundation.NSDictionary("fields", parameters); // //// _request = new GraphRequest (Path, dict, _token.TokenString, HttpMethod, Version); // // Initialize (token, path, dict, httpMethod, version); // // return this; // } public Task <IGraphResponse> ExecuteAsync() { TaskCompletionSource <IGraphResponse> tcs = new TaskCompletionSource <IGraphResponse> (); var handler = new GraphRequestHandler((connection, result, error) => { // System.Diagnostics.Debug.WriteLine(result); tcs.SetResult(new iOSGraphResponse((NSMutableDictionary)result)); }); _connection = new GraphRequestConnection(); _connection.AddRequest(_request, handler); _connection.Failed += (sender, e) => { System.Diagnostics.Debug.WriteLine("Request failed"); tcs.SetCanceled(); }; _connection.Start(); return(tcs.Task); }
public Task <FacebookResponse> GetPosts() { _task = new TaskCompletionSource <FacebookResponse>(); //"fields", "picture" var request = new GraphRequest("/admicleon/posts?fields=from,full_picture,permalink_url,message,story,created_time&locale=es", new NSDictionary(), "203591490120675|a909222218ad39a1de0767ea41a679b1", null, "GET"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(request, (connection, result, error) => { try { var jsonData = NSJsonSerialization.Serialize(result, 0, out error); if (error == null) { var jsonString = (string)NSString.FromData(jsonData, NSStringEncoding.UTF8); var response = Newtonsoft.Json.JsonConvert.DeserializeObject <FacebookResponse>(jsonString); _task.SetResult(response); } else { _task.SetResult(null); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); _task.SetResult(null); } }); requestConnection.Start(); return(_task.Task); }
private void GetUserInfo(List <string> fields, FacebookSession facebookSession, TaskCompletionSource <OperationResult <FacebookSession> > taskCompletionSource) { var builder = new StringBuilder(); fields.ForEach(m => { builder.Append($"{m},"); }); var s = builder.ToString(); if (!String.IsNullOrWhiteSpace(s)) { s = s.Substring(0, s.Length - 1); } var graphRequest = new GraphRequest($"/me?fields={s}", null, facebookSession.Token, null, "GET"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(graphRequest, (connection, result, error) => { if (error != null) { taskCompletionSource.SetResult( OperationResult <FacebookSession> .AsFailure(new ApplicationException(error.LocalizedDescription))); return; } var r = result as NSDictionary; var jsonData = r.ToDictionary(); facebookSession.Data = JObject.FromObject(jsonData); taskCompletionSource.SetResult(OperationResult <FacebookSession> .AsSuccess(facebookSession)); }); requestConnection.Start(); }
private void GetDetailsRequestHandler(GraphRequestConnection connection, NSObject result, NSError error) { if (error != null) { _completionSource.TrySetResult(new LoginResult ( LoginState.Failed, null, error.LocalizedDescription )); } else { var userProfile = new UserProfile( Profile.CurrentProfile.FirstName, Profile.CurrentProfile.LastName, Profile.CurrentProfile.ImageUrl(ProfilePictureMode.Square, new CGSize(200, 200)).ToString() ); _completionSource.TrySetResult(new LoginResult(LoginState.Success, userProfile)); } }
public ListViewController (FacebookListType type) : base (UITableViewStyle.Grouped, null, true) { var kindListName = type == FacebookListType.Friends ? "friendlists?fields=id,name" : "groups?fields=id,name"; Root = new RootElement (type == FacebookListType.Friends ? "Friendlists" : "Managed Groups"); // Depends of what you want to see, list all your groups or all your friendslist that you have var request = new GraphRequest ("/" + Profile.CurrentProfile.UserID + "/" + kindListName, null, AccessToken.CurrentAccessToken.TokenString, null, "GET"); var requestConnection = new GraphRequestConnection (); requestConnection.AddRequest (request, (connection, result, error) => { // Handle if something went wrong if (error != null) { new UIAlertView ("Error...", error.Description, null, "Ok", null).Show (); return; } // Get all the info of all the friends or group list that you belong NSArray listsData = (result as NSDictionary) ["data"] as NSArray; var listSection = new Section (); for (nuint i = 0; i < listsData.Count; i++) { var data = listsData.GetItem <NSDictionary> (i); listSection.Add (new StringElement (data ["name"].ToString (), () => { // Ask for all the FB user members that belong to the groups // For security reasons, FB doesn't let you see who is in your friendlist anymore if (type == FacebookListType.Groups) NavigationController.PushViewController (new ListDetailViewController (data ["id"].ToString (), data ["name"].ToString (), type), true); })); } Root.Add (listSection); }); requestConnection.Start (); }
void AddUserInfoSection (string userId) { // Ask for the info that the user allowed to show var fields = "?fields=id,name,email,birthday,about,hometown"; var request = new GraphRequest ("/" + userId + fields, null, AccessToken.CurrentAccessToken.TokenString, null, "GET"); var requestConnection = new GraphRequestConnection (); requestConnection.AddRequest (request, (connection, result, error) => { // Handle if something went wrong with the request if (error != null) { new UIAlertView ("Error...", error.Description, null, "Ok", null).Show (); return; } NSDictionary userInfo = (result as NSDictionary); var userSection = new Section (userInfo ["name"].ToString ()); // Show the info user that allowed to show // If the user haven't assigned anything to his/her information, // it will be null even if the user allowed to show it. if (userInfo ["email"] != null) userSection.Add (new StringElement ("Email: " + userInfo ["email"].ToString ())); if (userInfo ["birthday"] != null) userSection.Add (new StringElement ("Birthday: " + userInfo ["birthday"].ToString ())); if (userInfo ["about"] != null) userSection.Add (new StringElement ("About: " + userInfo ["about"].ToString ())); if (userInfo ["hometown"] != null) userSection.Add (new StringElement ("Hometown: " + userInfo ["hometown"].ToString ())); Root.Add (userSection); // Add the allowed actions that user have granted AddActionsSection (); }); requestConnection.Start (); }
// Post a "Hello!" into user wall void PostHello () { if (isHelloPosted) { InvokeOnMainThread (() => new UIAlertView ("Error", "Hello already posted on your wall", null, "Ok", null).Show ()); return; } // Verify if you have permissions to post into user wall, // if not, ask to user if he/she wants to let your app post thing for them if (!AccessToken.CurrentAccessToken.Permissions.Contains ("publish_actions")) { var alertView = new UIAlertView ("Post Hello", "Would you like to let this app to post a \"Hello\" for you?", null, "Maybe later", new [] { "Ok" }); alertView.Clicked += (sender, e) => { if (e.ButtonIndex == 1) return; // If they let you post thing, ask a new loggin with publish permissions var login = new LoginManager (); login.LogInWithPublishPermissions (new [] { "publish_actions" }, (result, error) => { if (error != null) { new UIAlertView ("Error...", error.Description, null, "Ok", null).Show (); return; } PostHello (); }); }; alertView.Show (); } else { // Once you have the permissions, you can publish into user wall var request = new GraphRequest ("me/feed", new NSDictionary ("message", "Hello!"), AccessToken.CurrentAccessToken.TokenString, null, "POST"); var requestConnection = new GraphRequestConnection (); // Handle the result of the request requestConnection.AddRequest (request, (connection, result, error) => { if (error != null) { new UIAlertView ("Error...", error.Description, null, "Ok", null).Show (); return; } helloId = (result as NSDictionary)["id"].ToString (); new UIAlertView ("Success!!", "Posted Hello in your wall, MsgId: " + helloId, null, "Ok", null).Show (); isHelloPosted = true; }); requestConnection.Start (); } }
// Delete the last Xamarin.com shared void DeleteSharedPost () { if (!isXamarinShared) { new UIAlertView ("Error", "Please Share \"Xamarin.com\" to your wall first", null, "Ok", null).Show(); return; } // Use GraphRequest to delete the last shared post var request = new GraphRequest (sharedId, null, AccessToken.CurrentAccessToken.TokenString, null, "DELETE"); var requestConnection = new GraphRequestConnection (); // Handle the result of the request requestConnection.AddRequest (request, (connection, result, error) => { if (error != null) { new UIAlertView ("Error...", error.Description, null, "Ok", null).Show (); return; } sharedId = ""; new UIAlertView ("Success!!", "Deleted your last share from your wall", null, "Ok", null).Show (); isXamarinShared = false; }); // Start all your request that you have added requestConnection.Start (); }
#endregion LogIn with Email public void FacebookLoginProcess(LoginButtonCompletedEventArgs e) { if (e.Error != null) { Console.WriteLine(e.Error.ToString()); new UIAlertView("Facebook", "We were not able to authenticate you with Facebook. Please login again.", null, "OK", null) .Show(); } else if (e.Result.IsCancelled) { Console.WriteLine("Result was cancelled"); new UIAlertView("Facebook", "You cancelled the Facebook login process. Please login again.", null, "OK", null).Show(); } else if (!e.Result.GrantedPermissions.ToString().Contains("email")) { // Check that we have email as a permission, otherwise show that we can't signup Console.WriteLine("Email permission not found"); new UIAlertView("Facebook", "Email permission is required to sign in, Please login again.", null, "OK", null).Show(); } else { var meRequest = new GraphRequest("/me", new NSDictionary("fields", "first_name,last_name,name,email,picture"), "GET"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(meRequest, (connection, meResult, meError) => { var client = new WebClient(); if (meError != null) { Console.WriteLine(meError.ToString()); new UIAlertView("Facebook", "Unable to login to facebook.", null, "OK", null).Show(); return; } var user = meResult as NSDictionary; var sc = new SocialLoginData(); sc.scFirstName = user.ValueForKey(new NSString("first_name")).Description; sc.scLastName = user.ValueForKey(new NSString("last_name")).Description; sc.scUserName = user.ValueForKey(new NSString("name")).Description; sc.scSocialId = user.ValueForKey(new NSString("id")).Description; sc.scEmail = user.ValueForKey(new NSString("email")).Description; sc.scProfileImgUrl = ""; //user.ValueForKey(new NSString("picture")).Description; sc.scSource = "facebook"; sc.scAccessUrl = "http://facebook.com/profile.php?id=" + user.ValueForKey(new NSString("id")).Description; sc.scSocialOauthToken = AccessToken.CurrentAccessToken.TokenString; sc.scAccount = AccessToken.CurrentAccessToken.TokenString; StartRegistration(sc); }); requestConnection.Start(); } } public async void StartRegistration(SocialLoginData SocialData) { InpowerResult Result = null; UserProfile userProfile = new UserProfile(); try { string isscEmail = ""; if (SocialData.scEmail != "" || SocialData.scEmail != null) { isscEmail = SocialData.scEmail; }else{isscEmail = SocialData.scFirstName + SocialData.scLastName + SocialData.scSocialId + "@InPower.com";} Result = await new AccountService().Registration(new UserRegisterRequestViewModel { FirstName = SocialData.scFirstName, LastName = SocialData.scLastName, Email = isscEmail , Password = "******" }, GlobalConstant.AccountUrls.RegisterServiceUrl); var modelReporeg = JsonConvert.DeserializeObject<UserRegisterResponseViewModel>(Result.Response.ToString()); var ResultToken = await new AccountService().AccessToken(new TokenRequestViewModel { UserName = modelReporeg.Email, password = modelReporeg.Password, grant_type = "password" }); if (Result.Message == "Detail Successfully Updated") { ContinuetoMainScreen(modelReporeg.UserId.ToString(), modelReporeg.Password, ResultToken.access_token, modelReporeg.Email, modelReporeg.AWSAccessKey,modelReporeg.AWSSecretKey); } else { var token = AccessToken.CurrentAccessToken != null; if (ResultToken != null) {
// Delete the "Hello!" post from user wall void DeleteHelloPost () { if (!isHelloPosted) { new UIAlertView ("Error", "Please Post \"Hello\" to your wall first", null, "Ok", null).Show(); return; } // Use GraphRequest to delete the Hello! post var request = new GraphRequest (helloId, null, AccessToken.CurrentAccessToken.TokenString, null, "DELETE"); var requestConnection = new GraphRequestConnection (); // Handle the result of the request requestConnection.AddRequest (request, (connection, result, error) => { if (error != null) { new UIAlertView ("Error...", error.Description, null, "Ok", null).Show (); return; } helloId = ""; new UIAlertView ("Success", "Deleted Hello from your wall", null, "Ok", null).Show (); isHelloPosted = false; }); requestConnection.Start (); }
private void LoginManagerRequestTokenHandler(LoginManagerLoginResult result, NSError error) { if (error != null) { //Handle error } var request = new GraphRequest("/me", null, AccessToken.CurrentAccessToken.TokenString, null, "GET"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(request, GraphRequestHandler); requestConnection.Start(); }
async void getEvents(string id) { //var fields = "?fields=events,id,name,email,about,hometown,groups"; //var request = new GraphRequest("/me/events?fields=name,id,place,description&rsvp_status=attending", null, AccessToken.CurrentAccessToken.TokenString, null, "GET"); var request = new GraphRequest("/me/friends", null, AccessToken.CurrentAccessToken.TokenString, null, "GET"); var requestConnection = new GraphRequestConnection(); var fbEvents = new List<FaceBookEvent>(); requestConnection.AddRequest(request, (connection, result, error) => { // Handle if something went wrong with the reques if (error != null) { System.Diagnostics.Debug.WriteLine("Hnnn2"); new UIAlertView("Error...", error.Description, null, "Ok", null).Show(); return; } //fbEvents = JsonConvert.DeserializeObject<List<FaceBookEvent>>(result); NSDictionary userInfo = (result as NSDictionary); if (error != null) { } }); requestConnection.Start(); await System.Threading.Tasks.Task.Delay(500); }
// Post and delete the "Hello!" from user wall void PostHello () { // Verify if you have permissions to post into user wall, // if not, ask to user if he/she wants to let your app post things for them if (!AccessToken.CurrentAccessToken.HasGranted ("publish_actions")) { AskPermissions ("Post Hello", "Would you like to let this app to post a \"Hello\" for you?", new [] { "publish_actions" }, PostHello); return; } // Once you have the permissions, you can publish or delete the post from your wall GraphRequest request; if (!isHelloPosted) request = new GraphRequest ("me/feed", new NSDictionary ("message", "Hello!"), AccessToken.CurrentAccessToken.TokenString, null, "POST"); else request = new GraphRequest (helloId, null, AccessToken.CurrentAccessToken.TokenString, null, "DELETE"); var requestConnection = new GraphRequestConnection (); // Handle the result of the request requestConnection.AddRequest (request, (connection, result, error) => { // Handle if something went wrong if (error != null) { ShowMessageBox ("Error...", error.Description, "Ok", null, null); return; } // Post the Hello! to your wall if (!isHelloPosted) { helloId = (result as NSDictionary) ["id"].ToString (); isHelloPosted = true; InvokeOnMainThread (() => { strPostHello.Caption = "Delete \"Hello\" from your wall"; Root.Reload (strPostHello, UITableViewRowAnimation.Left); ShowMessageBox ("Success!!", "Posted Hello in your wall, MsgId: " + helloId, "Ok", null, null); }); } else { // Delete the Hello! from your wall helloId = ""; isHelloPosted = false; InvokeOnMainThread (() => { strPostHello.Caption = "Post \"Hello\" on your wall"; Root.Reload (strPostHello, UITableViewRowAnimation.Left); ShowMessageBox ("Success", "Deleted Hello from your wall", "Ok", null, null); }); } }); requestConnection.Start (); }
private void GraphRequestHandler(GraphRequestConnection connection, NSObject requestResult, NSError requestError) { NSDictionary userInfo = (requestResult as NSDictionary); // Handle if something went wrong if (requestError != null || userInfo == null) { //Handle error } //Handle graph request result //For example: var fad = new FacebookAccountData(); if (userInfo["id"] != null) { fad.SocialNetworkId = userInfo["id"].ToString(); } if (userInfo["name"] != null) { fad.Name = userInfo["name"].ToString(); } if (userInfo["first_name"] != null) { fad.FirstName = userInfo["first_name"].ToString(); } if (userInfo["middle_name"] != null) { fad.MiddleName = userInfo["middle_name"].ToString(); } if (userInfo["last_name"] != null) { fad.LastName = userInfo["last_name"].ToString(); } if (userInfo["age_range"] != null) { fad.AgeRange = userInfo["age_range"].ToString(); } if (userInfo["link"] != null) { fad.Link = userInfo["link"].ToString(); } if (userInfo["gender"] != null) { fad.Gender = userInfo["gender"].ToString(); } if (userInfo["locale"] != null) { fad.Locale = userInfo["locale"].ToString(); } if (userInfo["timezone"] != null) { fad.Timezone = userInfo["timezone"].ToString(); } if (userInfo["updated_time"] != null) { fad.UpdatedTime = userInfo["updated_time"].ToString(); } if (userInfo["verified"] != null) { fad.Verified = userInfo["verified"].ToString(); } if (userInfo["email"] != null) { fad.Email = userInfo["email"].ToString(); } }
private void OnRequestHandler(GraphRequestConnection connection, NSObject result, NSError error) { if (error != null || result == null) { OnLoginError?.Invoke(new Exception(error.LocalizedDescription)); } else { var id = string.Empty; var first_name = string.Empty; var email = string.Empty; var last_name = string.Empty; var url = string.Empty; try { id = result.ValueForKey(new NSString("id"))?.ToString(); } catch (Exception e) { Debug.WriteLine(e.Message); } try { first_name = result.ValueForKey(new NSString("first_name"))?.ToString(); } catch (Exception e) { Debug.WriteLine(e.Message); } try { email = result.ValueForKey(new NSString("email"))?.ToString(); } catch (Exception e) { Debug.WriteLine(e.Message); } try { last_name = result.ValueForKey(new NSString("last_name"))?.ToString(); } catch (Exception e) { Debug.WriteLine(e.Message); } try { url = ((result.ValueForKey(new NSString("picture")) as NSDictionary).ValueForKey(new NSString("data")) as NSDictionary).ValueForKey(new NSString("url")).ToString(); } catch (Exception e) { Debug.WriteLine(e.Message); } //Grab the user and send the success event User = new FacebookUser(id, AccessToken.CurrentAccessToken.TokenString, first_name, last_name, email, url); OnLoginSuccess?.Invoke(User); } }
public PhotoViewController() : base(UITableViewStyle.Grouped, null, true) { // Add the image that will be publish var imageView = new UIImageView(new CGRect(0, 0, View.Frame.Width, 220)) { Image = UIImage.FromFile("wolf.jpg") }; // Add a textbox that where you will be able to add a comment to the photo txtMessage = new EntryElement("", "Say something nice!", ""); Root = new RootElement("Post photo!") { new Section() { new UIViewElement("", imageView, true) { Flags = UIViewElement.CellFlags.DisableSelection | UIViewElement.CellFlags.Transparent, }, txtMessage } }; // Create the request to post a photo into your wall NavigationItem.RightBarButtonItem = new UIBarButtonItem("Post", UIBarButtonItemStyle.Plain, ((sender, e) => { // Disable the post button for prevent another untill the actual one finishes (sender as UIBarButtonItem).Enabled = false; // Add the photo and text that will be publish var parameters = new NSDictionary("picture", UIImage.FromFile("wolf.jpg").AsPNG(), "caption", txtMessage.Value); // Create the request var request = new GraphRequest("/" + Profile.CurrentProfile.UserID + "/photos", parameters, AccessToken.CurrentAccessToken.TokenString, null, "POST"); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(request, (connection, result, error) => { // Enable the post button (sender as UIBarButtonItem).Enabled = true; // Handle if something went wrong if (error != null) { new UIAlertView("Error...", error.Description, null, "Ok", null).Show(); return; } // Do your magic if the request was successful new UIAlertView("Yay!!", "Your photo was published!", null, "Ok", null).Show(); photoId = (result as NSDictionary) ["post_id"].ToString(); // Add a button to allow to delete the photo posted Root.Add(new Section() { new StyledStringElement("Delete Post", DeletePost) { Alignment = UITextAlignment.Center, TextColor = UIColor.Red } }); }); requestConnection.Start(); })); }
protected override IEnumerable<Datum> Poll(CancellationToken cancellationToken) { List<Datum> data = new List<Datum>(); if (HasValidAccessToken) { string[] missingPermissions = GetRequiredPermissionNames().Where(p => !AccessToken.CurrentAccessToken.Permissions.Contains(p)).ToArray(); if (missingPermissions.Length > 0) ObtainAccessToken(missingPermissions); } else ObtainAccessToken(GetRequiredPermissionNames()); if (HasValidAccessToken) { ManualResetEvent startWait = new ManualResetEvent(false); List<ManualResetEvent> responseWaits = new List<ManualResetEvent>(); Exception exception = null; // can't throw exception from within the UI thread -- it will crash the app. use this variable to check whether an exception did occur. Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { try { GraphRequestConnection requestConnection = new GraphRequestConnection(); #region add requests to connection foreach (Tuple<string, List<string>> edgeFieldQuery in GetEdgeFieldQueries()) { NSDictionary parameters = null; if (edgeFieldQuery.Item2.Count > 0) parameters = new NSDictionary("fields", string.Concat(edgeFieldQuery.Item2.Select(field => field + ",")).Trim(',')); GraphRequest request = new GraphRequest( "me" + (edgeFieldQuery.Item1 == null ? "" : "/" + edgeFieldQuery.Item1), parameters, AccessToken.CurrentAccessToken.TokenString, null, "GET"); ManualResetEvent responseWait = new ManualResetEvent(false); requestConnection.AddRequest(request, (connection, result, error) => { if (error == null) { FacebookDatum datum = new FacebookDatum(DateTimeOffset.UtcNow); #region set datum properties NSDictionary resultDictionary = result as NSDictionary; bool valuesSet = false; foreach (string resultKey in resultDictionary.Keys.Select(k => k.ToString())) { PropertyInfo property; if (FacebookDatum.TryGetProperty(resultKey, out property)) { object value = null; if (property.PropertyType == typeof(string)) value = resultDictionary[resultKey].ToString(); else if (property.PropertyType == typeof(bool?)) { int parsedBool; if (int.TryParse(resultDictionary[resultKey].ToString(), out parsedBool)) value = parsedBool == 1 ? true : false; } else if (property.PropertyType == typeof(DateTimeOffset?)) { DateTimeOffset parsedDateTimeOffset; if (DateTimeOffset.TryParse(resultDictionary[resultKey].ToString(), out parsedDateTimeOffset)) value = parsedDateTimeOffset; } else if (property.PropertyType == typeof(List<string>)) { List<string> values = new List<string>(); NSArray resultArray = resultDictionary[resultKey] as NSArray; for (nuint i = 0; i < resultArray.Count; ++i) values.Add(resultArray.GetItem<NSObject>(i).ToString()); value = values; } else throw new SensusException("Unrecognized FacebookDatum property type: " + property.PropertyType.ToString()); if (value != null) { property.SetValue(datum, value); valuesSet = true; } } else SensusServiceHelper.Get().Logger.Log("Unrecognized key in Facebook result dictionary: " + resultKey, LoggingLevel.Verbose, GetType()); } #endregion if (valuesSet) data.Add(datum); } else SensusServiceHelper.Get().Logger.Log("Error received while querying Facebook graph API: " + error.Description, LoggingLevel.Normal, GetType()); SensusServiceHelper.Get().Logger.Log("Response for \"" + request.GraphPath + "\" has been processed.", LoggingLevel.Verbose, GetType()); responseWait.Set(); }); responseWaits.Add(responseWait); } #endregion if (responseWaits.Count == 0) exception = new Exception("Request connection contained zero requests."); else { SensusServiceHelper.Get().Logger.Log("Starting request connection with " + responseWaits.Count + " requests.", LoggingLevel.Normal, GetType()); requestConnection.Start(); } startWait.Set(); } catch (Exception ex) { exception = new Exception("Error starting request connection: " + ex.Message); } }); startWait.WaitOne(); // wait for all responses to be processed foreach (ManualResetEvent responseWait in responseWaits) responseWait.WaitOne(); // if any exception occurred when running query, throw it now if (exception != null) throw exception; } else throw new Exception("Attempted to poll Facebook probe without a valid access token."); return data; }
void RequestData(Dictionary <string, object> pDictionary) { string path = $"{pDictionary["method"]}"; string version = $"{pDictionary["version"]}"; Dictionary <string, string> paramDict = pDictionary["parameters"] as Dictionary <string, string>; FacebookHttpMethod? method = pDictionary["method"] as FacebookHttpMethod?; var currentTcs = _requestTcs; var onEvent = OnRequestData; var httpMethod = "GET"; if (method != null) { switch (method) { case FacebookHttpMethod.Get: httpMethod = "GET"; break; case FacebookHttpMethod.Post: httpMethod = "POST"; onEvent = OnPostData; currentTcs = _postTcs; break; case FacebookHttpMethod.Delete: httpMethod = "DELETE"; onEvent = OnDeleteData; currentTcs = _deleteTcs; break; } } if (string.IsNullOrEmpty(path)) { var fbResponse = new FBEventArgs <string>(null, FacebookActionStatus.Error, "Graph query path not specified"); onEvent?.Invoke(CrossFacebookClient.Current, fbResponse); currentTcs?.TrySetResult(new FacebookResponse <string>(fbResponse)); return; } NSMutableDictionary parameters = null; if (paramDict != null) { parameters = new NSMutableDictionary(); foreach (var p in paramDict) { var key = $"{p}"; parameters.Add(new NSString(key), new NSString($"{paramDict[key]}")); } } var graphRequest = string.IsNullOrEmpty(version)?new GraphRequest(path, parameters, httpMethod): new GraphRequest(path, parameters, AccessToken.CurrentAccessToken.TokenString, version, httpMethod); var requestConnection = new GraphRequestConnection(); requestConnection.AddRequest(graphRequest, (connection, result, error) => { if (error == null) { var fbResponse = new FBEventArgs <string>(result.ToString(), FacebookActionStatus.Completed); onEvent?.Invoke(CrossFacebookClient.Current, fbResponse); currentTcs?.TrySetResult(new FacebookResponse <string>(fbResponse)); } else { var fbResponse = new FBEventArgs <string>(null, FacebookActionStatus.Error, $" Facebook operation failed - {error.Code} - {error.Description}"); onEvent?.Invoke(CrossFacebookClient.Current, fbResponse); currentTcs?.TrySetResult(new FacebookResponse <string>(fbResponse)); } }); requestConnection.Start(); }
protected override IEnumerable <Datum> Poll(CancellationToken cancellationToken) { List <Datum> data = new List <Datum>(); if (HasValidAccessToken) { // prompt user for any missing permissions string[] missingPermissions = GetRequiredPermissionNames().Where(p => !AccessToken.CurrentAccessToken.Permissions.Contains(p)).ToArray(); if (missingPermissions.Length > 0) { _loginManager.LogInWithReadPermissions(missingPermissions, _loginResultHandler); return(data); } ManualResetEvent startWait = new ManualResetEvent(false); List <ManualResetEvent> responseWaits = new List <ManualResetEvent>(); Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { try { GraphRequestConnection requestConnection = new GraphRequestConnection(); #region add requests to connection foreach (Tuple <string, List <string> > edgeFieldQuery in GetEdgeFieldQueries()) { NSDictionary parameters = null; if (edgeFieldQuery.Item2.Count > 0) { parameters = new NSDictionary("fields", string.Concat(edgeFieldQuery.Item2.Select(field => field + ",")).Trim(',')); } GraphRequest request = new GraphRequest( "me" + (edgeFieldQuery.Item1 == null ? "" : "/" + edgeFieldQuery.Item1), parameters, AccessToken.CurrentAccessToken.TokenString, null, "GET"); ManualResetEvent responseWait = new ManualResetEvent(false); requestConnection.AddRequest(request, (connection, result, error) => { if (error == null) { FacebookDatum datum = new FacebookDatum(DateTimeOffset.UtcNow); #region set datum properties NSDictionary resultDictionary = result as NSDictionary; bool valuesSet = false; foreach (string resultKey in resultDictionary.Keys.Select(k => k.ToString())) { PropertyInfo property; if (FacebookDatum.TryGetProperty(resultKey, out property)) { object value = null; if (property.PropertyType == typeof(string)) { value = resultDictionary[resultKey].ToString(); } else if (property.PropertyType == typeof(bool?)) { int parsedBool; if (int.TryParse(resultDictionary[resultKey].ToString(), out parsedBool)) { value = parsedBool == 1 ? true : false; } } else if (property.PropertyType == typeof(DateTimeOffset?)) { DateTimeOffset parsedDateTimeOffset; if (DateTimeOffset.TryParse(resultDictionary[resultKey].ToString(), out parsedDateTimeOffset)) { value = parsedDateTimeOffset; } } else if (property.PropertyType == typeof(List <string>)) { List <string> values = new List <string>(); NSArray resultArray = resultDictionary[resultKey] as NSArray; for (nuint i = 0; i < resultArray.Count; ++i) { values.Add(resultArray.GetItem <NSObject>(i).ToString()); } value = values; } else { throw new SensusException("Unrecognized FacebookDatum property type: " + property.PropertyType.ToString()); } if (value != null) { property.SetValue(datum, value); valuesSet = true; } } else { SensusServiceHelper.Get().Logger.Log("Unrecognized key in Facebook result dictionary: " + resultKey, LoggingLevel.Verbose, GetType()); } } #endregion if (valuesSet) { data.Add(datum); } } else { SensusServiceHelper.Get().Logger.Log("Error received while querying Facebook graph API: " + error.Description, LoggingLevel.Normal, GetType()); } SensusServiceHelper.Get().Logger.Log("Response for \"" + request.GraphPath + "\" has been processed.", LoggingLevel.Verbose, GetType()); responseWait.Set(); }); responseWaits.Add(responseWait); } #endregion if (responseWaits.Count == 0) { SensusServiceHelper.Get().Logger.Log("Request connection contained zero requests.", LoggingLevel.Normal, GetType()); } else { SensusServiceHelper.Get().Logger.Log("Starting request connection with " + responseWaits.Count + " requests.", LoggingLevel.Normal, GetType()); requestConnection.Start(); } startWait.Set(); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Error starting request connection: " + ex.Message, LoggingLevel.Normal, GetType()); } }); startWait.WaitOne(); // wait for all responses to be processed foreach (ManualResetEvent responseWait in responseWaits) { responseWait.WaitOne(); } } else { SensusServiceHelper.Get().Logger.Log("Attempted to poll Facebook probe without a valid access token.", LoggingLevel.Normal, GetType()); } return(data); }
// Revoke all the permissions that you had granted, you will need to login again for ask the permissions again // You can also revoke a single permission, for more info, visit this link: // https://developers.facebook.com/docs/facebook-login/permissions/v2.3#revoking void RevokeAllPermissions (string userId) { // Create the request for delete all the permissions var request = new GraphRequest ("/" + userId + "/permissions", null, AccessToken.CurrentAccessToken.TokenString, null, "DELETE"); var requestConnection = new GraphRequestConnection (); requestConnection.AddRequest (request, (connection, result, error) => { // Handle if something went wrong if (error != null) { ShowMessageBox ("Error...", error.Description, "Ok", null, null); return; } // If the revoking was successful, logout from FB if ((result as NSDictionary) ["success"].ToString () == "1") InvokeOnMainThread (() => { ShowMessageBox ("Successful", "All permissions have been revoked", "Ok", null, null); var login = new LoginManager (); login.LogOut (); LoggedOut (); }); else InvokeOnMainThread (() => ShowMessageBox ("Ups...", "A problem has ocurred", "Ok", null, null)); }); requestConnection.Start (); }
// Delete the photo posted from your wall void DeletePost() { // Create the request to delete the post var request = new GraphRequest ("/" + photoId, null, AccessToken.CurrentAccessToken.TokenString, null, "DELETE"); var requestConnection = new GraphRequestConnection (); requestConnection.AddRequest (request, (connection, result, error) => { // Handle if something went wrong if (error != null) { new UIAlertView ("Error...", error.Description, null, "Ok", null).Show (); return; } // Do your magin is the request was successful new UIAlertView ("Post Deleted", "Success", null, "OK", null).Show (); NavigationController.PopViewController (true); }); requestConnection.Start (); }