private void FinalizeLogin()
        {
            if (AccessToken.CurrentAccessToken != null) {
                InvokeOnMainThread (() => {
                    StatusLabel.Text = "TryingServer_string".Localize ();
                });
                var request = new GraphRequest ("/me?fields=name,id,birthday,first_name,gender,last_name,interested_in,location", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");
                request.Start ((connection, result, error) => {
                    // Handle if something went wrong with the request
                    if (error != null) {
                        new UIAlertView ("Error...", error.Description, null, "Ok", null).Show ();
                        return;
                    }

                    // Get your profile name
                    var userInfo = result as NSDictionary;

                    LettuceServer.Instance.FacebookLogin (userInfo ["id"].ToString (), AccessToken.CurrentAccessToken.TokenString, (theUser) => {
                        InvokeOnMainThread (() => {
                            NavController.PopToRootViewController (true);
                        });
                    });
                });
            } else {
                InvokeOnMainThread (() => {
                    StatusLabel.Text = "FacebookConnectFailed_string".Localize();
                });
            }
        }
        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 ();
            }));
        }
Exemple #3
0
        /// <summary>
        /// Bot calls users.
        /// </summary>
        /// <param name="participantsCallingRequestData">Input data.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task BotCallsUsersAsync(ParticipantsCallingRequestData participantsCallingRequestData)
        {
            Guid            scenarioId = Guid.NewGuid();
            ParticipantInfo source     = new ParticipantInfo
            {
                Identity = new IdentitySet
                {
                    Application = new Identity
                    {
                        Id = this.appId,
                    },
                },
            };

            Call requestCall = new Call
            {
                Source              = source,
                Targets             = new List <InvitationParticipantInfo>(),
                MediaConfig         = new ServiceHostedMediaConfig {
                },
                RequestedModalities = new List <Modality> {
                    Modality.Audio
                },
                TenantId    = participantsCallingRequestData.TenantId,
                Direction   = CallDirection.Outgoing,
                CallbackUri = new Uri(this.botBaseUri, ControllerConstants.CallbackPrefix).ToString(),
            };

            List <InvitationParticipantInfo> listTargets = new List <InvitationParticipantInfo>();

            foreach (string userId in participantsCallingRequestData.ObjectIds)
            {
                InvitationParticipantInfo target = new InvitationParticipantInfo
                {
                    Identity = new IdentitySet
                    {
                        User = new Identity
                        {
                            Id = userId,
                        },
                    }
                };
                listTargets.Add(target);
            }
            requestCall.Targets = listTargets;
            var callRequest = this.RequestBuilder.Communications.Calls;
            var request     = new GraphRequest <Call>(new Uri(callRequest.RequestUrl), requestCall, RequestType.Create);
            var response    = await this.GraphApiClient.SendAsync <Call, Call>(request, requestCall.TenantId, scenarioId).ConfigureAwait(false);

            Call responseMeetingCall = response.Content;

            this.GraphLogger.Log(
                TraceLevel.Verbose,
                $"Bot called users {participantsCallingRequestData.ObjectIds}, the responded state is {responseMeetingCall?.State}");
        }
