public override async System.Threading.Tasks.Task GrantCustomExtension(OAuthGrantCustomExtensionContext context) { if(context.GrantType.ToLower() == "facebook") { var fbClient = new FacebookClient(context.Parameters.Get("accesstoken")); dynamic mainDataResponse = await fbClient.GetTaskAsync("me", new { fields = "first_name, last_name, picture" }); dynamic friendListResponse = await fbClient.GetTaskAsync("me/friends"); var friendsResult = (IDictionary<string, object>)friendListResponse; var friendsData = (IEnumerable<object>)friendsResult["data"]; var friendsIdList = new List<string>(); foreach (var item in friendsData) { var friend = (IDictionary<string, object>)item; friendsIdList.Add((string)friend["id"]); } User user = await CreateOrUpdateUser(mainDataResponse.id, mainDataResponse.first_name, mainDataResponse.last_name, mainDataResponse.picture.data.url, friendsIdList); var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(_fbIdKey, mainDataResponse.id)); identity.AddClaim(new Claim(_idKey, user.Id.ToString())); await base.GrantCustomExtension(context); context.Validated(identity); } return; }
// GET: Facebook public async Task<ActionResult> Index() { var access_token = HttpContext.Items["access_token"].ToString(); if(access_token != null) { try { var appsecret_proof = access_token.GenerateAppSecretProof(); var fb = new FacebookClient(access_token); //Get current user's profile dynamic myInfo = await fb.GetTaskAsync("me?fields=first_name,last_name,link,locale,email,name,birthday,gender,location,bio,age_range".GraphAPICall(appsecret_proof)); //var facebookProfile = DynamicExtension.ToStatic<FacebookProfileViewModel>(myInfo); //get curent profile dynamic profileImgResult = await fb.GetTaskAsync("{0}/picture?width=200&height=200&redirect=false".GraphAPICall((string)myInfo.id, appsecret_proof)); //facebookProfile.ImageUrl = profileImgResult.data.url; var facebookProfile = new FacebookProfileViewModel() { } } catch (Exception) { throw; } } }
private async Task GetExtendedToken() { try { var accessToken = settings.Get<string>(FACEBOOK_TOKEN_SETTING); if (!string.IsNullOrEmpty(accessToken)) { var facebookClient = new FacebookClient(accessToken); dynamic parameters = new ExpandoObject(); parameters.client_id = APP_ID; parameters.client_secret = APP_SECRET; parameters.grant_type = "fb_exchange_token"; parameters.fb_exchange_token = accessToken; //parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html"; dynamic tokenResponse = await facebookClient.GetTaskAsync("oauth/access_token",parameters); if (!string.IsNullOrEmpty(tokenResponse.access_token)) { settings.Set<string>(FACEBOOK_TOKEN_SETTING, tokenResponse.access_token); settings.Set(FACEBOOK_TOKEN_EXPIRES_AT_SETTING, DateTime.UtcNow.AddSeconds((int)tokenResponse.expires).ToFileTimeUtc()); } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
public static void API( string endpoint, HttpMethod method, FacebookDelegate callback) { if (method != HttpMethod.GET) throw new NotImplementedException(); Task.Run(async () => { FacebookClient fb = new FacebookClient(_fbSessionClient.CurrentAccessTokenData.AccessToken); FBResult fbResult = null; try { var apiCall = await fb.GetTaskAsync(endpoint, null); if (apiCall != null) { fbResult = new FBResult(); fbResult.Text = apiCall.ToString(); fbResult.Json = apiCall as JsonObject; } } catch (Exception ex) { fbResult = new FBResult(); fbResult.Error = ex.Message; } if (callback != null) { Utils.RunOnUnityAppThread(() => { callback(fbResult); }); } }); }
public async Task<HttpResponseMessage> Login(string authToken) { var fb = new FacebookClient(authToken); fb.AppSecret = Environment.GetEnvironmentVariable("FacebookSecret"); dynamic result = await fb.GetTaskAsync("me"); var existingUser = (User)await _userService.GetUser(result.id); if (existingUser == null) { var newUser = await _userService.CreateUser(new User { Id = Guid.NewGuid(), FacebookId = result.id.ToString(), FacebookToken = authToken, Name = result.name.ToString(), UpdatedAt = DateTime.Now }); return Request.CreateResponse(HttpStatusCode.OK, newUser); } existingUser.Name = result.name.ToString(); existingUser.FacebookToken = authToken; existingUser.UpdatedAt = DateTime.Now; var updatedUser = await _userService.UpdateUser(existingUser); return Request.CreateResponse(HttpStatusCode.OK, updatedUser); }
private async void FetchFacebookNewFeed() { // get facebook new feed var fb = new Facebook.FacebookClient(Session.ActiveSession.CurrentAccessTokenData.AccessToken); var parameters = new Dictionary <string, object>(); parameters[""] = ""; dynamic result = await fb.GetTaskAsync("/me/home", parameters); foreach (var data in result[0]) { ISNPost tmp = new ISNPost(); ISNUser usr = new ISNUser(); try { tmp.id = data["id"]; tmp.message = data["message"]; usr.id = data["from"]["id"]; usr.name = data["from"]["name"]; usr.picture = "http://graph.facebook.com/" + data["from"]["id"] + "/picture"; tmp.user = usr; itemsList.Add(tmp); } catch (Exception exc) { continue; } } this.myProgressRing.Visibility = Visibility.Collapsed; }
/// <summary> /// Setups the application link. /// </summary> public static void Setup() { _app = new FacebookClient(); _app.AppId = "223453524434397"; _app.AppSecret = "3b6769b53e52b0d122d2572950d770bd"; dynamic parameters = new ExpandoObject(); parameters.client_id = _app.AppId; parameters.client_secret = _app.AppSecret; parameters.grant_type = "client_credentials"; Task<Object> connect = _app.GetTaskAsync("https://graph.facebook.com/oauth/access_token", parameters); connect.ContinueWith(task => { try { // Save the access token _app.AccessToken = JObject.Parse(task.Result.ToString()).Value<String>("access_token"); Connection |= FacebookState.Connected; } catch (AggregateException aex) { aex.Handle(e => { if (e is FacebookOAuthException) { } return true; }); } }); }
private void LoadUserInfo() { var fb = new FacebookClient(App.AccessToken); fb.GetCompleted += (o, e) => { if (e.Error != null) { Dispatcher.BeginInvoke(() => MessageBox.Show(e.Error.Message)); return; } var result = (IDictionary<string, object>)e.GetResultData(); Dispatcher.BeginInvoke(() => { var profilePictureUrl = string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", App.FacebookId, "square", App.AccessToken); this.MyImage.Source = new BitmapImage(new Uri(profilePictureUrl)); this.MyName.Text = String.Format("{0} {1}", (string)result["first_name"], (string)result["last_name"]); }); }; fb.GetTaskAsync("me"); }
private void LoadFacebookData() { var fb = new FacebookClient(App.FacebookAccessToken); fb.GetCompleted += (o, e) => { if (e.Error != null) { } var result = (IDictionary<string, object>)e.GetResultData(); Dispatcher.BeginInvoke(() => { var profilePictureUrl = string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", App.FacebookId, "square", App.FacebookAccessToken); ProfilePicture.Source = new BitmapImage(new Uri(profilePictureUrl)); FirstNameBox.Text = result["first_name"].ToString(); LastNameBox.Text = result["last_name"].ToString(); if (result["gender"].ToString().ToLower() == "male") GenderPicker.SelectedIndex = 1; var location = (IDictionary<string, object>)result["location"]; LocationBox.Text = location["name"].ToString(); //var favoriteteams = (List<IDictionary<string, object>>)result["favorite_teams"]; } ); }; fb.GetTaskAsync("me"); }
private async System.Threading.Tasks.Task RetriveUserInfo(AccessTokenData accessToken) { var client = new Facebook.FacebookClient(accessToken.AccessToken); dynamic result = null; bool failed = false; try { result = await client.GetTaskAsync("me?fields=id,birthday,first_name,last_name,middle_name,gender"); } catch(Exception e) { failed = true; } if(failed) { MessageDialog dialog = new MessageDialog("Facebook is not responding to our authentication request. Sorry."); await dialog.ShowAsync(); throw new Exception("Windows phone does not provide an exit function, so we have to crash the app."); } string fullName = string.Join(" ", new[] { result.first_name, result.middle_name, result.last_name }); string preferredName = result.last_name; bool? gender = null; if (result.gender == "female") { gender = true; } else if (result.gender == "male") { gender = false; } DateTime birthdate = DateTime.UtcNow - TimeSpan.FromDays(365 * 30); if (result.birthday != null) { birthdate = DateTime.Parse(result.birthday); } var currentUser = new Facebook.Client.GraphUser(result); long facebookId = long.Parse(result.id); UserState.ActiveAccount = await Api.Do.AccountFacebook(facebookId); if (UserState.ActiveAccount == null) { Frame.Navigate(typeof(CreatePage), new CreatePage.AutofillInfo { SocialId = facebookId, Authenticator = Authenticator.Facebook, Birthdate = birthdate, FullName = fullName, Gender = gender, PreferredName = preferredName }); } else { Frame.Navigate(typeof(MainPage), UserState.CurrentId); } }
public int ProcessFbOathResult(FacebookOAuthResult oauthResult) { var resultCode = 0; var accessToken = oauthResult.AccessToken; App.ViewModel.UserPreference.AccessKey = accessToken; var fbS = new FacebookClient(accessToken); fbS.GetCompleted += (o, res) => { if (res.Error != null) { resultCode = 1; return; } var result = (IDictionary<string, object>) res.GetResultData(); App.ViewModel.UserPreference.FbUserId = (string) result["id"]; App.ViewModel.UserPreference.Name = (string) result["name"]; App.ViewModel.LoadData(true); App.ViewModel.SaveSettings(); Dispatcher.BeginInvoke(() => { facebookImage.Source = App.ViewModel.UserPreference.UserImage; name.Text = App.ViewModel.UserPreference.Name; }); }; fbS.GetTaskAsync("me"); return resultCode; }
public async void ContinueWithWebAuthenticationBroker(WebAuthenticationBrokerContinuationEventArgs args) { ObjFBHelper.ContinueAuthentication(args); if (ObjFBHelper.AccessToken != null) { fbclient = new Facebook.FacebookClient(ObjFBHelper.AccessToken); //Fetch facebook UserProfile: dynamic result = await fbclient.GetTaskAsync("me"); string id = result.id; string email = result.email; string FBName = result.name; IsLoggedIn = true; btnFBLogin.Content = "Log out"; txtBlockContent.Text = "You're now logged in as " + FBName; var msgDialog = new MessageDialog("Hello, " + FBName, "Login successful"); await msgDialog.ShowAsync(); } else { var msgDialog = new MessageDialog("Check your credentials and try again", "Login failed"); await msgDialog.ShowAsync(); } }
public override async Task GrantCustomExtension(OAuthGrantCustomExtensionContext context) { if (context.GrantType.ToLower() == "facebook") { var fbClient = new FacebookClient(context.Parameters.Get("accesstoken")); dynamic response = await fbClient.GetTaskAsync("me", new { fields = "email, first_name, last_name" }); string id = response.id; string email = response.email; string firstname = response.first_name; string lastname = response.last_name; // place your own logic to lookup and/or create users.... // your choice of claims... var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("sub", $"{firstname} {lastname}")); identity.AddClaim(new Claim("role", id)); await base.GrantCustomExtension(context); context.Validated(identity); } return; }
/// <summary> /// Get the loged in user info based on the access token /// </summary> /// <param name="accessToken">Login returned access token</param> /// <returns>a dictionary with the user info values.</returns> public async Task<IDictionary<string, object>> GetLogedUserInfoAsync(string accessToken) { _fb = new FacebookClient(accessToken); return (IDictionary<string, object>)await _fb.GetTaskAsync("me"); }
private async void OnFacebookAuthenticationFinished(AccessTokenData session) { // here the authentication succeeded callback will be received. // put your login logic here try { FacebookClient client = new FacebookClient(session.AccessToken); //Graph request and result dynamic result = await client.GetTaskAsync("me"); //Getting current user from graph request result var currentUser = new Facebook.Client.GraphUser(result); //Do something with current user data var fad = new FacebookAccountData() { SocialNetworkId = currentUser.Id, Name = currentUser.Name, LastName = currentUser.LastName, FirstName = currentUser.FirstName, Email = "", Link = currentUser.Link, MiddleName = currentUser.MiddleName }; } catch (Exception ex) { //Handle exception } }
public async Task <ActionResult> FacebookCallback(string code) { var fb = new Facebook.FacebookClient(); dynamic result = await fb.PostTaskAsync("oauth/access_token", new { client_id = "<Your application ID>", client_secret = "<Your Application password>", redirect_uri = RedirectUri.AbsoluteUri, code = code }); var accessToken = result.access_token; Session["FacebookToken"] = accessToken; fb.AccessToken = accessToken; dynamic me = await fb.GetTaskAsync("me?fields=link,first_name,currency,last_name,email,gender,locale,timezone,verified,picture,age_range"); string _Email = me.email; string _Name = me.first_name + " " + me.last_name; using (AreaEntities db = new AreaEntities()) { // If user exists log him. var tmp = await db.users.Where(m => m.Email == _Email).FirstOrDefaultAsync(); if (tmp != null) { Session["Username"] = _Name; Session["Email"] = _Email; db.users.Attach(tmp); tmp.Token_facebook = accessToken; db.Entry(tmp).State = EntityState.Modified; db.SaveChanges(); FormsAuthentication.SetAuthCookie(_Email, false); return(RedirectToAction("Index", "Home")); } // If user doesn't exists, add it to the database with a default password. else { user ToAdd = new user() { Email = _Email, Name = _Name, Password = "", Token_facebook = accessToken }; db.users.Add(ToAdd); await db.SaveChangesAsync(); Session["Username"] = _Name; Session["Email"] = _Email; FormsAuthentication.SetAuthCookie(_Email, false); return(RedirectToAction("Index", "Home")); } } }
async private void graphCallButton_Click(object sender, RoutedEventArgs e) { FacebookClient fb = new FacebookClient(Session.ActiveSession.CurrentAccessTokenData.AccessToken); dynamic friendsTaskResult = await fb.GetTaskAsync("/me/friends"); MessageBox.Show("Graph Request for /me/friends: " + friendsTaskResult.ToString()); }
private async void Test_Click(object sender, RoutedEventArgs e) { var fb = new Facebook.FacebookClient(Session.ActiveSession.CurrentAccessTokenData.AccessToken); var parameters = new Dictionary <string, object>(); parameters[""] = ""; dynamic result = await fb.GetTaskAsync("/565811000225586", parameters); }
private async void RetriveUserInfo() { var token = Session.ActiveSession.CurrentAccessTokenData.AccessToken; var client = new Facebook.FacebookClient(token); dynamic result = await client.GetTaskAsync("me"); var currentUser = new Facebook.Client.GraphUser(result); this.userInfo.Text = this.BuildUserInfoDisplay(currentUser); }
private async void sChanged(object sender, ScrollViewerViewChangedEventArgs sve) { await Task.Run(async() => { ScrollViewer sv = (ScrollViewer)sender; //Debug.WriteLine(sv.ScrollableHeight + " , " + sv.VerticalOffset); if (sv.VerticalOffset >= sv.ScrollableHeight - 2000 && !loading) { loading = true; /*App.Progress.IsActive = true; App.Progress.Visibility = Windows.UI.Xaml.Visibility.Visible;*/ FacebookClient _fb = new FacebookClient(session.accessToken); dynamic parameters = new ExpandoObject(); parameters.access_token = session.accessToken; dynamic result = null; try { result = await _fb.GetTaskAsync(nextPage, parameters); } catch (FacebookOAuthException e) { Debug.WriteLine("Problem: " + e.StackTrace); /*App.Progress.IsActive = false; App.Progress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;*/ loading = false; return; } var friendResult = (IDictionary<string, object>)result; var data = (IEnumerable<object>)friendResult["data"]; foreach (var item in data) { var posts = (IDictionary<string, object>)item; await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { FacebookPost post = new FacebookPost(posts, session.userSession); feedStack.Children.Add(post); }); } Debug.WriteLine(friendResult + "\n\n" + nextPage); nextPage = (String)((IDictionary<string, object>)friendResult["paging"])["next"]; /*App.Progress.IsActive = false; App.Progress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;*/ loading = false; } }); }
private async System.Threading.Tasks.Task RetriveUserInfo() { profpic.ProfileId = App.FacebookId; var cli = new Facebook.FacebookClient(App.AccessToken); dynamic result = await cli.GetTaskAsync("me"); var currentUser = new Facebook.Client.GraphUser(result); fnfb.Text = currentUser.FirstName; lnfb.Text = currentUser.LastName; }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult (requestCode, resultCode, data); switch (resultCode) { case Result.Ok: { accessToken = data.GetStringExtra("AccessToken"); string userId = data.GetStringExtra("UserId"); string error = data.GetStringExtra("Exception"); fb = new FacebookClient(accessToken); ImageView imgUser = FindViewById<ImageView>(Resource.Id.imgUser); TextView txtvUserName = FindViewById<TextView>(Resource.Id.txtvUserName); fb.GetTaskAsync("me").ContinueWith(t => { if (!t.IsFaulted) { var result = (IDictionary<string, object>)t.Result; // available picture types: square (50x50), small (50xvariable height), large (about 200x variable height) (all size in pixels) // for more info visit http://developers.facebook.com/docs/reference/api string profilePictureUrl = string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", userId, "square", accessToken); var bm = BitmapFactory.DecodeStream(new Java.Net.URL(profilePictureUrl).OpenStream()); string profileName = (string)result["name"]; RunOnUiThread(() => { imgUser.SetImageBitmap(bm); txtvUserName.Text = profileName; }); isLoggedIn = true; } else { Alert("Failed to Log In", "Reason: " + error, false, (res) => { }); } }); } break; case Result.Canceled: Alert ("Failed to Log In", "User Cancelled", false, (res) => {} ); break; default: break; } }
async private Task <string> CallFacebookFQL(String Query) { var fb = new Facebook.FacebookClient(App.AccessToken); var result = await fb.GetTaskAsync("fql", new { q = Query }); return(result.ToString()); }
public Task<FacebookProfile> GetFacebookPublicProfileAsync(long userId) { FacebookClient facebookClient = new FacebookClient(); Task<object> task = facebookClient.GetTaskAsync(userId.ToString(CultureInfo.InvariantCulture)); return task.ContinueWith( result => { dynamic me = result.Result; FacebookProfile userProfile = ReadProfileData(me); return userProfile; }, TaskContinuationOptions.ExecuteSynchronously); }
public static async Task <IList <T> > GetArrayAsync <T>(Facebook.FacebookClient facebookClient, string path) { dynamic response = await facebookClient.GetTaskAsync(path); var str = response.ToString() as string; if (str.IsNullOfEmpty()) { return(default(IList <T>)); } var result = await Newtonsoft.Json.JsonConvert.DeserializeObjectAsync <FbData <T> >(str); return(result.Data); }
// Load data for the ViewModel NewsItems protected async override void OnNavigatedTo(NavigationEventArgs e) { try { _item = App.ViewModel.ActivityItems.ElementAt(Convert.ToInt32(NavigationContext.QueryString["activityItem"])); if (_item == null) { throw new Exception("Er is geen activiteit mee gegeven als argument."); } if (_item.FacebookId == null || _item.FacebookId.Equals("") || !App.ViewModel.HasConnection) return; var fb = new FacebookClient { AppId = App.ViewModel.Appid, AccessToken = App.ViewModel.UserPreference.AccessKey ?? App.ViewModel.GenericId }; fb.GetCompleted += async (o, res) => { if (res.Error != null) { return; } var result = (IDictionary<string, object>)res.GetResultData(); var data = (IList<object>)result["data"]; var eventData = ((IDictionary<string, object>)data.ElementAt(0)); _item.RsvpStatus = await GetRsvp(_item); _item.FriendsPics = await FriendImages(_item); _item.Attendings = Convert.ToInt32(eventData["attending_count"]); _item.ImageUri = (string)eventData["pic"]; Dispatcher.BeginInvoke(()=>DataContext = _item); }; // query to get all the friends var query = string.Format("SELECT eid,attending_count, pic FROM event WHERE eid = {0}", _item.FacebookId); // Note: For windows phone 7, make sure to add [assembly: InternalsVisibleTo("Facebook")] if you are using anonymous objects as parameter. await fb.GetTaskAsync("fql", new { q = query }); } catch (Exception) { NavigationService.Navigate(new Uri("/Pages/MainPage.xaml", UriKind.Relative)); } }
private async static void ExecuteAsyncMethod() { var fb = new FacebookClient(); try { dynamic result = await fb.GetTaskAsync("/4"); Console.WriteLine("Name: {0}", result.name); } catch (FacebookApiException ex) { Console.WriteLine(ex.Message); } }
public Task<string> GetLastNameAsync(long userId) { FacebookClient fb = new FacebookClient(); dynamic parameters = new ExpandoObject(); parameters.q = string.Format("SELECT last_name FROM user WHERE uid='{0}'", userId); Task<object> task = fb.GetTaskAsync("fql", parameters); return task.ContinueWith( result => { dynamic response = result.Result; string lastname = response.data[0].last_name; return lastname; }, TaskContinuationOptions.ExecuteSynchronously); }
public async Task<string> GetExtendedAccessTokenAsync(string shortLivedToken) { var client = new FacebookClient(); string extendedToken = ""; dynamic result = await client.GetTaskAsync("/oauth/access_token", new { grant_type = "fb_exchange_token", client_id = _appId, client_secret = _appSecret, fb_exchange_token = shortLivedToken }); extendedToken = result.access_token; return extendedToken; }
public async Task<IList<FacebookIdentity>> GetFriends(IdentityUser user) { var accessToken = GetAccessToken(user); var client = new FacebookClient(accessToken); var data = await client.GetTaskAsync(string.Format("{0}/friends", GetUserIdentifier(user))); var settings = new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Ignore, NullValueHandling = NullValueHandling.Ignore }; var friends = JsonConvert.DeserializeObject<FacebookDataWrapper<IList<FacebookIdentity>>>(data.ToString(), settings); Log.InfoFormat("Pulled Facebook friends for user. UserId={0} FacebookId={1}", user.Id, GetUserIdentifier(user)); return friends.Data; }
public String ExtendFacebook(String accessToken) { FacebookClient _fb = new FacebookClient(accessToken); String request = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=fb_exchange_token&fb_exchange_token={2}", Constants.FacebookAppId, Constants.FacebookAppSecret, accessToken); dynamic extended; try { extended = _fb.GetTaskAsync(request); } catch (FacebookOAuthException e) { Debug.WriteLine(e.StackTrace); return null; } var extendDic = (IDictionary<string, object>)extended; return (String)extendDic["access_token"]; }
public async Task<RootObject> GetAmigos(string userToken) { var fb = new FacebookClient(userToken); object result = null; await fb.GetTaskAsync("me/friends?limit=9000").ContinueWith(async (t) => { if (!t.IsFaulted) { var jsonString = (await t).ToString(); var i = JsonConvert.DeserializeObject <RootObject>(jsonString); result = i; return i; } return null; }); return (RootObject)result; }
public void fb(string token) { FacebookClient fb = new FacebookClient (token); fb.GetCompleted += (sender, e) => { System.Diagnostics.Debug.WriteLine("in FB Completed"); var ex = e.Error; if (ex != null){ System.Diagnostics.Debug.WriteLine("=====> FB Error"); }else{ //var t = (String) e.GetResultData(); //var res = JObject.Parse (t); System.Diagnostics.Debug.WriteLine("====>> in FB"+e.GetResultData().ToString()); } }; fb.GetTaskAsync ("1698903283671929?fields=feed"); }
public async void FbFeed(ListItemTemplate session) { FacebookClient _fb = new FacebookClient(session.accessToken); dynamic parameters = new ExpandoObject(); parameters.access_token = session.accessToken; dynamic result = null; try{ result = await _fb.GetTaskAsync("me/home", parameters); } catch (FacebookOAuthException e) { Debug.WriteLine("Problem: \n" + e.Message); App.Progress.IsActive = false; App.Progress.Visibility = Windows.UI.Xaml.Visibility.Collapsed; return; } var friendResult = (IDictionary<string, object>)result; var data = (IEnumerable<object>)friendResult["data"]; FacebookFeed fbFeed = new FacebookFeed(session); foreach (var item in data) { var posts = (IDictionary<string, object>)item; FacebookPost post = new FacebookPost(posts, session.userSession); fbFeed.feedStack.Children.Add(post); } fbFeed.nextPage = (String)((IDictionary<string, object>)friendResult["paging"])["next"]; fbFeed.previousPage = (String)((IDictionary<string, object>)friendResult["paging"])["previous"]; await Task.Run(() => { fbFeed.realtimeUpdate(); }); await Task.Run(() => { fbFeed.timeUpdate(); }); rightPane.Children.Add(fbFeed); App.Progress.IsActive = false; App.Progress.Visibility = Windows.UI.Xaml.Visibility.Collapsed; }
public async Task<IDictionary<string,object>> RecuperaDadosUsuario(string userToken) { // This uses Facebook Graph API // See https://developers.facebook.com/docs/reference/api/ for more information. var fb = new FacebookClient(userToken); object result = null; await fb.GetTaskAsync("me").ContinueWith(async (t) => { if (!t.IsFaulted) { var i = (IDictionary<string, object>)(await t); result = i; return i; } return null; }); return (IDictionary<string, object>)result; }
private static void ExecuteAsyncMethod() { var fb = new FacebookClient(); var task = fb.GetTaskAsync("/4"); task.ContinueWith( t => { if (t.Exception == null) { dynamic result = t.Result; Console.WriteLine("Name: {0}", result.name); } else { Console.WriteLine("error occurred"); } }); }
public async Task<FacebookUser> GetPersonalInfo(IdentityUser user) { var accessToken = GetAccessToken(user); var client = new FacebookClient(accessToken); var data = await client.GetTaskAsync(GetUserIdentifier(user)); var settings = new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Ignore, NullValueHandling = NullValueHandling.Ignore }; var me = JsonConvert.DeserializeObject<FacebookUser>(data.ToString(), settings); var picture = await GetPicture(user, GetUserIdentifier(user), FacebookPictureSize.Large); me.Picture = picture; Log.InfoFormat("Pulled Facebook profile data for user. UserId={0} FacebookId={1}", user.Id, me.Id); return me; }
private async void OnQueryButtonClick(object sender, RoutedEventArgs e) { this.myProgressRing.Visibility = Visibility.Visible; var fb = new Facebook.FacebookClient(Session.ActiveSession.CurrentAccessTokenData.AccessToken); var parameters = new Dictionary <string, object>(); parameters[""] = ""; dynamic result = await fb.GetTaskAsync("/me/home", parameters); List <ISNPost> itemsList = new List <ISNPost>(); foreach (var data in result[0]) { ISNPost tmp = new ISNPost(); ISNUser usr = new ISNUser(); try { tmp.id = data["id"]; tmp.message = data["message"]; usr.id = data["from"]["id"]; usr.name = data["from"]["name"]; usr.picture = "http://graph.facebook.com/" + data["from"]["id"] + "/picture"; tmp.user = usr; itemsList.Add(tmp); } catch (Exception exc) { continue; } } newFeedList.ItemsSource = itemsList; this.myProgressRing.Visibility = Visibility.Collapsed; }
private async System.Threading.Tasks.Task RetriveUserInfo(AccessTokenData accessToken) { var client = new Facebook.FacebookClient(accessToken.AccessToken); dynamic result = null; bool failed = false; try { result = await client.GetTaskAsync("me?fields=id,birthday,first_name,last_name,middle_name,gender"); } catch (Exception e) { failed = true; } if (failed) { MessageDialog dialog = new MessageDialog("Facebook is not responding to our authentication request. Sorry."); await dialog.ShowAsync(); throw new Exception("Windows phone does not provide an exit function, so we have to crash the app."); } string fullName = string.Join(" ", new[] { result.first_name, result.middle_name, result.last_name }); string preferredName = result.last_name; bool? gender = null; if (result.gender == "female") { gender = true; } else if (result.gender == "male") { gender = false; } DateTime birthdate = DateTime.UtcNow - TimeSpan.FromDays(365 * 30); if (result.birthday != null) { birthdate = DateTime.Parse(result.birthday); } var currentUser = new Facebook.Client.GraphUser(result); long facebookId = long.Parse(result.id); UserState.ActiveAccount = await Api.Do.AccountFacebook(facebookId); if (UserState.ActiveAccount == null) { Frame.Navigate(typeof(CreatePage), new CreatePage.AutofillInfo { SocialId = facebookId, Authenticator = Authenticator.Facebook, Birthdate = birthdate, FullName = fullName, Gender = gender, PreferredName = preferredName }); } else { Frame.Navigate(typeof(MainPage), UserState.CurrentId); } }