Beispiel #1
0
        public void OnCompleted(GraphResponse response)
        {
            if (response?.JSONObject == null)
            {
                _completionSource?.TrySetResult(new Models.LoginResult {
                    LoginState = LoginState.Canceled
                });
            }
            else
            {
                _loginResult = new Models.LoginResult
                {
                    FirstName  = Profile.CurrentProfile.FirstName,
                    LastName   = Profile.CurrentProfile.LastName,
                    Email      = response.JSONObject.Has("email") ? response.JSONObject.GetString("email") : string.Empty,
                    ImageUrl   = response.JSONObject.GetJSONObject("picture")?.GetJSONObject("data")?.GetString("url"),
                    Token      = AccessToken.CurrentAccessToken.Token,
                    UserId     = AccessToken.CurrentAccessToken.UserId,
                    ExpireAt   = Utils.FromMsDateTime(AccessToken.CurrentAccessToken?.Expires?.Time),
                    LoginState = LoginState.Success
                };

                _completionSource?.TrySetResult(_loginResult);
            }
        }
Beispiel #2
0
        private GraphResponse ConstructGraphResponse(JObject json)
        {
            var response = new GraphResponse();

            var posixTime = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);

            foreach (JProperty property in json["average"].Children())
            {
                response.Average.GraphPoints.Add(new GraphPoint
                {
                    Date  = posixTime.AddMilliseconds(Convert.ToInt64(property.Name)),
                    Price = property.Value.ToObject <int>()
                });
            }
            foreach (JProperty property in json["daily"].Children())
            {
                response.Daily.GraphPoints.Add(new GraphPoint
                {
                    Date  = posixTime.AddMilliseconds(Convert.ToInt64(property.Name)),
                    Price = property.Value.ToObject <int>()
                });
            }

            return(response);
        }
Beispiel #3
0
        private static Bucket SelectBucket(Plan plan)
        {
            if (plan.Buckets == null)
            {
                using (var httpClient = PreparePlannerClient())
                {
                    plan.Buckets = GraphResponse <BucketResponse> .Get("plans/" + plan.Id + "/buckets", httpClient).Result.Buckets;
                }
            }

            for (int i = 0; i < plan.Buckets.Length; i++)
            {
                Console.WriteLine("(" + i + ") " + plan.Buckets[i].Name);
            }

            string selectedBucketS = Program.GetInput("Which bucket do you want to use: ");

            int selectedBucket = -1;

            if (int.TryParse(selectedBucketS, out selectedBucket))
            {
                return(plan.Buckets[selectedBucket]);
            }
            throw new Exception("Please select a bucket");
        }
Beispiel #4
0
        public async void OnCompleted(JSONObject json, GraphResponse response)
        {
            String correo = json.GetString("email");
            String nombre = json.GetString("name");

            await Revisar_login(correo, nombre, "facebook");
        }
        public void OnCompleted(JSONObject p0, GraphResponse p1)
        {
            FacebookResponseK fbResponse = JsonConvert.DeserializeObject <FacebookResponseK>(p1.RawResponse);

            profile = Profile.CurrentProfile;

            if (profile != null)
            {
                var buttonFB = view.FindViewById <Button>(Resource.Id.buttonFB);
                buttonFB.Enabled = false;
                buttonFB.SetBackgroundColor(Xamarin.Forms.Color.Gray.ToAndroid());

                profilePictureView.ProfileId = profile.Id;
                Android.Net.Uri profilePic = profile.GetProfilePictureUri(220, 220);
                fbPictureUrl = profilePic.ToString();

                //chito.do not force user to must have an email
                viewModel.FacebookEmail     = fbResponse.email ?? "";
                viewModel.FacebookFirstName = firstname ?? fbResponse.first_name;
                viewModel.FacebookLastName  = lastname ?? fbResponse.last_name;
                viewModel.FacebookPhoto     = fbPictureUrl;
                viewModel.FacebookBirthday  = fbResponse.birthday;
                viewModel.FacebookGender    = fbResponse.gender;
                viewModel.FacebookId        = fbResponse.id ?? "0";
                viewModel.FacebookLink      = fbResponse.link;
                viewModel.SaveFacebookProfileAsync();
            }
        }