Exemple #4
0
        private void InitializeComponents()
        {
            try
            {
                progress_bar = FindViewById <ProgressBar>(Resource.Id.progress_bar_login);

                btn_login_facebook = FindViewById <Button>(Resource.Id.btn_login_facebook);

                btn_login_facebook.SetOnClickListener(this);

                FacebookSdk.SdkInitialize(ApplicationContext);

                callbackManager = CallbackManagerFactory.Create();

                graphCallback = new GraphJSONObjectCallback
                {
                    HandleSuccess = email =>
                    {
                        LoginWithFacebook(Profile.CurrentProfile, email);
                    }
                };

                loginCallback = new FacebookCallback <LoginResult>
                {
                    HandleSuccess = loginResult =>
                    {
                        var request = GraphRequest.NewMeRequest(loginResult.AccessToken, graphCallback);

                        Bundle parameters = new Bundle();

                        parameters.PutString("fields", "id, name, email");

                        request.Parameters = parameters;

                        request.ExecuteAsync();
                    },
                    HandleCancel = () =>
                    {
                        StopLoading();
                    },
                    HandleError = loginError =>
                    {
                        StopLoading();
                    }
                };

                Xamarin.Facebook.Login.LoginManager.Instance.RegisterCallback(callbackManager, loginCallback);

                CheckUserLogged();
            }
            catch (Exception exception)
            {
                InsightsUtils.LogException(exception);
            }
        }
        public Task <SocialData> GetPersonData()
        {
            _facebookTask = new TaskCompletionSource <SocialData>();
            CancellationToken canellationToken = new CancellationToken(true);

            manager.LogInWithReadPermissions(readPermissions.ToArray(), (res, e) =>
            {
                if (e != null)
                {
                    Mvx.Trace($"FacebookLoginButton error {e}");
                    _facebookTask.TrySetResult(null);
                    return;
                }

                try
                {
                    if (AccessToken.CurrentAccessToken == null)
                    {
                        Mvx.Trace($"Empty token");
                        manager.LogOut();
                        _facebookTask.TrySetCanceled(canellationToken);
                        //GetPersonData();
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message, ex.StackTrace);
                }

                GraphRequest request = new GraphRequest("/me", new NSDictionary("fields", "name,picture,email"), AccessToken.CurrentAccessToken.TokenString, null, "GET");
                request.Start(new GraphRequestHandler((connection, result, error) =>
                {
                    FacebookAccountResult acct = new FacebookAccountResult()
                    {
                        Id    = result.ValueForKey(new NSString("id")).ToString(),
                        Name  = result.ValueForKey(new NSString("name")).ToString(),
                        Email = result.ValueForKey(new NSString("email")).ToString()
                    };

                    if (acct != null)
                    {
                        Mvx.Trace($"Profile: {acct.Name}, {acct.Email}, {acct.PhotoUrl}");
                        _facebookTask.TrySetResult(new SocialData()
                        {
                            Email     = acct.Email,
                            FirstName = acct.Name,
                            Photo     = acct.PhotoUrl,
                            Source    = AuthorizationType.Facebook
                        });
                    }
                }));
            });
            return(_facebookTask.Task);
        }
		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;
		}
Exemple #7
0
        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");
            }
        }
Exemple #8
0
 public void VerifyPermissions(string[] permissions = null, Action <ChallengesFacebookShareResponseType> viewModelResponse = null, object param = null)
 {
     //var token = AccessToken.CurrentAccessToken;
     ViewModelResponse = viewModelResponse;
     Param             = param;
     if (Xamarin.Facebook.AccessToken.CurrentAccessToken != null)
     {
         var request = new GraphRequest(AccessToken.CurrentAccessToken, "/me/permissions", null, HttpMethod.Get, this);
         request.ExecuteAsync();
     }
 }
Exemple #9
0
 /// <summary>
 ///     Called when [success].
 /// </summary>
 /// <param name="result">The result.</param>
 public void OnSuccess(Object result)
 {
     if (result is LoginResult n)
     {
         var request = GraphRequest.NewMeRequest(n.AccessToken, this);
         var bundle  = new Bundle();
         bundle.PutString("fields", "id, first_name, email, last_name, picture.width(500).height(500)");
         request.Parameters = bundle;
         request.ExecuteAsync();
     }
 }
Exemple #10
0
        private void ConfigurateFacebookData()
        {
            GraphRequest oGraphRequest = GraphRequest.NewMeRequest(AccessToken.CurrentAccessToken, this);
            Bundle       parameters    = new Bundle();

            parameters.PutString("fields", "id,name,birthday,email,address");
            oGraphRequest.Parameters = parameters;
            oGraphRequest.ExecuteAsync();
            oICallbackManager = CallbackManagerFactory.Create();
            btnLogin.RegisterCallback(oICallbackManager, this);
        }