Beispiel #6
0
        public void OnCompleted(JSONObject json, GraphResponse response)
        {
            FacebookResult result = JsonConvert.DeserializeObject <FacebookResult>(json.ToString());

            Toast.MakeText(this, result.name + " " + result.email, ToastLength.Short).Show();
            StartActivity(typeof(MainView));
        }
            public void OnCompleted(JSONObject json, GraphResponse response)
            {
                if (response.Error != null)
                {
                }
                else
                {
                    string fbEmail = json.GetString("email");

                    Profile profile          = Profile.CurrentProfile;
                    string  id               = profile.Id;
                    string  fbprofilePicpath = "";
                    string  fbProfilename    = "";


                    if (Profile.CurrentProfile != null)
                    {
                        fbprofilePicpath = Profile.CurrentProfile.GetProfilePictureUri(240, 240).ToString();
                        fbProfilename    = Profile.CurrentProfile.FirstName + " " + Profile.CurrentProfile.LastName;
                    }


                    if (!string.IsNullOrEmpty(fbEmail))
                    {
                        new LoginWithFb(new faceBookProfileInfo {
                            email = fbEmail, ProfileName = fbProfilename, ProfilePic = fbprofilePicpath
                        }, context).Execute();
                    }
                    else
                    {
                        Toast.MakeText(context, "Fail to authenticate!", ToastLength.Short).Show();
                    }
                }
            }
Beispiel #8
0
        // allows the user to search for a group, select the right one and then select the right plan
        // idea: if only one group matches or only one plan is in the group, that could be preselected
        private static Plan[] SelectPlan(bool allowMultiSelect)
        {
            using (var httpClient = PrepareGroupsClient())
            {
                bool foundGroup = false;
                while (!foundGroup)
                {
                    string groupSearch = Program.GetInput("Please enter the start of the name of the group containing your plan: ");
                    var    groups      = GraphResponse <GroupResponse> .Get("?$filter=groupTypes/any(c:c+eq+'Unified') and startswith(displayName, '" + groupSearch + "')", httpClient).Result.Groups;

                    if (groups.Length == 0)
                    {
                        Console.WriteLine("Found no matching group");
                    }
                    else
                    {
                        foundGroup = true;

                        Console.WriteLine("Select group:");
                        for (int i = 0; i < groups.Length; i++)
                        {
                            Console.WriteLine("(" + i + ") " + groups[i].DisplayName);
                        }

                        string selectedGroupS = Program.GetInput("Which group do you want to use: ");

                        int selectedGroup = -1;
                        if (int.TryParse(selectedGroupS, out selectedGroup))
                        {
                            var plans = GraphResponse <PlanResponse> .Get(groups[selectedGroup].Id + "/planner/plans", httpClient).Result.Plans;

                            Console.WriteLine("Select plan:");
                            for (int i = 0; i < plans.Length; i++)
                            {
                                Console.WriteLine("(" + i + ") " + plans[i].Title);
                            }
                            if (allowMultiSelect)
                            {
                                Console.WriteLine("(" + plans.Length + ") All plans");
                            }

                            string selectedPlanS = Program.GetInput("Which plan do you want to use: ");
                            int    selectedPlan  = -1;
                            if (int.TryParse(selectedPlanS, out selectedPlan))
                            {
                                if (selectedPlan == plans.Length)
                                {
                                    return(plans);
                                }
                                else
                                {
                                    return new Plan[] { plans[selectedPlan] }
                                };
                            }
                        }
                    }
                }
            }
            throw new Exception("Please select a plan");
        }
Beispiel #9
0
 public void OnCompleted(GraphResponse response)
 {
     try
     {
         List <string> unGrantedPermissions = new List <string>();
         var           array = response.JSONObject.OptJSONArray("data");
         for (int i = 0; i < array.Length(); i++)
         {
             JSONObject actor = array.GetJSONObject(i);
             string     name  = actor.GetString("permission");
             if (actor.GetString("status") != "granted")
             {
                 unGrantedPermissions.Add(name);
             }
         }
         if (unGrantedPermissions.Count > 0)
         {
             LoginManager loginManager = LoginManager.Instance;
             loginManager.RegisterCallback(null, this);
             loginManager.LogInWithReadPermissions(Param as Activity, unGrantedPermissions);
             return;
         }
         UpdateAccessToken();
         ViewModelResponse(ChallengesFacebookShareResponseType.Successed);
     }
     catch (Java.Lang.Exception ex)
     {
         ViewModelResponse(ChallengesFacebookShareResponseType.Error);
     }
 }