Exemple #11
0
        private void Initialize(IAccessToken token, string path, string httpMethod = default(string), string version = default(string))
        {
            _token     = (token as DroidAccessToken).ToNative();
            Path       = path;
            HttpMethod = httpMethod;
            Version    = version;

            GraphCallback callback = new GraphCallback();

            _request = new GraphRequest(_token, Path, null, null, callback);
        }
        public void OnSuccess(Java.Lang.Object p0)
        {
            LoginResult loginResult = p0 as LoginResult;

            accessToken = loginResult.AccessToken;
            var    request    = GraphRequest.NewMeRequest(loginResult.AccessToken, this);
            Bundle parameters = new Bundle();

            parameters.PutString("fields", "id,name,picture,email");
            request.Parameters = parameters;
            request.ExecuteAsync();
        }
        public void OnSuccess(Java.Lang.Object result)
        {
            var n = result as LoginResult;

            if (n != null)
            {
                var request = GraphRequest.NewMeRequest(n.AccessToken, this);
                var bundle  = new Android.OS.Bundle();
                bundle.PutString("fields", "id, first_name, email, last_name, picture.width(500).height(500)");
                request.Parameters = bundle;
                request.ExecuteAsync();
            }
        }
        public void OnSuccess(Java.Lang.Object result)
        {
            var loginResult = result as Xamarin.Facebook.Login.LoginResult;

            Bundle parameters = new Bundle();

            parameters.PutString("fields", "email");

            GraphRequest request = GraphRequest.NewMeRequest(loginResult.AccessToken, new GraphJSONCallback(loginResult, this));

            request.Parameters = parameters;
            request.ExecuteAsync();
        }
        public ActionResult <List <List <int> > > CalculateShortestPath(GraphRequest graphRequest)
        {
            var shortestPath = _pathFinder.FindShortestPath(graphRequest.Matrix, graphRequest.StartVector, graphRequest.EndVector);

            Thread.Sleep(10000);

            if (shortestPath == null)
            {
                return(NoContent());
            }

            return(shortestPath);
        }
Exemple #16
0
        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();
        }
Exemple #17
0
        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));
            }
        }
Exemple #18
0
        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);
        }
        public async Task <string> ExecuteAsync(GraphRequest request)
        {
            _logger.Info($"Executing query {request.Query}");

            var result = await this.ExecuteAsync(_ =>
            {
                _.Query  = request.Query;
                _.Inputs = request.Variables.ToInputs();
                _.Listeners.Add(_dataLoaderDocumentListener);
            });

            _logger.Info($"Got query result {result}");

            return(result);
        }
Exemple #22
0
        public void OnSuccess(Java.Lang.Object result)
        {
            FacebookProgressBar.Visibility = ViewStates.Visible;
            FacebookButton.Enabled         = false;
            loginButton.Enabled            = false;
            signupButton.Enabled           = false;
            LoginResult   loginResult   = result as LoginResult;
            GraphCallback graphCallBack = new GraphCallback();

            graphCallBack.RequestCompleted += OnGetNameResponse;
            Bundle parameters = new Bundle();

            parameters.PutString("fields", "id,name,email");
            var request = new GraphRequest(loginResult.AccessToken, "/" + loginResult.AccessToken.UserId, parameters, HttpMethod.Get, graphCallBack).ExecuteAsync();
        }
Exemple #23
0
        public Graph PostGraph(GraphRequest graph)
        {
            var client  = new RestClient(_baseUrl);
            var request = new RestRequest {
                Resource = _postGraphEndpoint
            };

            request.AddJsonBody(graph);
            request.AddHeader("Authentication", _apiKey);
            request.Method = Method.POST;
            var response      = client.Execute(request);
            var graphResponse = JsonConvert.DeserializeObject <GraphResponse>(response.Content);

            return(graphResponse.graph);
        }
        public void OnSuccess(Java.Lang.Object p0)
        {
            // Facebook Email address
            LoginResult loginResult = (LoginResult)p0;

            _graphCBHandler = new GraphCBHandler(_fba);
            _fba.SetAccessToken(loginResult.AccessToken.Token);
            GraphRequest request = GraphRequest.NewMeRequest(loginResult.AccessToken, _graphCBHandler);

            Bundle parameters = new Bundle();

            parameters.PutString("fields", "email");
            request.Parameters = (parameters);
            request.ExecuteAsync();
        }