Beispiel #10
0
        private static string GetUserForId(string id)
        {
            if (id == null)
            {
                return(null);
            }
            if (users.ContainsKey(id))
            {
                return(users[id]);
            }
            else
            {
                using (var httpClient = PrepareUsersClient())
                {
                    try
                    {
                        var user = GraphResponse <UserResponse> .Get(id, httpClient).Result;

                        users.Add(id, user.DisplayName);
                        return(user.DisplayName);
                    }
                    catch
                    {
                        return(null);
                    }
                }
            }
        }
        // export a plan and optionally output it as json
        public static Plan Export(bool output = true)
        {
            Plan plan = SelectPlan();

            using (var httpClient = PreparePlannerClient())
            {
                // get all buckets, tasks and task details
                var buckets = GraphResponse <BucketResponse> .Get("plans/" + plan.Id + "/buckets", httpClient).Result.Buckets;

                var tasks = GraphResponse <TaskResponse> .Get("plans/" + plan.Id + "/tasks", httpClient).Result.Tasks;

                foreach (var task in tasks)
                {
                    task.TaskDetail = GraphResponse <TaskDetailResponse> .Get("tasks/" + task.Id + "/details", httpClient).Result;
                }

                // put tasks in buckets so that the plan object has all data hierarchically
                foreach (var bucket in buckets)
                {
                    bucket.Tasks = tasks.Where(t => t.BucketId == bucket.Id).ToArray();
                }

                plan.Buckets = buckets;
            }

            if (output)
            {
                Console.WriteLine(Serialize.ToJson(plan));
            }

            return(plan);
        }
 public void OnCompleted(JSONObject @object, GraphResponse response)
 {
     try
     {
         if (response.Error != null)
         {
             System.Diagnostics.Debug.WriteLine(response.Error.ErrorMessage.ToString());
             var fbArgs = new FBEventArgs <string>(null, FacebookActionStatus.Error, response.Error.ErrorMessage.ToString());
             _onUserData?.Invoke(CrossFacebookClient.Current, fbArgs);
             _userDataTcs?.TrySetResult(new FacebookResponse <string>(fbArgs));
         }
         else
         {
             var fbArgs = new FBEventArgs <string>(@object?.ToString(), FacebookActionStatus.Completed);
             _onUserData?.Invoke(CrossFacebookClient.Current, fbArgs);
             _userDataTcs?.TrySetResult(new FacebookResponse <string>(fbArgs));
         }
     }
     catch (JSONException ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.ToString());
         var fbArgs = new FBEventArgs <string>(null, FacebookActionStatus.Error, ex.ToString());
         _onUserData?.Invoke(CrossFacebookClient.Current, fbArgs);
         _userDataTcs?.TrySetResult(new FacebookResponse <string>(fbArgs));
     }
 }