Exemple #25
0
        public Task <FacebookUserInfo> GetUserInfo()
        {
            var _taskCompletionSource = new TaskCompletionSource <FacebookUserInfo>();

            Bundle parameters = new Bundle();

            parameters.PutString("fields", "id,first_name,last_name,email");

            GraphRequest graphRequestData     = new GraphRequest();
            GraphRequest userInfoGraphRequest = new GraphRequest(AccessToken.CurrentAccessToken, "me", parameters, graphRequestData.HttpMethod, new GetUserInfoCallback(_taskCompletionSource), graphRequestData.Version);

            userInfoGraphRequest.ExecuteAsync();

            return(_taskCompletionSource.Task);
        }
        public async Task <GraphResponse> GetGameScoresforGraph(GraphRequest request)
        {
            var             response      = new GraphResponse();
            APIResponseBase tokenResponse = ValidateUserToken();

            if (tokenResponse != null && tokenResponse.ErrorCode == (int)LAMPConstants.API_SUCCESS_CODE)
            {
                response = await Task.Run(() => _SurveyService.GetGameScoresforGraph(request));
            }
            else
            {
                response.ErrorCode    = tokenResponse.ErrorCode;
                response.ErrorMessage = tokenResponse.ErrorMessage;
            }
            return(response);
        }
Exemple #27
0
        private void Btn_Click(object sender, EventArgs e)
        {
            LoginManager.Instance.LogOut();
            LoginManager.Instance.LogIn(this, PERMISSIONS);

            Task.Run(() =>
            {
                var likesRequest = "Insert_Requred_Request_To_Get_Likes_Info";
                var response     = GraphRequest.ExecuteAndWait(new GraphRequest(AccessToken.CurrentAccessToken, likesRequest));
                //ToDo: process response, get FB likes
                if (response != null && response.JSONObject is Org.Json.JSONObject jSON)
                {
                    var likes = jSON.GetInt("Here_Goes_The_Name_Of_Parameter");
                }
            });
        }
        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 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);
        }
Exemple #30
0
        public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
        {
            base.PrepareForSegue(segue, sender);
            if (user.name == "")
            {
                var request = new GraphRequest("me", null);
                request.Start((connection, result, error) =>
                {
                    var userInfo = result as Foundation.NSDictionary;
                    user.name    = userInfo["name"].ToString();
                    DataStorage.Instance.UpdateUser(user);
                });
            }
            var returningUser = segue.DestinationViewController as NewTripController;

            returningUser.user = user;
        }
Exemple #31
0
        public void OnSuccess(Java.Lang.Object result)
        {
            LoginResult loginResult = result as LoginResult;


            GraphCallback graphCallBack = new GraphCallback();

            graphCallBack.RequestCompleted += OnGetFriendsResponseAsync;

            Bundle bundle = new Bundle();

            bundle.PutString("fields", "id,name,email");



            var request = new GraphRequest(loginResult.AccessToken, "/" + AccessToken.CurrentAccessToken.UserId, bundle, HttpMethod.Get, graphCallBack).ExecuteAsync();
        }
        public override async Task GetAnimatedGraph(GraphRequest request, IServerStreamWriter <GraphResponse> responseStream, ServerCallContext context)
        {
            try
            {
                var location = PlotFactory.Locations.ElementAt(request.LastLocation);
                await FD.GetForecastData();

                var forecast = Compressor.Unpack <IEnumerable <Data> >(FD.ForecastBytes);

                var lastTemp = forecast
                               .Where(f => f.id.Equals(location.Key) && f.dtype.Equals(DataType.actual))
                               .Last();

                var xaxis = forecast
                            .Where(f => f.id.Equals(location.Key) && f.dtype.Equals(DataType.forecast) && (f.dt.CompareTo(lastTemp.dt) < 0))
                            .Select(f => f.dt)
                            .Distinct();

                var rek = forecast
                          .Where(f => f.id.Equals(location.Key) && f.dtype.Equals(DataType.forecast) && (f.dt.CompareTo(lastTemp.dt) < 0))
                          .GroupBy(f => f.dt, f => f.main.temp);

                var list = new List <decimal?[]>(
                    Enumerable.Range(0, 40).Select(_ => new decimal?[40]));
                for (int row = 0; row < rek.Count(); row++)
                {
                    for (int col = 0; col < rek.ElementAt(row).Count(); col++)
                    {
                        list.ElementAt(col)[row] = rek.ElementAt(row).ElementAt(col);
                    }
                }
                decimal?[] lastRow = list.First();
                foreach (var row in list)
                {
                    for (int i = 0; i < row.Length; i++)
                    {
                        row[i] = row[i] ?? lastRow[i];
                    }
                    lastRow = row;
                }

                await responseStream.WriteAsync(
                    new GraphResponse
                {
                    Data = Google.Protobuf.ByteString.CopyFrom(
                        Compressor.Pack(new[]
Exemple #33
0
        public void OnSuccess(Java.Lang.Object result)
        {
            var facebookLoginResult = result.JavaCast <Xamarin.Facebook.Login.LoginResult>();

            if (facebookLoginResult == null)
            {
                return;
            }

            var parameters = new Bundle();

            parameters.PutString("fields", "id,email,picture.width(1000).height(1000)");
            var request = GraphRequest.NewMeRequest(facebookLoginResult.AccessToken, this);

            request.Parameters = parameters;
            request.ExecuteAsync();
        }
		// 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 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 ();
		}
Exemple #36
0
		private Task<FacebookUser> getUserData(Facebook.CoreKit.AccessToken token)
		{
			var fbUser = new FacebookUser()
				{
					Token = token.TokenString,
					ExpiryDate = token.ExpirationDate.ToDateTime()
				};

			var completion = new TaskCompletionSource<FacebookUser>();

			var request = new GraphRequest("me", NSDictionary.FromObjectAndKey(new NSString("id, first_name, last_name, email, location"), new NSString("fields")), "GET");
			request.Start((connection, result, error) =>
				{					
					if(error != null)
					{
						Mvx.Trace(MvxTraceLevel.Error, error.ToString());
					}
					else
					{
						
						var data = NSJsonSerialization.Serialize(result as NSDictionary, 0, out error);
						if(error != null)
						{
							Mvx.Trace(MvxTraceLevel.Error, error.ToString());
						}
						else
						{
							var json = new NSString(data, NSStringEncoding.UTF8).ToString();
							fbUser.User = JsonConvert.DeserializeObject<User>(json);
							fbUser.User.ProfilePictureUrl =  string.Format("https://graph.facebook.com/{0}/picture?width={1}&height={1}", fbUser.User.ID, Constants.FBProfilePicSize);
						}
						completion.TrySetResult(fbUser);	
					}

				});
			return completion.Task;
		}
		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 ();
		}
		// 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 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 ();
		}
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			// Perform any additional setup after loading the view, typically from a nib.

			// If was send true to Profile.EnableUpdatesOnAccessTokenChange method
			// this notification will be called after the user is logged in and
			// after the AccessToken is gotten
			Profile.Notifications.ObserveDidChange ((sender, e) => {

				if (e.NewProfile == null)
					return;

				nameLabel.Text = e.NewProfile.Name;
			});

			// Set the Read and Publish permissions you want to get
			loginButton = new LoginButton (new CGRect (80, 20, 220, 46)) {
				LoginBehavior = LoginBehavior.Native,
				ReadPermissions = readPermissions.ToArray ()
			};

			// Handle actions once the user is logged in
			loginButton.Completed += (sender, e) => {
				if (e.Error != null) {
					// Handle if there was an error
					new UIAlertView ("Login", e.Error.Description, null, "Ok", null).Show ();
					return;
				}

				if (e.Result.IsCancelled) {
					// Handle if the user cancelled the login request
					new UIAlertView ("Login", "The user cancelled the login", null, "Ok", null).Show ();
					return;
				}

				// Handle your successful login
				new UIAlertView ("Login", "Success!!", null, "Ok", null).Show ();
			};

			// Handle actions once the user is logged out
			loginButton.LoggedOut += (sender, e) => {
				// Handle your logout
				nameLabel.Text = "";
			};

			// The user image profile is set automatically once is logged in
			pictureView = new ProfilePictureView (new CGRect (80, 100, 220, 220));

			// Create the label that will hold user's facebook name
			nameLabel = new UILabel (new CGRect (80, 340, 220, 21)) {
				TextAlignment = UITextAlignment.Center,
				BackgroundColor = UIColor.Clear
			};

			// If you have been logged into the app before, ask for the your profile name
			if (AccessToken.CurrentAccessToken != null) {
				var request = new GraphRequest ("/me?fields=name", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");
				request.Start ((connection, result, error) => {
					// Handle if something went wrong with the request
					if (error != null) {
						new UIAlertView ("Error...", error.Description, null, "Ok", null).Show ();
						return;
					}

					// Get your profile name
					var userInfo = result as NSDictionary;
					nameLabel.Text = userInfo ["name"].ToString ();
				});
			}

			// Add views to main view
			View.AddSubview (loginButton);
			View.AddSubview (pictureView);
			View.AddSubview (nameLabel);
		}
        //        public override void ViewDidLoad ()
        //        {
        //            
        //        }
        public override void ViewDidLoad()
        {
            Profile.Notifications.ObserveDidChange ((sender, e) => {

                if (e.NewProfile == null)
                    return;

                nameLabel.Text = e.NewProfile.Name;
            });

            // Set the Read and Publish permissions you want to get
            loginButton = new LoginButton (new CGRect (100, 100, 220, 46)) {
                LoginBehavior = LoginBehavior.Native,
                ReadPermissions = readPermissions.ToArray ()
            };

            // Handle actions once the user is logged in
            loginButton.Completed += (sender, e) => {
                if (e.Error != null) {
                    // Handle if there was an error
                }

                if (e.Result.IsCancelled) {
                    // Handle if the user cancelled the login request
                }

                // Handle your successful login
            };

            // Handle actions once the user is logged out
            loginButton.LoggedOut += (sender, e) => {
                // Handle your logout
                nameLabel.Text = "";
            };

            // The user image profile is set automatically once is logged in
            pictureView = new ProfilePictureView (new CGRect (100, 160, 220, 220));

            // Create the label that will hold user's facebook name
            nameLabel = new UILabel (new CGRect (100, 400, 280, 21)) {
                TextAlignment = UITextAlignment.Left,
                BackgroundColor = UIColor.Clear
            };

            // If you have been logged into the app before, ask for the your profile name
            if (AccessToken.CurrentAccessToken != null) {
                var request = new GraphRequest ("/me/friends", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");
                request.Start ((connection, result, error) => {
                    // Handle if something went wrong with the request
                    if (error != null) {
                        new UIAlertView ("Error...", error.Description, null, "Ok", null).Show ();
                        return;
                    }

                    // Get your profile name
                    var userInfo = result as NSDictionary;
                    var friendlist = userInfo["data"];
                    var summary = userInfo["summary"];
                });
            }

            // Add views to main view
            View.AddSubview (loginButton);
            View.AddSubview (pictureView);
            View.AddSubview (nameLabel);
        }
Exemple #42
0
        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();
        }
		// 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 ();
			}
		}
        private void FinalizeLogin()
        {
            if (AccessToken.CurrentAccessToken != null) {
                var request = new GraphRequest ("/me?fields=name,id,birthday,first_name,gender,last_name,interested_in,location", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");
                request.Start ((connection, result, error) => {
                    // Handle if something went wrong with the request
                    if (error != null) {
                        new UIAlertView ("Error...", error.Description, null, "Ok", null).Show ();
                        return;
                    }

                    // Get your profile name
                    var userInfo = result as NSDictionary;

                    LettuceServer.Instance.FacebookLogin (userInfo["id"].ToString(), AccessToken.CurrentAccessToken.TokenString, (theUser) => {
                        InvokeOnMainThread(() => {
                            LoginView.Hidden = true;
                            LightBox.Hidden = true;
                            RefreshButtonCounts();
                            });
                        });
                });
            }
        }
        private void InitFacebookLogin()
        {
            LoginView.Hidden = false;
            Profile.Notifications.ObserveDidChange ((sender, e) => {

                if (e.NewProfile == null)
                    return;

                LoginView.Hidden = true;
                LightBox.Hidden = true;
                nameLabel.Text = e.NewProfile.Name;
            });
            CGRect viewBounds = LoginView.Bounds;

            // Set the Read and Publish permissions you want to get
            nfloat leftEdge = (viewBounds.Width - 220) /2;
            loginButton = new LoginButton (new CGRect (leftEdge, 60, 220, 46)) {
                LoginBehavior = LoginBehavior.Native,
                ReadPermissions = readPermissions.ToArray ()
            };

            // Handle actions once the user is logged in
            loginButton.Completed += (sender, e) => {
                if (e.Error != null) {
                    // Handle if there was an error
                }

                if (e.Result.IsCancelled) {
                    // Handle if the user cancelled the login request
                }

                // Handle your successful login
                FinalizeLogin();
            };

            // Handle actions once the user is logged out
            loginButton.LoggedOut += (sender, e) => {
                // Handle your logout
                nameLabel.Text = "";
            };

            // The user image profile is set automatically once is logged in
            pictureView = new ProfilePictureView (new CGRect (leftEdge, 140, 220, 220));

            // Create the label that will hold user's facebook name
            nameLabel = new UILabel (new CGRect (20, 360, viewBounds.Width - 40, 21)) {
                TextAlignment = UITextAlignment.Center,
                BackgroundColor = UIColor.Clear
            };

            // If you have been logged into the app before, ask for the your profile name
            if (AccessToken.CurrentAccessToken != null) {
                var request = new GraphRequest ("/me?fields=name", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");
                request.Start ((connection, result, error) => {
                    // Handle if something went wrong with the request
                    if (error != null) {
                        new UIAlertView ("Error...", error.Description, null, "Ok", null).Show ();
                        return;
                    }

                    // Get your profile name
                    var userInfo = result as NSDictionary;
                    nameLabel.Text = userInfo ["name"].ToString ();
                    var controller = AppDelegate.ProfileController;
                    this.NavigationController.PresentViewController(controller, true, null);

                });
            }

            // Add views to main view
            LoginView.AddSubview (loginButton);
            LoginView.AddSubview (pictureView);
            LoginView.AddSubview (nameLabel);
        }
Exemple #46
0
        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;
        }
		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);



		}
		// 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 ();
		}
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            loginButton = new LoginButton(new CGRect(80, 120, 220, 46))
            {
                LoginBehavior = LoginBehavior.SystemAccount,
                ReadPermissions = readPermissions.ToArray()
            };

            loginButton.Completed += (sender, e) => {
                if (e.Error != null)
                {
                    Debug.WriteLine(e.Error.Description);
                }

                if (e.Result != null && e.Result.IsCancelled)
                {
                    // Handle if the user cancelled the login request
                }

                // Handle your successful login
            };

            // Handle actions once the user is logged out
            loginButton.LoggedOut += (sender, e) => {
                // Handle your logout
                nameLabel.Text = "";
            };

            // The user image profile is set automatically once is logged in
            pictureView = new ProfilePictureView(new CGRect(80, 200, 220, 220));

            // Create the label that will hold user's facebook name
            nameLabel = new UILabel(new CGRect(20, 319, 280, 21))
            {
                TextAlignment = UITextAlignment.Center,
                BackgroundColor = UIColor.Clear
            };

            // If you have been logged into the app before, ask for the your profile name
            if (AccessToken.CurrentAccessToken != null)
            {
                var request = new GraphRequest("/me?fields=name", null, AccessToken.CurrentAccessToken.TokenString, null, "GET");
                request.Start((connection, result, error) => {
                    // Handle if something went wrong with the request
                    if (error != null)
                    {
                        new UIAlertView("Error...", error.Description, null, "Ok", null).Show();
                        return;
                    }

                    // Get your profile name
                    var userInfo = result as NSDictionary;
                    nameLabel.Text = userInfo["name"].ToString();
                });
            }

            // Add views to main view
            View.AddSubview(loginButton);
            View.AddSubview(pictureView);
            View.AddSubview(nameLabel);

            // Perform any additional setup after loading the view, typically from a nib.
            ConfigureView();
        }
		// 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 ();
		}
		// 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 ();
		}