Beispiel #13
0
        public static async Task <GraphGroup> CreateGroup(GroupRequest request)
        {
            var uriEndPoint = $"{Constants.ResourceUrl}/{Constants.GraphApiVersion}/groups";

            GraphResponse <GraphGroup> result = null;
            var group = new GraphGroup()
            {
                Description = request.AccountId,
                DisplayName = request.AccountName,
                GroupTypes  = new List <string>()
                {
                    "Unified"
                },
                MailEnabled     = true,
                MailNickname    = request.AccountId,
                SecurityEnabled = false
            };

            // Create group with Graph API
            result = await Client.GetData <GraphGroup>(HttpMethod.Post, uriEndPoint, group).ConfigureAwait(false);

            if (!result.IsSuccessfull)
            {
                throw new Exception($"Error: group not created - API error: {result.Message}");
            }

            return(result.Data);
        }
        public void OnCompleted(GraphResponse response)
        {
            var currentTcs = _requestTcs;

            var _onEvent = _onRequestData;

            if (response.Request.HttpMethod == HttpMethod.Post)
            {
                currentTcs = _postTcs;

                _onEvent = _onPostData;
            }
            else if (response.Request.HttpMethod == HttpMethod.Delete)
            {
                currentTcs = _deleteTcs;
                _onEvent   = _onDeleteData;
            }

            if (response.Error != null)
            {
                System.Diagnostics.Debug.WriteLine(response.Error.ErrorMessage.ToString());
                var fbResponse = new FBEventArgs <string>(null, FacebookActionStatus.Error, response.Error.ErrorMessage);
                _onEvent?.Invoke(CrossFacebookClient.Current, fbResponse);
                currentTcs?.TrySetResult(new FacebookResponse <string>(fbResponse));
            }
            else
            {
                var fbResponse = new FBEventArgs <string>(response?.JSONObject?.ToString(), FacebookActionStatus.Completed);
                _onEvent?.Invoke(CrossFacebookClient.Current, fbResponse);
                currentTcs?.TrySetResult(new FacebookResponse <string>(fbResponse));
            }
        }
Beispiel #15
0
 /// <summary>
 /// Has got user data from facebook
 /// </summary>
 /// <param name="object">JSON data object</param>
 /// <param name="response">Response</param>
 public void OnCompleted(JSONObject @object, GraphResponse response)
 {
     if (@object != null)
     {
         JsonConvert.PopulateObject(@object.ToString(), FacebookResult);
     }
     FacebookDataCallback?.OnUserDataReceived(FacebookResult);
 }
Beispiel #16
0
        public void OnCompleted(Org.Json.JSONObject json, GraphResponse response)
        {
            string          data   = json.ToString();
            FacebookProfile result = JsonConvert.DeserializeObject <FacebookProfile>(data);

            System.Diagnostics.Debug.Write("THE DATA IS ******* : " + data);
            mTest.Text = data;
        }
Beispiel #17
0
        public void OnCompleted(Org.Json.JSONObject json, GraphResponse response)
        {
            string data = json.ToString();

            email = json.GetString("email");

            var result = JsonConvert.DeserializeObject(data);
        }
 public void OnCompleted(GraphResponse p0)
 {
     if (tcsText != null)
     {
         tcsText.TrySetResult((p0.Error == null) ? true : false);
         tcsText = null;
     }
 }
Beispiel #19
0
 public async void OnCompleted(GraphResponse p0)
 {
     if (p0.Error == null)
     {
         // TODO messagin center
         //MessagingCenter.Send<FBPostCallback, bool> (this, "FacebookDataRetriveDone", true);
     }
 }
Beispiel #20
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = "users/{id}")]
            [RequestBodyType(typeof(User), "User")]
            HttpRequest req, string id, ILogger log, ExecutionContext context)
        {
            log.LogInformation($"{context?.FunctionName} processed a HTTP request.");
            // TelemetryClient.Context.Operation.Id = context?.InvocationId.ToString(); // No longer needed?

            string requestBody = new StreamReader(req.Body).ReadToEnd();
            var    user        = JsonConvert.DeserializeObject <User>(requestBody);

            if (user is null)
            {
                return(new BadRequestObjectResult("No User definition specified in body."));
            }

            user.Id = user.Id ?? id;

            if (user.Id != id)
            {
                return(new BadRequestObjectResult("User Id provided in request JSON does not match the Id provided in the route."));
            }

            try
            {
                var query    = GremlinHelper.UpdateVertexQuery(id, user, log);
                var response = new GraphResponse(await GremlinClient.SubmitAsync <dynamic>(query));

                GremlinHelper.ThrowIfResponseInvalid(response);

                GremlinHelper.GraphTelemetryEvent(TelemetryClient, "GraphVertexUpdate", response, "vertex", "user");

                if (response.Entities == null || response.Entities.Count() < 1)
                {
                    return(new NotFoundResult());
                }

                user = response.GetEntityAsType <User>();
            }
            catch (ResponseException ex)
            {
                GremlinHelper.HandleGraphResponseException(ex, log, context, TelemetryClient);
            }
            catch (Exception ex)
            {
                GremlinHelper.HandleGeneralException(ex, log, context, TelemetryClient);
            }

            return(user != null ?
                   new OkObjectResult(user)
            {
                StatusCode = 200
            } :
                   new OkObjectResult("Failed to update user.")
            {
                StatusCode = 500
            });
        }
Beispiel #21
0
            public void OnCompleted(JSONObject result, GraphResponse response)
            {
                var c = HandleSuccess;

                if (c != null)
                {
                    c(result.JavaCast <TResult>());
                }
            }
Beispiel #22
0
        private static void CreateBucket(string targetPlanId, Bucket bucket, bool addAssignments, HttpClient httpClient)
        {
            bucket.PlanId = targetPlanId;

            // reset all order hints as the exported values don't work
            bucket.OrderHint = " !";
            var newBucket = GraphResponse <Bucket> .Post("buckets", httpClient, bucket).Result;

            // if we are too quick the created bucket is not available yet, make sure it it there
            Thread.Sleep(5 * 1000);
            var verifyNewBucket = GraphResponse <Bucket> .Get("buckets/" + newBucket.Id, httpClient).Result;

            bucket.Tasks = bucket.Tasks.Reverse().ToArray();
            foreach (PlannerTask task in bucket.Tasks)
            {
                task.PlanId    = targetPlanId;
                task.BucketId  = newBucket.Id;
                task.OrderHint = " !";

                // assignments contain the users assigned to a task
                if (addAssignments)
                {
                    foreach (Assignment assignment in task.Assignments.Values)
                    {
                        assignment.OrderHint = " !";
                    }
                }
                else
                {
                    task.Assignments = new Dictionary <string, Assignment>();
                }
                var newTask = GraphResponse <PlannerTask> .Post("tasks", httpClient, task).Result;

                // remember new task id for next loop
                task.Id = newTask.Id;
            }

            // if we are too quick the created tasks are not available yet
            Thread.Sleep(5 * 1000);

            foreach (PlannerTask task in bucket.Tasks)
            {
                var newTaskDetailsResponse = GraphResponse <TaskDetailResponse> .Get("tasks/" + task.Id + "/details", httpClient).Result;

                foreach (var checklist in task.TaskDetail.Checklist.Values)
                {
                    checklist.OrderHint = " !";
                }
                foreach (var reference in task.TaskDetail.References.Values)
                {
                    // same as order hint
                    reference.PreviewPriority = " !";
                }
                var updatedTaskDetailsResponse = GraphResponse <TaskDetailResponse> .Patch("tasks/" + task.Id + "/details", httpClient, task.TaskDetail, newTaskDetailsResponse.OdataEtag).Result;
            }
        }
Beispiel #23
0
        public void OnCompleted(Org.Json.JSONObject p0, GraphResponse p1)
        {
            var c = HandleSuccess;

            if (c != null)
            {
                var email = p0.OptString("email");
                c(email);
            }
        }
Beispiel #24
0
 // Implement GraphRequest.ICallback
 void GraphRequest.ICallback.OnCompleted(GraphResponse response)
 {
     if (response.Error != null)
     {
         ActivityCompleted(FBStatus.Error, response.Error.ErrorMessage, null);
     }
     else
     {
         ActivityCompleted(FBStatus.Success, "Authentication Completed.", response.RawResponse);
     }
 }
 public void OnCompleted(JSONObject p0, GraphResponse p1)
 {
     try
     {
         _fba.OnFinished(true, p0.GetString("email"));
     }
     catch (JSONException e)
     {
         Console.WriteLine(e.ToString());
     }
 }
Beispiel #26
0
        public void OnCompleted(JSONObject json, GraphResponse response)
        {
            try
            {
                string fbId    = json.GetString("id");
                string fbToken = AccessToken.CurrentAccessToken.Token;
                string fbEmail = json.GetString("email");

                _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();

                    ((ChattyApplication)this.Activity.Application).RegisterToNotificationsHub();

                    var f       = new ChatFragment();
                    f.Arguments = new Bundle();
                    f.Arguments.PutString("Email", _email);
                    this.FragmentManager.BeginTransaction()
                    .AddToBackStack("BeforeChatFragment")
                    .Replace(Resource.Id.ContentLayout, f, "ChatFragment")
                    .Commit();
                },
                                        // Service call error
                                        (error) =>
                {
                    Toast.MakeText(this.Activity.Application, error, ToastLength.Long).Show();
                },
                                        // Service call finished
                                        () =>
                {
                    // Allow user to tap views
                    ((MainActivity)this.Activity).UnblockUI();
                });
            }
            catch (Exception ex)
            {
                ((MainActivity)this.Activity).UnblockUI();

                Toast.MakeText(this.Activity.ApplicationContext, "Error", ToastLength.Long).Show();
            }
            finally
            {
                LoginManager.Instance.LogOut();
            }
        }
Beispiel #27
0
        public void OnCompleted(Org.Json.JSONObject json, GraphResponse response)
        {
            string          data   = json.ToString();
            FacebookProfile result = JsonConvert.DeserializeObject <FacebookProfile>(data);

            _userService.SetUser(result);

            if (FacebookProfileHelper.IsRegistred())
            {
                StartActivity(typeof(TabPageView));
            }
        }
        public void OnCompleted(JSONObject jsonObject, GraphResponse response)
        {
            var id         = string.Empty;
            var first_name = string.Empty;
            var last_name  = string.Empty;
            var email      = string.Empty;
            var pictureUrl = string.Empty;

            if (jsonObject.Has("id"))
            {
                id = jsonObject.GetString("id");
            }

            if (jsonObject.Has("first_name"))
            {
                first_name = jsonObject.GetString("first_name");
            }

            if (jsonObject.Has("last_name"))
            {
                last_name = jsonObject.GetString("last_name");
            }

            if (jsonObject.Has("email"))
            {
                email = jsonObject.GetString("email");
            }

            if (jsonObject.Has("picture"))
            {
                var picture = jsonObject.GetJSONObject("picture");
                if (picture.Has("data"))
                {
                    var data = picture.GetJSONObject("data");
                    if (data.Has("url"))
                    {
                        pictureUrl = data.GetString("url");
                    }
                }
            }

            var fbUser = new FBUser()
            {
                Id        = id,
                Email     = email,
                FirstName = first_name,
                LastName  = last_name,
                PicUrl    = pictureUrl,
                Token     = AccessToken.CurrentAccessToken.Token
            };

            _onLoginComplete?.Invoke(fbUser, string.Empty);
        }
Beispiel #29
0
        private static void CreateBucket(string targetPlanId, Bucket bucket, bool addAssignments, HttpClient httpClient)
        {
            bucket.PlanId = targetPlanId;

            // reset all order hints as the exported values don't work
            bucket.OrderHint = " !";
            var newBucket = GraphResponse <Bucket> .Post("buckets", httpClient, bucket).Result;

            // if we are too quick the created bucket is not available yet, make sure it it there
            Thread.Sleep(5 * 1000);
            var verifyNewBucket = GraphResponse <Bucket> .Get("buckets/" + newBucket.Id, httpClient).Result;

            SaveTasks(targetPlanId, newBucket.Id, addAssignments, bucket.Tasks, httpClient);
        }
Beispiel #30
0
        private async Task <string> SendGraphGetRequest(string api, string query)
        {
            // First, use ADAL to acquire a token using the app's identity (the credential)
            // The first parameter is the resource we want an access_token for; in this case, the Graph API.
            AuthenticationResult result = await authContext.AcquireTokenAsync("https://graph.windows.net", credential);

            // For B2C user managment, be sure to use the 1.6 Graph API version.
            HttpClient http = new HttpClient();
            string     url  = "https://graph.windows.net/" + tenant + api + "?" + Globals.aadGraphVersion;

            if (!string.IsNullOrEmpty(query))
            {
                url += "&$filter=userPrincipalName eq '" + query + "'";
            }

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("GET " + url);
            Console.WriteLine("Authorization: Bearer " + result.AccessToken.Substring(0, 80) + "...");
            Console.WriteLine("");

            // Append the access token for the Graph API to the Authorization header of the request, using the Bearer scheme.
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            HttpResponseMessage response = await http.SendAsync(request);

            if (!response.IsSuccessStatusCode)
            {
                string error = await response.Content.ReadAsStringAsync();

                object formatted = JsonConvert.DeserializeObject(error);
                throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented));
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine((int)response.StatusCode + ": " + response.ReasonPhrase);
            Console.WriteLine("");
            var res = await response.Content.ReadAsStringAsync();

            var users = new List <User>();


            GraphResponse user = JsonConvert.DeserializeObject <GraphResponse>(res);
            var           a    = JsonConvert.SerializeObject(user.value);

            users = JsonConvert.DeserializeObject <List <User> >(a);
            var b = JsonConvert.SerializeObject(users);

            return(b);
        }
 public void OnCompleted(Org.Json.JSONObject json, GraphResponse response)
 {
     string data = json.GetString("email");
     email.Text = data;
 }
Beispiel #32
0
			public void OnCompleted(Org.Json.JSONObject result, GraphResponse response)
			{
				var fbUser = _initialToken ?? new FacebookUser();
				fbUser.User = JsonConvert.DeserializeObject<User>(response.RawResponse);
				fbUser.User.ProfilePictureUrl =  string.Format("https://graph.facebook.com/{0}/picture?width={1}&height={1}", fbUser.User.ID, Constants.FBProfilePicSize);
				_completion.TrySetResult(fbUser);
			}
Beispiel #33
0
 public void OnCompleted(Org.Json.JSONObject json, GraphResponse response)
 {
     
     string data = json.ToString();
     FacebookResult result = JsonConvert.DeserializeObject<FacebookResult>(data);
 }
		public async void OnCompleted(Org.Json.JSONObject json, GraphResponse response){
			string tag = "OnCompleted";
			Log.Debug (tag, "Lel, datos :v");
			try{
			string email = json.GetString ("email");
			Log.Debug (tag, "el email debería ser: "+email);

			if (email == "" || email == null || email == "null") {
				//aqui vamos a cachar si no hay email para no hacer el registro.
			} else {

				datosfb.Add ("email", email);

				//ya tenemos todo, ahora podemos mandarlo!, tal vez aqui considere poner la foto de perfil y el nombre en la pantalla

				string resp = await plifserver.PostMultiPartForm ("http://plif.mx/pages/log_reg_face", null, "nada", "file[]", "image/jpeg", datosfb, true);
				Log.Debug (tag,"LA RESPUESTA!!!: "+resp);
        		JsonValue respuesta = JsonValue.Parse(resp);
				//Estructura de respuesta: [{"u":{"id":"225","username":"******","nombre":"Rutiaga","apellidos":"Cervantes","email":"*****@*****.**","rol":"cliente","facebook_id":"10204786604253973","puntos":"100"},"iu":{"ruta":"https:\/\/graph.facebook.com\/10204786604253973\/picture?height=800&width=800&migration_overrides=%7Boctober_2012%3Atrue%7D"}}]
				if (respuesta != null) {
					var prefs = this.GetSharedPreferences("RunningAssistant.preferences", FileCreationMode.Private);
					var editor = prefs.Edit ();

					string n=respuesta[0]["u"]["nombre"];
					string ap=respuesta[0]["u"]["apellidos"];

					editor.PutString ("id", respuesta[0]["u"]["id"]);
					editor.PutString ("nombre", n+ap);
					editor.PutString ("email", respuesta[0]["u"]["email"]);
					editor.PutString ("img_perfil", respuesta[0]["iu"]["ruta"]);
					editor.Commit();

					//JA

					//Toast.MakeText (this, "Inicio de sesión correcto", ToastLength.Long).Show();
					StartActivity(typeof(MainActivity));
					Finish();

				} else {
						Toast.MakeText (this, "Há ocurido un inconveniente. Por favor inténtalo de nuevo!", ToastLength.Long).Show();
				}

				

			}
				//CATCH
			}catch(Exception ex){
				Log.Debug ("OnCompleted", "Algo Salio mal en el OnCompleted! " + ex);
				//Toast.MakeText (this, "Algo salió mal. Por favor inténtalo de nuevo.", ToastLength.Long).Show();

				infoface = FindViewById<LinearLayout> (Resource.Id.infoface);
				infologin = FindViewById<LinearLayout> (Resource.Id.infologin);

				infologin.Visibility = ViewStates.Visible;
				infoface.Visibility = ViewStates.Gone;

			}

		}