public void Publish_Photo_To_Existing_Album()
        {
            #if DEBUG
            string photoPath = @"..\..\..\Facebook.Tests\bin\Debug\monkey.jpg";
            #else
            string photoPath = @"..\..\..\Facebook.Tests\bin\Release\monkey.jpg";
            #endif
            string albumId = ConfigurationManager.AppSettings["AlbumId"];
            byte[] photo = File.ReadAllBytes(photoPath);

            FacebookClient app = new FacebookClient();
            dynamic parameters = new ExpandoObject();
            parameters.access_token = ConfigurationManager.AppSettings["AccessToken"];
            parameters.message = "This is a test photo of a monkey that has been uploaded " +
                                 "by the Facebook C# SDK (http://facebooksdk.codeplex.com)" +
                                 "using the Graph API";
            var mediaObject = new FacebookMediaObject
            {
                FileName = "monkey.jpg",
                ContentType = "image/jpeg",
            };
            mediaObject.SetValue(photo);
            parameters.source = mediaObject;

            dynamic result = app.Post(String.Format("/{0}/photos", albumId), parameters);

            Assert.NotNull(result);
            Assert.NotEqual(null, result.id);
        }
        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");
        }
Esempio n. 3
0
        private void GraphApiAsyncExample()
        {
            var fb = new FacebookClient(_accessToken);

            fb.GetCompleted +=
                (o, e) =>
                {
                    // note: remember to always check the error for async methods
                    if (e.Error == null)
                    {
                        // there was no error, so process the result
                        dynamic result = e.GetResultData();
                        // note: for performance remeber to cache the GetResultData() or GetResultData<T>()
                        // every time you call it will deserialize the json string into object.

                        lblFirstName.Text = "First name: " + result.first_name;
                        lblLastName.Text = "Last name: " + result.last_name;
                    }
                    else
                    {
                        MessageBox.Show(e.Error.Message);
                    }
                };

            dynamic parameters = new ExpandoObject();
            parameters.fields = "first_name,last_name";

            //// if dynamic keyword is not supported.
            //var parameters = new Dictionary<string, object>
            //                     {
            //                         { "fields", "first_name,last_name" }
            //                     };

            fb.GetAsync("/me", parameters);
        }
        async public Task<AppLink> GetAppLinkAsync(string accessToken, string sourceUrl)
        {
            FacebookClient _client = new FacebookClient(accessToken);
            
            String finalUrl = String.Format("https://graph.facebook.com/v2.0/?ids={0}&type=al&fields=windows,windows_phone,windows_universal", sourceUrl);
            dynamic appLinkData = await _client.GetTaskAsync(finalUrl);
            List<Target> targets = new List<Target>();

            var outerShell = (IDictionary<string, object>)appLinkData[sourceUrl];
            if (outerShell.ContainsKey("windows"))
            {
                var windowsArray = (IEnumerable<object>)outerShell["windows"];
                var windowsObject = (IDictionary<string, object>)(windowsArray.First());
                targets.Add(new Target { Uri = (string)windowsObject["url"], Platform = Platform.Windows, Name = (string)windowsObject["app_name"] });
            }

            if (outerShell.ContainsKey("windows_phone"))
            {
                var windowsPhoneArray = (IEnumerable<object>)outerShell["windows_phone"];
                var windowsPhoneObject = (IDictionary<string, object>)(windowsPhoneArray.First());
                targets.Add(new Target { Uri = (string)windowsPhoneObject["url"], Platform = Platform.WindowsPhone, Name = (string)windowsPhoneObject["app_name"] });
            }

            if (outerShell.ContainsKey("windows_universal"))
            {
                var universalArray = (IEnumerable<object>)outerShell["windows_universal"];
                var universalObject = (IDictionary<string, object>)(universalArray.First());
                targets.Add(new Target { Uri = (string)universalObject["url"], Platform = Platform.Universal, Name = (string)universalObject["app_name"] });
            }

            return new AppLink {SourceUri =  sourceUrl, FallbackUri = sourceUrl, Targets = targets};
        }
Esempio n. 5
0
        // [TestCategory("RequiresOAuth")]
        public void publish_photo_to_application_album()
        {

#if DEBUG
            string photoPath = @"..\..\..\Facebook.Tests\bin\Debug\monkey.jpg";
#else
            string photoPath = @"..\..\..\Facebook.Tests\bin\Release\monkey.jpg";
#endif

            byte[] photo = File.ReadAllBytes(photoPath);
            FacebookClient app = new FacebookClient();
            dynamic parameters = new ExpandoObject();
            parameters.access_token = ConfigurationManager.AppSettings["AccessToken"];
            parameters.caption = "This is a test photo of a monkey that has been uploaded " +
                                 "by the Facebook C# SDK (http://facebooksdk.codeplex.com)" +
                                 "using the REST API";
            parameters.method = "facebook.photos.upload";
            parameters.uid = ConfigurationManager.AppSettings["UserId"];
            var mediaObject = new FacebookMediaObject
            {
                FileName = "monkey.jpg",
                ContentType = "image/jpeg",
            };
            mediaObject.SetValue(photo);
            parameters.source = mediaObject;
            dynamic result = app.Post(parameters);

            Assert.NotNull(result);
            Assert.NotEqual(result.aid, null);
        }
 public TypedObjectTests()
 {
     app = new FacebookClient();
     //app.Session = new FacebookSession
     //{
     //    AccessToken = ConfigurationManager.AppSettings["AccessToken"],
     //};
 }
 public dynamic DeleteTest(string accessToken, string path)
 {
     return Test("delete test", () =>
                                    {
                                        var fb = new FacebookClient(accessToken);
                                        return fb.Delete(path);
                                    });
 }
 public dynamic GetTestWithAccessToken(string accessToken)
 {
     return Test("get test with access token", () =>
                                                   {
                                                       var fb = new FacebookClient(accessToken);
                                                       return fb.Get("/me");
                                                   });
 }
        async private void DialogWebBrowserOnLoadCompleted(object sender, NavigationEventArgs args)
#endif
        {
            if (args.Uri.ToString().StartsWith("https://www.facebook.com/connect/login_success.html"))
            {
                if (ParentControlPopup != null)
                {
                    ParentControlPopup.IsOpen = false;
                }

                if (!args.Uri.Fragment.Contains("access_token"))
                {
                    // this callback is in return for the dialog, so just cancel it.

                    if (OnDialogFinished != null)
                    {
                        OnDialogFinished(WebDialogResult.WebDialogResultDialogCompleted);
                    }

                    return;
                }

                try
                {
                    var client = new FacebookClient();
                    var authResult = client.ParseOAuthCallbackUrl(args.Uri);

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

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

                    Session.ActiveSession.CurrentAccessTokenData = new AccessTokenData
                    {
                        AccessToken = authResult.AccessToken,
                        Expires = authResult.Expires,
                        FacebookId = (string)dict["id"],
                        AppId = Session.AppId
                    };

                    if (Session.OnFacebookAuthenticationFinished != null)
                    {
                        Session.OnFacebookAuthenticationFinished(Session.ActiveSession.CurrentAccessTokenData);
                    }

                    if (Session.OnSessionStateChanged != null)
                    {
                        Session.OnSessionStateChanged(LoginStatus.LoggedIn);
                    }
                }
                catch (Facebook.FacebookOAuthException exc)
                {
                    // TODO: (sanjeevd) catch appropriately
                }
            }
        }
        public void FqlSingleQueryTests(string accessToken)
        {
            Test("fql single query test", () =>
                                              {
                                                  var fb = new FacebookClient(accessToken);

                                                  return fb.Query("SELECT uid,name FROM  user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=me())");
                                              });
        }
        public dynamic GetTestWithoutAccessToken()
        {
            return Test("get test without access token", () =>
            {
                var fb = new FacebookClient();

                return fb.Get("4");
            });
        }
Esempio n. 12
0
 // Constructor
 public Page1()
 {
     InitializeComponent();
     _fbClient = new FacebookClient();
     FacebookLoginBrowser.Loaded += new RoutedEventHandler(FacebookLoginBrowser_Loaded);
     //Get_User(_fbClient);
     //Get_Post(_fbClient);
     //Post(_fbClient);
 }
        public AccountController(FacebookClient fb)
        {
            _fb = fb;

            var context = System.Web.HttpContext.Current;
            var url = context.Request.Url.Scheme + System.Uri.SchemeDelimiter + context.Request.Url.Host + (context.Request.Url.Port != 80 ? ":" + context.Request.Url.Port : "");

            _redirectUri = url + "/Account/FacebookCallback";
        }
Esempio n. 14
0
        public FacebookLogin(FacebookClient fb, string appId, string extendedPermissions)
        {
            if (fb == null)
                throw new ArgumentNullException("fb");
            if (string.IsNullOrWhiteSpace(appId))
                throw new ArgumentNullException("appId");

            _fb = fb;
            _loginUrl = GenerateLoginUrl(appId, extendedPermissions);
        }
 internal async Task PreloadUserInformation()
 {
     if (!String.IsNullOrEmpty(Session.ActiveSession.CurrentAccessTokenData.AccessToken))
     {
         FacebookClient client = new FacebookClient(Session.ActiveSession.CurrentAccessTokenData.AccessToken);
         dynamic result = await client.GetTaskAsync("me");
         
         Session.ActiveSession.CurrentAccessTokenData.FacebookId = (new GraphUser(result)).Id;
         AccessTokenDataCacheProvider.Current.SaveSessionData(Session.ActiveSession.CurrentAccessTokenData);
     }
 }
        public dynamic FqlMultiQueryTests(string accessToken)
        {
            return Test("fql multi query test", () =>
                                             {
                                                 var fb = new FacebookClient(accessToken);

                                                 return fb.Query(
                                                     "SELECT uid,name FROM  user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=me())",
                                                     "SELECT name FROM user WHERE uid=me()");
                                             });
        }
Esempio n. 17
0
 public void DeleteAction(string actionId)
 {
     if (!string.IsNullOrEmpty(actionId))
     {
         Task.Factory.StartNew(() =>
             {
                 var client = new FacebookClient(AccessToken);
                 client.Delete(string.Format("{0}", actionId));
             });
     }
 }
        public void Wall_Post_Publish()
        {
            FacebookClient app = new FacebookClient();
            dynamic parameters = new ExpandoObject();
            parameters.access_token = ConfigurationManager.AppSettings["AccessToken"];
            parameters.message = "This is a test message that has been published by the Facebook C# SDK on Codeplex. " + DateTime.UtcNow.Ticks.ToString();
            parameters.attribution = "Facebook C# SDK";

            dynamic result = app.Post("/me/feed", parameters);

            Assert.NotEqual(null, result.id);
        }
        async private void selectFriendsTextBox_Tapped(object sender, TappedRoutedEventArgs evtArgs)
        {
            FacebookClient fb = new FacebookClient(App.AccessToken);

            dynamic friendsTaskResult = await fb.GetTaskAsync("/me/friends");

            var result = (IDictionary<string, object>)friendsTaskResult;
            var data = (IEnumerable<object>)result["data"];
            foreach (var item in data)
            {
                var friend = (IDictionary<string, object>)item;
                if( ((string)friend["name"]).Contains("Hwang") ) FacebookData.Friends.Add(new Friend { Name = (string)friend["name"], id = (string)friend["id"], PictureUri = new Uri(string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", (string)friend["id"], "square", App.AccessToken)) });
            }
            Frame.Navigate(typeof(FriendSelector));
        }
        private async void LoadUserInfo()
        {
            FacebookClient fb = new FacebookClient(App.AccessToken);

            dynamic parameters = new ExpandoObject();
            parameters.access_token = App.AccessToken;
            parameters.fields = "name";

            dynamic result = await fb.GetTaskAsync("me", parameters);

            string profilePictureUrl = string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", App.FacebookId, "large", fb.AccessToken);

            this.MyImage.Source = new BitmapImage(new Uri(profilePictureUrl));
            this.MyName.Text = result.name;
        }
        public dynamic GraphVideoUploadTests(string accessToken, byte[] data, string contentType, string fileName)
        {
            return Test("graph video upload tests", () =>
                                                        {
                                                            var fb = new FacebookClient(accessToken);
                                                            var parameters = new Dictionary<string, object>();
                                                            parameters["source"] = new FacebookMediaObject
                                                                                       {
                                                                                           ContentType = contentType,
                                                                                           FileName = fileName
                                                                                       }.SetValue(data);
                                                            parameters["message"] = "graph video upload test";

                                                            return fb.Post("/me/videos", parameters);
                                                        });
        }
        // [TestCategory("RequiresOAuth")]
        public void Wall_Post_Publish_And_Delete()
        {
            FacebookClient app = new FacebookClient();
            dynamic parameters = new ExpandoObject();
            parameters.access_token = ConfigurationManager.AppSettings["AccessToken"];
            parameters.message = "This is a test message that has been published by the Facebook C# SDK on Codeplex. " + DateTime.UtcNow.Ticks.ToString();

            dynamic result = app.Post("/me/feed", parameters);

            Assert.NotEqual(null, result.id);

            // Delete methods should return 'true'
            var isDeleted = app.Delete(result.id);

            Assert.True(isDeleted);
        }
 public dynamic PostDictionaryTest(string accessToken)
 {
     return Test("post message with dictionary<string,object>",
                 () =>
                 {
                     var fb = new FacebookClient(accessToken);
                     return fb.Post("/me/feed",
                                    new Dictionary
                                        <string, object>
                                            {
                                                {
                                                    "message",
                                                    "dictionary<string,object> test from fb c# sdk"
                                                    }
                                            });
                 });
 }
Esempio n. 24
0
 private void FacebookLoginBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
 {
     FacebookOAuthResult oauthResult;
     if (FacebookOAuthResult.TryParse(e.Uri, out oauthResult))
     {
         if (oauthResult.IsSuccess)
         {
             _fbClient = new FacebookClient(oauthResult.AccessToken);
             _loggedIn = true;
             loginSucceeded();
         }
         else
         {
             MessageBox.Show(oauthResult.ErrorDescription);
         }
     }
 }
Esempio n. 25
0
        public void Publish_Global_News()
        {
            FacebookClient app = new FacebookClient();
            dynamic parameters = new ExpandoObject();
            parameters.method = "dashboard.addGlobalNews";

            var list = new List<object>();
            dynamic news1 = new ExpandoObject();
            news1.message = "This is a test news message. " + DateTime.UtcNow.Ticks.ToString();
            list.Add(news1);

            parameters.news = list;

            dynamic result = app.Post(parameters);

            long id;
            long.TryParse(result, out id);
            Assert.True(id > 0);
        }
Esempio n. 26
0
        private Uri GenerateLoginUrl(string appId, string extendedPermissions)
        {
            // for .net 3.5
            // var parameters = new Dictionary<string,object>
            // parameters["client_id"] = appId;
            dynamic parameters = new ExpandoObject();
            parameters.client_id = appId;
            parameters.redirect_uri = "https://apps.facebook.com/markakodtest/";

            // The requested response: an access token (token), an authorization code (code), or both (code token).
            parameters.response_type = "token";

            // list of additional display modes can be found at http://developers.facebook.com/docs/reference/dialogs/#display
            parameters.display = "popup";

            // add the 'scope' parameter only if we have extendedPermissions.
            if (!string.IsNullOrWhiteSpace(extendedPermissions))
                parameters.scope = extendedPermissions;

            // generate the login url
            var fb = new FacebookClient();
            return fb.GetLoginUrl(parameters);
        }
        public void Publish_Video_To_Wall()
        {
            var videoPath = TestHelpers.GetPathRelativeToExecutable("do-beer-not-drugs.3gp");
            byte[] video = File.ReadAllBytes(videoPath);

            var mediaObject = new FacebookMediaObject
                                  {
                                      FileName = "do-beer-not-drugs.3gp",
                                      ContentType = "video/3gpp"
                                  };
            mediaObject.SetValue(video);

            dynamic parameters = new ExpandoObject();
            parameters.source = mediaObject;
            parameters.method = "video.upload";
            parameters.access_token = ConfigurationManager.AppSettings["AccessToken"];

            var fb = new FacebookClient();
            dynamic result = fb.Post(parameters);

            Assert.NotNull(result);
            Assert.NotEqual(null, result.vid);
        }
Esempio n. 28
0
        private void GraphApiExample()
        {
            // note: avoid using synchronous methods if possible as it will block the thread until the result is received
            // use async methods instead. see: GraphApiAsyncExample()
            var fb = new FacebookClient(_accessToken);

            try
            {
                dynamic result = fb.Get("/me");
                var name = result.name;

                lnkName.Text = "Hi " + name;
                lnkName.LinkClicked += (o, e) => Process.Start(result.link);

                // 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
                picProfilePic.LoadAsync(string.Format("https://graph.facebook.com/{0}/picture?type={1}", result.id, "square"));
            }
            catch (FacebookApiException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void friendSelectorTextBlockHandler(object sender, System.Windows.Input.GestureEventArgs evtArgs)
        {
            FacebookClient 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();

                var data = (IEnumerable<object>)result["data"]; ;


                Dispatcher.BeginInvoke(() =>
                {
                    // The observable collection can only be updated from within the UI thread. See 
                    // http://10rem.net/blog/2012/01/10/threading-considerations-for-binding-and-change-notification-in-silverlight-5
                    // If you try to update the bound data structure from a different thread, you are going to get a cross
                    // thread exception.
                    foreach (var item in data)
                    {
                        var friend = (IDictionary<string, object>)item;

                        FacebookData.Friends.Add(new Friend { Name = (string)friend["name"], id = (string)friend["id"], PictureUri = new Uri(string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", (string)friend["id"], "square", App.AccessToken)) });
                    }

                    NavigationService.Navigate(new Uri("/Pages/FriendSelector.xaml", UriKind.Relative));
                });

            };

            fb.GetTaskAsync("/me/friends");
        }
Esempio n. 30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CustomAudiencesTOS"/> class.
 /// </summary>
 /// <param name="id">The identifier.</param>
 /// <param name="parentId">The parent identifier.</param>
 /// <param name="client">The client.</param>
 public CustomAudiencesTOS(string id, string parentId = null, FacebookClient client = null) : base(id, parentId, client)
 {
 }
Esempio n. 31
0
        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            if (FacebookWebContext.Current.IsAuthenticated() && FacebookWebContext.Current.IsAuthorized())
            {
                FacebookClient fbClient   = new FacebookClient(FacebookWebContext.Current.AccessToken);
                dynamic        me         = fbClient.Get("me");
                string         facebookId = (string)me.id;
                string         userEmail  = (string)me.email;

                if (facebookId == null || userEmail == null)
                {
                    throw new FacebookOAuthException();
                }

                var user = market.Users.SingleOrDefault(u => u.Email == userEmail);

                if (user == null)
                {
                    //User does not exist in our DB, let us make him
                    var location = me.location;
                    if (location == null)
                    {
                        location = me.hometown;
                        if (location == null)
                        {
                            var model = new RegisterModel();
                            ModelState.AddModelError("", "Oops, your Facebook profile does not have your location information. Please use the form below to request access.");
                            fbClient.Delete(facebookId + "/permissions");
                            FormsAuthentication.SignOut();
                            return(View(model));
                        }
                    }

                    string[] address = ((string)location.name).Split(',');
                    string   city    = address[0].Trim();
                    string   prov    = address[1].Trim();

                    //Let us create a new user
                    market.Users.Add(new UserModel
                    {
                        Email          = userEmail,
                        FirstName      = (string)me.first_name,
                        LastName       = (string)me.last_name,
                        City           = city,
                        RegionId       = market.Regions.SingleOrDefault(r => r.Name.Contains(prov)).Id,
                        CountryId      = 1,
                        isFacebookUser = true,
                        FacebookUserId = facebookId,
                        ActivationId   = Guid.NewGuid().ToString()
                    });

                    //Let us add a facebook user to our DB with isApproved set to false
                    market.FacebookUsers.Add(new FacebookUser
                    {
                        Id             = facebookId,
                        UserModelEmail = (string)me.email,
                        AccessToken    = FacebookWebContext.Current.AccessToken,
                        IsApproved     = false,
                        Expires        = FacebookWebContext.Current.Session.Expires
                    });

                    market.SaveChanges();
                    Session["REGISTERED_USER"] = true;
                    log.Info("Account - New user registered (" + userEmail.ToLower() + ")");
                    return(View());
                }
                else
                {
                    if (user.isFacebookUser == false)
                    {
                        market.FacebookUsers.Add(new FacebookUser
                        {
                            Id             = facebookId,
                            UserModelEmail = (string)me.email,
                            AccessToken    = FacebookWebContext.Current.AccessToken,
                            IsApproved     = Membership.GetUser(user.Email).IsApproved,
                            Expires        = FacebookWebContext.Current.Session.Expires
                        });

                        market.SaveChanges();

                        user.isFacebookUser      = true;
                        market.Entry(user).State = EntityState.Modified;
                        market.SaveChanges();

                        if (Membership.GetUser(user.Email).IsApproved == true)
                        {
                            FormsAuthentication.SetAuthCookie((string)me.email, false);
                            Session["USER_F_NAME"] = (string)me.first_name;
                            log.Info("Account - User logged in (" + (string)me.email + ")");
                            return(RedirectToAction("Index", "Home"));
                        }
                        else
                        {
                            UserMailer.Welcome(newUser: user).Send();
                            Session["REGISTERED_USER"] = true;
                            log.Info("Account - New user registered (" + user.Email.ToLower() + ")");
                            return(View());
                        }
                    }
                }
            }

            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            ViewBag.RegionId       = new SelectList(market.Regions, "Id", "Name");
            return(View());
        }
Esempio n. 32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ObjectStorySpec"/> class.
 /// </summary>
 /// <param name="id">The identifier.</param>
 /// <param name="parentId">The parent identifier.</param>
 /// <param name="client">The client.</param>
 public ObjectStorySpec(string id, string parentId = null, FacebookClient client = null) : base(id, parentId, client)
 {
 }
Esempio n. 33
0
        public async static Task <FacebookUser> GetUserAsync(this FacebookClient client)
        {
            var userResult = await client.GetCurrentUserAsync() as JsonObject;

            return(FacebookUserMappers.MapToUser(userResult));
        }
Esempio n. 34
0
        public async static Task <FacebookUser> GetFacebookUser(string accessToken)
        {
            var response = await FacebookClient.Get <FacebookUser>("me", accessToken);

            return(response);
        }
Esempio n. 35
0
 public Farmer(string name, string password)
 {
     Name    = name;
     _client = new FacebookClient(name, password);
 }
Esempio n. 36
0
 protected void Button1_Click(object sender, EventArgs e)
 {
     var     client    = new FacebookClient("AAAD1aVeVJoABAOtoDqFU9d4wZCCJ8ZCSFuOed0N6cYIcbfi32FYs6QURIRKDh92PvIIwGOSFbCcy6DgYrH2GZBwXGngu0LnwxD88wG9FwZDZD");
     dynamic result    = client.Post("me/feed", new { message = "My first wall post using Facebook C# SDK" });
     var     newPostId = result.id;
 }
Esempio n. 37
0
        public ActionResult FacebookCallback(string code)
        {
            var     fb     = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id     = ConfigurationManager.AppSettings["clientId"],
                client_secret = ConfigurationManager.AppSettings["clientSecret"],
                redirect_uri  = RedirectUri.AbsoluteUri,
                code          = code
            });

            var accessToken = result.access_token;

            // Store the access token in the session
            Session["AccessToken"] = accessToken;

            // update the facebook client with the access token so
            // we can make requests on behalf of the user
            fb.AccessToken = accessToken;


            // Get the user's information
            dynamic me         = fb.Get("/me");
            string  facebookId = me.id;
            string  email      = me.email;

            if (string.IsNullOrEmpty(email))
            {
                email = facebookId + "@facebook.com";
            }

            // select from DB
            User newUser = GraphDatabaseHelpers.Instance.GetUser(1, email); // Facebook account: TypeId = 1

            /*
             *  Insert into Graph DB
             */

            if (newUser == null)
            {
                var nameArray       = ((string)me.name).Split(' ').ToList();
                var firstNameBackup = nameArray.First();

                if (nameArray.Count > 1)
                {
                    nameArray.RemoveAt(0);
                }

                var lastNameBackup = string.Join(" ", nameArray);

                newUser = new User
                {
                    TypeId      = 1,
                    Email       = email,
                    Address     = me.adress,
                    DateJoined  = DateTime.Now.ToString(FapConstants.DatetimeFormat),
                    DateOfBirth = me.date_of_birth,
                    FirstName   = me.first_name ?? firstNameBackup,
                    LastName    = me.last_name ?? lastNameBackup,
                    Gender      = me.gender ?? "other",
                    PhoneNumber = me.phone_number,
                    Status      = FapConstants.UserActive,
                    Avatar      = "https://graph.facebook.com/" + facebookId + "/picture?type=large",
                    Password    = "",
                    CoverUrl    = ""
                };
                // Facebook account

                // insert user to Database
                GraphDatabaseHelpers.Instance.InsertUser(ref newUser);
            }
            else if (!FapConstants.UserActive.Equals(newUser.Status))
            {
                // user is Locked
                Session["loginMessageError"] = "Your account has been locked! Please contact us follow email: [email protected]";
                return(RedirectToAction("Index", "Home"));
            }

            // Set the auth cookie
            Session["authenicated"]      = true;
            Session["username"]          = newUser.FirstName + " " + newUser.LastName;
            Session["userAva"]           = newUser.Avatar;
            Session["UserId"]            = newUser.UserId;
            Session["loginMessageError"] = "";
            UserHelpers.SetCurrentUser(Session, newUser);

            //FormsAuthentication.SetAuthCookie(email, false);
            //SessionHelper.RenewCurrentUser();

            return(RedirectToAction("Index", "Home"));
        }
Esempio n. 38
0
        private void AuthThroughBuddy(string fbUserId, string fbUserToken)
        {
            //Check to ensure everything's setup right
            GcmClient.CheckDevice(this);
            GcmClient.CheckManifest(this);
            GcmClient.Register(this, GcmBroadcastReceiver.SENDER_IDS);
            var registrationId = GcmClient.GetRegistrationId(this);

            FacebookClient fb = new FacebookClient(fbUserToken);

            fb.AppId     = AppId;
            fb.AppSecret = AppSecret;

            BuddyClient              client              = new BuddyClient(BuddyAppName, BuddyAppKey);
            const string             BuddyAccountKey     = "BuddyAccount";
            const string             BuddyAccessTokenKey = "AccessToken";
            const string             FacebookIDTokenKey  = "FacebookIdTokenKey";
            var                      accountStore        = AccountStore.Create(this);
            var                      savedAccount        = accountStore.FindAccountsForService(BuddyAccountKey).LastOrDefault();
            Task <AuthenticatedUser> getUserTask;
            bool                     saveAccount = false;

            if (savedAccount != null && savedAccount.Properties.ContainsKey(BuddyAccessTokenKey))
            {
                saveAccount = false;
                var token = savedAccount.Properties [BuddyAccessTokenKey];
                getUserTask = client.LoginAsync(token);
            }
            else
            {
                saveAccount = true;
                getUserTask = client.SocialLoginAsync("Facebook", fbUserId, fbUserToken).ContinueWith((u) => {
                    if (u.IsFaulted)
                    {
                        // try again for kicks
                    }

                    return((AuthenticatedUser)u.Result);
                });
            }

            getUserTask.ContinueWith(r => {
                Console.WriteLine("Get User Task has happened result is faulted = " + r.IsFaulted.ToString());

                if (!r.IsFaulted)
                {
                    AuthenticatedUser user = r.Result;
                    var successActivity    = new Action(() => {
                        var repository = new POPpicLibrary.GameRepository(user, client, fb);
                        Console.WriteLine("Success task is running!");

                        if (saveAccount)
                        {
                            var properties = new Dictionary <string, string>();
                            properties[BuddyAccessTokenKey] = user.Token;
                            properties[FacebookIDTokenKey]  = fbUserId;
                            Account buddyAccount            = new Account(user.ID.ToString(), properties);
                            accountStore.Save(buddyAccount, BuddyAccountKey);
                        }

                        // Finish();

                        if (progressDialog != null)
                        {
                            progressDialog.Dismiss();
                        }

                        ((POPpicApplication)Application).SetGameRepository(repository);
                    });

                    if (string.IsNullOrEmpty(user.ApplicationTag))
                    {
                        user.PhotoAlbums.CreateAsync(user.ID.ToString(), true, null).ContinueWith(pa => {
                            if (!pa.IsFaulted)
                            {
                                var album = pa.Result;
                                user.VirtualAlbums.CreateAsync(user.ID.ToString(), null).ContinueWith(va => {
                                    if (!va.IsFaulted)
                                    {
                                        var virtualAlbum               = va.Result;
                                        var extraData                  = new UserExtraData();
                                        extraData.UploadAlbumId        = album.AlbumId;
                                        extraData.WinnerAblumVirtualId = virtualAlbum.ID;
                                        user.UpdateAsync(null, null, UserGender.Any, 0, null, UserStatus.Any, false, false, JsonConvert.SerializeObject(extraData)).ContinueWith(updateResult => {
                                            if (!updateResult.IsFaulted && updateResult.Result)
                                            {
                                                RunOnUiThread(successActivity);
                                            }
                                        });
                                    }
                                });
                            }
                        });
                    }
                    else
                    {
                        RunOnUiThread(successActivity);
                    }
                }
                else
                {
                    if (progressDialog != null)
                    {
                        progressDialog.Dismiss();
                    }
                    RunOnUiThread(() => {
                        AndroidUtilities.ShowAlert(this, "Error Getting User Account", r.Exception.Message, "Try Again", (object sender, DialogClickEventArgs e) => {
                            AuthThroughBuddy();
                        });
                    });

                    Console.WriteLine(r.Exception.Message);
                }
            });
        }
Esempio n. 39
0
        /// <summary>
        /// Authenticates the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="username">The username.</param>
        /// <param name="returnUrl">The return URL.</param>
        /// <returns></returns>
        public override Boolean Authenticate(HttpRequest request, out string username, out string returnUrl)
        {
            var fbClient = new FacebookClient();
            FacebookOAuthResult oAuthResult;

            if (fbClient.TryParseOAuthCallbackUrl(request.Url, out oAuthResult) && oAuthResult.IsSuccess)
            {
                try
                {
                    var redirectUri = new Uri(GetRedirectUrl(request));

                    dynamic parameters = new ExpandoObject();
                    parameters.client_id     = AttributeValue("AppID");
                    parameters.client_secret = AttributeValue("AppSecret");
                    parameters.redirect_uri  = redirectUri.AbsoluteUri;
                    parameters.code          = oAuthResult.Code;

                    dynamic result = fbClient.Post("oauth/access_token", parameters);

                    string accessToken = result.access_token;

                    fbClient = new FacebookClient(accessToken);
                    dynamic me         = fbClient.Get("me");
                    string  facebookId = "FACEBOOK_" + me.id.ToString();

                    // query for matching id in the user table
                    UserService userService = new UserService();
                    var         user        = userService.GetByUserName(facebookId);

                    // if not user was found see if we can find a match in the person table
                    if (user == null)
                    {
                        try
                        {
                            // determine if we can find a match and if so add an user login record

                            // get properties from Facebook dynamic object
                            string lastName  = me.last_name.ToString();
                            string firstName = me.first_name.ToString();
                            string email     = me.email.ToString();

                            var personService = new PersonService();
                            var person        = personService.Queryable().FirstOrDefault(u => u.LastName == lastName && (u.GivenName == firstName || u.NickName == firstName) && u.Email == email);

                            if (person != null)
                            {
                                // since we have the data enter the birthday from Facebook to the db if we don't have it yet
                                DateTime birthdate = Convert.ToDateTime(me.birthday.ToString());

                                if (person.BirthDay == null)
                                {
                                    person.BirthDate = birthdate;
                                    personService.Save(person, person.Id);
                                }
                            }
                            else
                            {
                                var dvService = new DefinedValueService();

                                person                     = new Person();
                                person.IsSystem            = false;
                                person.RecordTypeValueId   = dvService.GetIdByGuid(SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON);
                                person.RecordStatusValueId = dvService.GetIdByGuid(SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE);

                                person.GivenName = me.first_name.ToString();
                                person.LastName  = me.last_name.ToString();
                                person.Email     = me.email.ToString();

                                if (me.gender.ToString() == "male")
                                {
                                    person.Gender = Gender.Male;
                                }
                                else if (me.gender.ToString() == "female")
                                {
                                    person.Gender = Gender.Female;
                                }
                                else
                                {
                                    person.Gender = Gender.Unknown;
                                }

                                person.BirthDate  = Convert.ToDateTime(me.birthday.ToString());
                                person.DoNotEmail = false;

                                personService.Add(person, null);
                                personService.Save(person, null);
                            }

                            user = userService.Create(person, AuthenticationServiceType.External, this.GetType().FullName, facebookId, "fb", true, person.Id);
                        }
                        catch (Exception ex)
                        {
                            string msg = ex.Message;
                            // TODO: probably should report something...
                        }

                        // TODO: Show label indicating inability to find user corresponding to facebook id
                    }

                    username  = user.UserName;
                    returnUrl = oAuthResult.State;
                    return(true);
                }
                catch (FacebookOAuthException oae)
                {
                    string msg = oae.Message;
                    // TODO: Add error handeling
                    // Error validating verification code. (usually from wrong return url very picky with formatting)
                    // Error validating client secret.
                    // Error validating application.
                }
            }

            username  = null;
            returnUrl = null;
            return(false);
        }
Esempio n. 40
0
        public ActionResult Handshake(string code)
        {
            //after authentication, Facebook will redirect to this controller action with a QueryString parameter called "code" (this is Facebook's Session key)

            //example uri: http://www.examplewebsite.com/facebook/handshake/?code=2.DQUGad7_kFVGqKTeGUqQTQ__.3600.1273809600-1756053625|dil1rmAUjgbViM_GQutw-PEgPIg.

            //this is your Facebook App ID
            string clientId = "144618862327767";

            //this is your Secret Key
            string clientSecret = "48af78235494ff833ed27d91d89a903d";

            //we have to request an access token from the following Uri
            string url = "https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}";

            //your redirect uri must be EXACTLY the same Uri that caused the initial authentication handshake
            string redirectUri = "http://localhost:1188/auth/handshake/";

            //Create a webrequest to perform the request against the Uri
            WebRequest request = WebRequest.Create(string.Format(url, clientId, redirectUri, clientSecret, code));

            //read out the response as a utf-8 encoding and parse out the access_token
            WebResponse  response     = request.GetResponse();
            Stream       stream       = response.GetResponseStream();
            Encoding     encode       = System.Text.Encoding.GetEncoding("utf-8");
            StreamReader streamReader = new StreamReader(stream, encode);
            string       accessToken  = streamReader.ReadToEnd().Replace("access_token=", "");

            streamReader.Close();
            response.Close();

            //set the access token to some session variable so it can be used through out the session
            Session["FacebookAccessToken"] = accessToken;

            var     client = new FacebookClient(accessToken);
            dynamic me     = client.Get("me");

            string email = me.email;

            var result = from u in db.Users
                         where u.Email == email
                         select u;

            if (result.Count() == 0)
            {
                User user = new User();

                //user.Name = me.name;
                user.Email = me.email;
                //user.Pass = FormsAuthentication.HashPasswordForStoringInConfigFile("test", "SHA1");
                user.RegistrationDate = DateTime.Now;
                user.PaymentId        = Guid.NewGuid().ToString("N");

                if (ModelState.IsValid)
                {
                    db.Users.Add(user);
                    db.SaveChanges();
                }
            }

            FormsAuthentication.SetAuthCookie(email, false);

            return(RedirectToAction("Index", "Home"));

            //return Content(email);
        }
Esempio n. 41
0
 /// <summary>
 /// Initializes a new instance of the <see cref="VideoThumbnail"/> class.
 /// </summary>
 /// <param name="id">The identifier.</param>
 /// <param name="parentId">The parent identifier.</param>
 /// <param name="client">The client.</param>
 public VideoThumbnail(string id, string parentId = null, FacebookClient client = null) : base(id, parentId, client)
 {
 }
Esempio n. 42
0
        private void btnPostVideo_Click(object sender, EventArgs args)
        {
            var ofd = new OpenFileDialog
            {
                Filter = "MP4 Files|*.mp4",
                Title  = "Select video to upload"
            };

            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            var fb = new FacebookClient(_accessToken);

            // make sure to add event handler for PostCompleted.
            fb.PostCompleted += (o, e) =>
            {
                // incase you support cancellation, make sure to check
                // e.Cancelled property first even before checking (e.Error!=null).
                if (e.Cancelled)
                {
                    // for this example, we can ignore as we don't allow this
                    // example to be cancelled.

                    // you can check e.Error for reasons behind the cancellation.
                    var cancellationError = e.Error;
                }
                else if (e.Error != null)
                {
                    // error occurred
                    this.BeginInvoke(new MethodInvoker(
                                         () =>
                    {
                        MessageBox.Show(e.Error.Message);
                    }));
                }
                else
                {
                    // the request was completed successfully

                    // make sure to be on the right thread when working with ui.
                    this.BeginInvoke(new MethodInvoker(
                                         () =>
                    {
                        MessageBox.Show("Video uploaded successfully");
                    }));
                }
            };

            dynamic parameters = new ExpandoObject();

            parameters.message = txtMessage.Text;
            parameters.source  = new FacebookMediaObject
            {
                ContentType = "video/mp4",
                FileName    = Path.GetFileName(ofd.FileName)
            }.SetValue(File.ReadAllBytes(ofd.FileName));

            fb.PostAsync("me/videos", parameters);
        }
Esempio n. 43
0
        private void BatchRequestAsyncExample()
        {
            var fb = new FacebookClient(_accessToken);

            // since batch request is actually a POST request internally,
            // make sure to add the event handler for PostCompleted.
            fb.PostCompleted += (o, e) =>
            {
                // incase you support cancellation, make sure to check
                // e.Cancelled property first even before checking (e.Error!=null).
                if (e.Cancelled)
                {
                    // for this example, we can ignore as we don't allow this
                    // example to be cancelled.

                    // you can check e.Error for reasons behind the cancellation.
                    var cancellationError = e.Error;
                }
                else if (e.Error != null)
                {
                    // error occurred
                    this.BeginInvoke(new MethodInvoker(
                                         () =>
                    {
                        MessageBox.Show(e.Error.Message);
                    }));
                }
                else
                {
                    // the request was completed successfully

                    // now we can either cast it to IDictionary<string, object> or IList<object>
                    // depending on the type. or we could use dynamic.
                    dynamic result = e.GetResultData();

                    // note: batch requests doesn't support generic versions of e.GetResultData<T>()

                    // make sure to be on the right thread when working with ui.
                    this.BeginInvoke(new MethodInvoker(
                                         () =>
                    {
                        // always remember to check individual errors for the batch requests.
                        if (result[0] is Exception)
                        {
                            MessageBox.Show(((Exception)result[0]).Message);
                        }
                        dynamic first = result[0];
                        string name   = first.name;

                        // note: incase the omit_response_on_success = true, result[x] == null

                        // for this example just comment it out
                        //if (result[1] is Exception)
                        //    MessageBox.Show(((Exception)result[1]).Message);
                        //if (result[2] is Exception)
                        //    MessageBox.Show(((Exception)result[1]).Message);
                        //if (result[3] is Exception)
                        //    MessageBox.Show(((Exception)result[1]).Message);
                        //if (result[4] is Exception)
                        //    MessageBox.Show(((Exception)result[1]).Message);
                        //if (result[5] is Exception)
                        //    MessageBox.Show(((Exception)result[1]).Message);
                        //if (result[6] is Exception)
                        //    MessageBox.Show(((Exception)result[1]).Message);
                        //if (result[7] is Exception)
                        //    MessageBox.Show(((Exception)result[1]).Message);
                    }));
                }
            };

            fb.BatchAsync(new[] {
                new FacebookBatchParameter {
                    HttpMethod = HttpMethod.Get, Path = "/4"
                },
                new FacebookBatchParameter(HttpMethod.Get, "/me/friend", new Dictionary <string, object> {
                    { "limit", 10 }
                }),                                                                                                           // this should throw error
                new FacebookBatchParameter("/me/friends", new { limit = 1 })
                {
                    Data = new { name = "one-friend", omit_response_on_success = false }
                },                                                                                                                                     // use Data to add additional parameters that doesn't exist
                new FacebookBatchParameter {
                    Parameters = new { ids = "{result=one-friend:$.data.0.id}" }
                },
                new FacebookBatchParameter("{result=one-friend:$.data.0.id}/feed", new { limit = 5 }),
                new FacebookBatchParameter().Query("SELECT name FROM user WHERE uid="),                                                       // fql
                new FacebookBatchParameter().Query("SELECT first_name FROM user WHERE uid=me()", "SELECT last_name FROM user WHERE uid=me()") // fql multi-query
                //,new FacebookBatchParameter(HttpMethod.Post, "/me/feed", new { message = "test status update" })
            });
        }
Esempio n. 44
0
        public ActionResult FacebookCallback(string code)
        {
            var     fb     = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id     = ConfigurationManager.AppSettings["FbAppId"],
                client_secret = ConfigurationManager.AppSettings["FbAppSecret"],
                redirect_uri  = RediredtUri.AbsoluteUri,
                code          = code
            });
            var accessToken = result.access_token;

            Session["AccessToken"] = accessToken;
            fb.AccessToken         = accessToken;
            dynamic me         = fb.Get("me?fields=link,first_name,currency,last_name,email,gender,locale,timezone,verified,picture,age_range");
            string  email      = me.email;
            string  first_name = me.first_name;
            string  last_name  = me.last_name;
            string  picture    = me.picture.data.url;
            string  fb_id      = me.id;

            FormsAuthentication.SetAuthCookie(email, false);
            ClientLoginModel model = new ClientLoginModel();

            model.Email     = email;
            model.FirstName = first_name;
            model.LastName  = last_name;
            model.Picture   = picture;
            model.Fb_ID     = fb_id;

            bool IsCheck = _factory.CheckExistLoginSosial(model.Fb_ID);

            if (IsCheck)
            {
                var resultLogin = _factory.Login(model);
                if (resultLogin != null)
                {
                    UserSession userSession = new UserSession();
                    userSession.Email         = resultLogin.Email;
                    userSession.UserName      = resultLogin.DisplayName;
                    userSession.IsAdminClient = resultLogin.IsAdmin;
                    userSession.FirstName     = resultLogin.FirstName;
                    userSession.LastName      = resultLogin.LastName;
                    userSession.Phone         = resultLogin.Phone;
                    userSession.Address       = resultLogin.Address;
                    userSession.UserId        = resultLogin.Id;
                    userSession.PostCode      = resultLogin.PostCode;
                    userSession.Country       = resultLogin.Country;
                    userSession.City          = resultLogin.City;
                    Session.Add("UserClient", userSession);
                    string     myObjectJson = JsonConvert.SerializeObject(userSession); //new JavaScriptSerializer().Serialize(userSession);
                    HttpCookie cookie       = new HttpCookie("UserClientCookie");
                    cookie.Expires = DateTime.Now.AddMonths(1);
                    cookie.Value   = Server.UrlEncode(myObjectJson);
                    HttpContext.Response.Cookies.Add(cookie);
                }
                else
                {
                    ModelState.AddModelError("Email", "Thông tin tài khoản không chính xác");
                    return(RedirectToAction("Index", "Home"));
                }
            }
            else
            {
                CustomerModels modelFB = new CustomerModels();
                modelFB.FbID      = fb_id;
                modelFB.FirstName = first_name;
                modelFB.LastName  = last_name;
                modelFB.Email     = email;
                modelFB.ImageURL  = picture;
                string msg          = "";
                string cusId        = "";
                var    resultSignUp = _factory.CreateOrUpdate(modelFB, ref cusId, ref msg);
                if (resultSignUp)
                {
                    var         data        = _factory.GetDetail(cusId);
                    UserSession userSession = new UserSession();
                    userSession.Email     = data.Email;
                    userSession.UserName  = data.FirstName + " " + data.LastName;
                    userSession.FirstName = data.FirstName;
                    userSession.LastName  = data.LastName;
                    userSession.Phone     = data.Phone;
                    userSession.Address   = data.Address;
                    userSession.UserId    = data.ID;
                    userSession.PostCode  = data.Postcode;
                    userSession.Country   = data.Country;
                    userSession.City      = data.City;
                    Session.Add("UserClient", userSession);
                    string     myObjectJson = JsonConvert.SerializeObject(userSession); //new JavaScriptSerializer().Serialize(userSession);
                    HttpCookie cookie       = new HttpCookie("UserClientCookie");
                    cookie.Expires = DateTime.Now.AddMonths(1);
                    cookie.Value   = Server.UrlEncode(myObjectJson);
                    HttpContext.Response.Cookies.Add(cookie);
                }
                else
                {
                    ModelState.AddModelError("Email", "");
                    return(RedirectToAction("Index", "Home"));
                }
            }
            return(RedirectToAction("Index", "Home"));
        }
Esempio n. 45
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AdAccountDeliveryEstimate"/> class.
 /// </summary>
 /// <param name="id">The identifier.</param>
 /// <param name="parentId">The parent identifier.</param>
 /// <param name="client">The client.</param>
 public AdAccountDeliveryEstimate(string id, string parentId = null, FacebookClient client = null) : base(id, parentId, client)
 {
 }
Esempio n. 46
0
    protected void Shared(string access_token)
    {
        string app_id     = "508197835942931";
        string app_secret = "969c88330438e916bae258c761921d44";
        string scope      = "publish_stream,manage_pages";

        //    if (Request["code"] == null)
        //    {
        //       Response.Redirect(string.Format(
        //           "https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
        //            app_id, Request.Url.AbsoluteUri, scope));
        //    }
        //    else
        //    {
        //Dictionary<string, string> tokens = new Dictionary<string, string>();

        //string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
        //    app_id, Request.Url.AbsoluteUri, scope, code, app_secret);

        //HttpWebRequest request = System.Net.WebRequest.Create(url) as HttpWebRequest;

        //using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        //{
        //    StreamReader reader = new StreamReader(response.GetResponseStream());

        //    string vals = reader.ReadToEnd();

        //    foreach (string token in vals.Split('&'))
        //    {
        //        //meh.aspx?token1=steve&token2=jake&...
        //        tokens.Add(token.Substring(0, token.IndexOf("=")),
        //            token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
        //    }
        //}

        //string access_token = tokens["access_token"];

        var    client    = new FacebookClient(access_token);
        string ImagePath = Server.MapPath("Images/books/Matla-e-Asaar2.jpg");

        FacebookClient fb    = new FacebookClient(access_token);
        string         appid = fb.AppId;     // ConfigurationManager.AppSettings["APPID"].ToString();
        string         scret = fb.AppSecret; //ConfigurationManager.AppSettings["APPSECRET"].ToString();

        var     imgstream = File.OpenRead(ImagePath);
        dynamic res       = fb.Post("669471026419805/photos", new
        {
            message = "November 2013 Edition",
            file    = new FacebookMediaStream
            {
                ContentType = "image/jpg",
                FileName    = Path.GetFileName(ImagePath)
            }.SetValue(imgstream)
        });
        //client.Post(res);

        // var myAccounts = client.Get("/me/accounts?type=page");
        // var pageAccessToken = myAccounts.Single(x => x.pageName == MY_PAGE_NAME).access_token;

        //var pageClient = new FacebookClient(pageAccessToken);
        //dynamic parameters = new ExpandoObject();
        //parameters.message = "November 2013 Edition";
        //books bookcontent = new books();
        // ProductThumb thumb = bookcontent.Getimage(new Guid("BC90654F-B2EE-4421-8886-C9FD854403B8"));
        //if (thumb != null)
        //{

        //}
        //else
        //{
        //}


        // parameters.link = "http://alamaat.biz/Item.aspx";
        // parameters.picture = "http://alamaat.biz/Images/books/foi2.jpg";
        // parameters.name = "Fehm-O-Idrak";
        //  parameters.caption = "Fehm-O-Idrak";
        // parameters.access_token = access_token;
        //446533181408238 is my fan page
        //client.Post("/669471026419805/feed", parameters);
        //client.Post("/669471026419805/feed", new { message = "Welcome " });

        // }
    }
 /// <summary>
 /// Initializes a new instance of the <see cref="CustomConversion"/> class.
 /// </summary>
 /// <param name="id">The identifier.</param>
 /// <param name="parentId">The parent identifier.</param>
 /// <param name="client">The client.</param>
 public CustomConversion(string id, string parentId = null, FacebookClient client = null) : base(id, parentId, client)
 {
 }
Esempio n. 48
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ProductFeedUploadError"/> class.
 /// </summary>
 /// <param name="id">The identifier.</param>
 /// <param name="parentId">The parent identifier.</param>
 /// <param name="client">The client.</param>
 public ProductFeedUploadError(string id, string parentId = null, FacebookClient client = null) : base(id, parentId, client)
 {
 }
Esempio n. 49
0
 /// <summary>
 /// Initializes a new instance of the <see cref="App"/> class.
 /// </summary>
 /// <param name="id">The identifier.</param>
 /// <param name="parentId">The parent identifier.</param>
 /// <param name="client">The client.</param>
 public App(string id, string parentId = null, FacebookClient client = null) : base(id, parentId, client) { }
Esempio n. 50
0
        public bool AddFacebookFriendsGender(string ProfileId, string FacebookUserId)
        {
            Api.Socioboard.Services.FacebookAccount  _FacebookAccount = new FacebookAccount();
            Domain.Socioboard.Domain.FacebookAccount _facebookAccount = new Domain.Socioboard.Domain.FacebookAccount();

            _facebookAccount = (Domain.Socioboard.Domain.FacebookAccount)(new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(_FacebookAccount.getFacebookAccountDetailsById(ProfileId, FacebookUserId), typeof(Domain.Socioboard.Domain.FacebookAccount)));

            if (string.IsNullOrEmpty(_facebookAccount.AccessToken))
            {
                _facebookAccount = new Domain.Socioboard.Domain.FacebookAccount();
                Api.Socioboard.Services.FacebookAccountRepository _FacebookAccountRepository = new FacebookAccountRepository();

                System.Collections.ArrayList lstFacebookAccounts = _FacebookAccountRepository.getAllFacebookAccounts();

                Random _random = new Random();
                var    rnum    = _random.Next(0, lstFacebookAccounts.Count - 1);
                _facebookAccount = (Domain.Socioboard.Domain.FacebookAccount)lstFacebookAccounts[rnum];
            }
            int malecount   = 0;
            int femalecount = 0;

            Domain.Socioboard.Domain.FacebookStats objfbStats = new Domain.Socioboard.Domain.FacebookStats();
            FacebookStatsRepository objFBStatsRepo            = new FacebookStatsRepository();

            FacebookClient fb = new FacebookClient();

            fb.AccessToken = _facebookAccount.AccessToken;
            try
            {
                dynamic data = fb.Get("v2.0/me/friends?fields=gender");

                //dynamic data, dynamic profile, Guid userId


                foreach (var item in data["data"])
                {
                    try
                    {
                        if (item["gender"] == "male")
                        {
                            malecount++;
                        }
                        else if (item["gender"] == "female")
                        {
                            femalecount++;
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex.Message);
                        logger.Error(ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                logger.Error(ex.StackTrace);
                return(false);
            }
            objfbStats.EntryDate   = DateTime.Now;
            objfbStats.FbUserId    = _facebookAccount.FbUserId;//profile["id"].ToString();
            objfbStats.FemaleCount = femalecount;
            objfbStats.Id          = Guid.NewGuid();
            objfbStats.MaleCount   = malecount;
            objfbStats.UserId      = _facebookAccount.UserId;
            objfbStats.FanCount    = getfanCount(objfbStats, _facebookAccount.AccessToken);

            if (objFBStatsRepo.checkFacebookStatsExists(objfbStats.FbUserId.ToString(), objfbStats.UserId, objfbStats.FanCount, objfbStats.MaleCount, objfbStats.FemaleCount))
            {
                objFBStatsRepo.addFacebookStats(objfbStats);
            }


            return(true);
        }
Esempio n. 51
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AdAccountAdRulesHistory"/> class.
 /// </summary>
 /// <param name="id">The identifier.</param>
 /// <param name="parentId">The parent identifier.</param>
 /// <param name="client">The client.</param>
 public AdAccountAdRulesHistory(string id, string parentId = null, FacebookClient client = null) : base(id, parentId, client)
 {
 }
Esempio n. 52
0
        public static FacebookUser GetUser(this FacebookClient client)
        {
            var userResult = client.GetCurrentUserAsync().Result as JsonObject;

            return(FacebookUserMappers.MapToUser(userResult));
        }
Esempio n. 53
0
 protected ApiBaseClass(FacebookClient client)
 {
     FacebookClient = client;
     RestClient     = client.RestClient;
 }
Esempio n. 54
0
        public ActionResult RegisterFBPrivateBeta()
        {
            if (FacebookWebContext.Current.IsAuthenticated() && FacebookWebContext.Current.IsAuthorized())
            {
                FacebookClient fbClient   = new FacebookClient(FacebookWebContext.Current.AccessToken);
                dynamic        me         = fbClient.Get("me");
                string         facebookId = (string)me.id;
                string         userEmail  = (string)me.email;

                if (facebookId == null || userEmail == null)
                {
                    throw new FacebookOAuthException();
                }

                var user = market.Users.SingleOrDefault(u => u.Email == userEmail);

                if (user == null)
                {
                    var location = me.location;
                    if (location == null)
                    {
                        location = me.hometown;
                        if (location == null)
                        {
                            var model = new RegisterPrBetaViewModel();
                            ModelState.AddModelError("", "Oops, your Facebook profile does not have your location information. Please use the form below to request access.");
                            fbClient.Delete(facebookId + "/permissions");
                            FormsAuthentication.SignOut();
                            return(View("../Home/Index", model));
                        }
                    }

                    string[] address = ((string)location.name).Split(',');
                    string   city    = address[0].Trim();
                    string   prov    = address[1].Trim();

                    //Let us create a new user
                    market.Users.Add(new UserModel
                    {
                        Email          = userEmail,
                        FirstName      = "Rambla",
                        LastName       = "User",
                        City           = city,
                        RegionId       = market.Regions.SingleOrDefault(r => r.Name.Contains(prov)).Id,
                        CountryId      = 1,
                        isFacebookUser = true,
                        FacebookUserId = facebookId,
                        ActivationId   = Guid.NewGuid().ToString()
                    });

                    //Let us add a facebook user to our DB with isApproved set to false
                    market.FacebookUsers.Add(new FacebookUser
                    {
                        Id             = facebookId,
                        UserModelEmail = (string)me.email,
                        AccessToken    = FacebookWebContext.Current.AccessToken,
                        IsApproved     = false,
                        Expires        = FacebookWebContext.Current.Session.Expires
                    });

                    market.SaveChanges();
                    Session["REQUESTED_ACCESS_USER"] = true;
                    log.Info("Account - New user registered (" + userEmail.ToLower() + ")");
                    return(View("Register"));
                }

                Session["REQUESTED_ACCESS_USER"] = true;
                return(View("Register"));
            }

            var regModel = new RegisterPrBetaViewModel();

            ModelState.AddModelError("", "Oops, your Facebook profile does not have your location information. Please use the form below to request access.");
            return(View("../Home/Index", regModel));
        }
Esempio n. 55
0
        private void GraphApiAsyncDynamicExample()
        {
            var fb = new FacebookClient(_accessToken);

            // make sure to add the appropriate event handler
            // before calling the async methods.
            // GetCompleted     => GetAsync
            // PostCompleted    => PostAsync
            // DeleteCompleted  => DeleteAsync
            fb.GetCompleted += (o, e) =>
            {
                // incase you support cancellation, make sure to check
                // e.Cancelled property first even before checking (e.Error!=null).
                if (e.Cancelled)
                {
                    // for this example, we can ignore as we don't allow this
                    // example to be cancelled.

                    // you can check e.Error for reasons behind the cancellation.
                    var cancellationError = e.Error;
                }
                else if (e.Error != null)
                {
                    // error occurred
                    this.BeginInvoke(new MethodInvoker(
                                         () =>
                    {
                        MessageBox.Show(e.Error.Message);
                    }));
                }
                else
                {
                    // the request was completed successfully

                    // now we can either cast it to IDictionary<string, object> or IList<object>
                    // depending on the type. or we could use dynamic.
                    dynamic result = e.GetResultData();

                    // you can use either the .
                    var firstName = result.first_name;

                    // or you can use indexer.
                    var lastName = result["last_name"];

                    // since this is an async callback, make sure to be on the right thread
                    // when working with the UI.
                    this.BeginInvoke(new MethodInvoker(
                                         () =>
                    {
                        lblLastName.Text = "Last Name: " + lastName;
                    }));
                }
            };

            // additional parameters can be passed and
            // must be assignable from IDictionary<string, object>
            // You can use ExpandoObject if you want to use dynamic
            dynamic parameters = new ExpandoObject();

            parameters.fields = "first_name,last_name";

            fb.GetAsync("me", parameters);
        }
Esempio n. 56
0
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            IEnumerable <object> authorizeAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(FacebookAuthorizeAttribute), inherit: true)
                                                       .Union(filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(FacebookAuthorizeAttribute), inherit: true));

            if (!authorizeAttributes.Any())
            {
                return;
            }

            FacebookClient  client        = _config.ClientProvider.CreateClient();
            HttpRequestBase request       = filterContext.HttpContext.Request;
            dynamic         signedRequest = FacebookRequestHelpers.GetSignedRequest(
                filterContext.HttpContext,
                rawSignedRequest =>
            {
                return(client.ParseSignedRequest(rawSignedRequest));
            });
            string userId      = null;
            string accessToken = null;

            if (signedRequest != null)
            {
                userId      = signedRequest.user_id;
                accessToken = signedRequest.oauth_token;
            }

            string appUrl      = _config.AppUrl;
            string redirectUrl = appUrl + request.Url.PathAndQuery;

            if (signedRequest == null || String.IsNullOrEmpty(userId) || String.IsNullOrEmpty(accessToken))
            {
                // Cannot obtain user information from signed_request, redirect to Facebook login.
                Uri loginUrl = client.GetLoginUrl(redirectUrl, _config.AppId, null);
                filterContext.Result = CreateRedirectResult(loginUrl);
            }
            else
            {
                HashSet <string> requiredPermissions = GetRequiredPermissions(authorizeAttributes);
                if (requiredPermissions.Count > 0)
                {
                    IEnumerable <string> currentPermissions = _config.PermissionService.GetUserPermissions(userId, accessToken);

                    // If the current permissions doesn't cover all required permissions,
                    // redirect to Facebook login or to the specified redirect path.
                    if (currentPermissions == null || !requiredPermissions.IsSubsetOf(currentPermissions))
                    {
                        string requiredPermissionString = String.Join(",", requiredPermissions);
                        Uri    authorizationUrl;
                        if (String.IsNullOrEmpty(_config.AuthorizationRedirectPath))
                        {
                            authorizationUrl = client.GetLoginUrl(redirectUrl, _config.AppId, requiredPermissionString);
                        }
                        else
                        {
                            UriBuilder authorizationUrlBuilder = new UriBuilder(appUrl);
                            authorizationUrlBuilder.Path += "/" + _config.AuthorizationRedirectPath.TrimStart('/');
                            authorizationUrlBuilder.Query = String.Format(CultureInfo.InvariantCulture,
                                                                          "originUrl={0}&permissions={1}",
                                                                          HttpUtility.UrlEncode(redirectUrl),
                                                                          HttpUtility.UrlEncode(requiredPermissionString));
                            authorizationUrl = authorizationUrlBuilder.Uri;
                        }
                        filterContext.Result = CreateRedirectResult(authorizationUrl);
                    }
                }
            }
        }
Esempio n. 57
0
        public ActionResult FacebookCallback(string code)
        {
            var     fb     = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id     = "2399813093365009",
                client_secret = "3cdc9343fb6b5baba1f9aa45b1716ef3",
                redirect_uri  = RedirectUri.AbsoluteUri,
                code          = code
            });

            var accessToken = result.access_token;

            // Store the access token in the session for farther use
            Session["AccessToken"] = accessToken;

            // update the facebook client with the access token so
            // we can make requests on behalf of the user
            fb.AccessToken = accessToken;

            // Get the user's information
            dynamic me       = fb.Get("me?fields=id,name,email,birthday,gender");
            string  email    = me.email;
            string  name     = me.name;
            string  birthday = me.birthday;
            string  gender   = me.gender;



            Khachhang khachHang = db.Khachhangs.SingleOrDefault(item => item.Email == email);

            if (khachHang == null)
            {
                // set khach hang login fb
                khachHang          = new Khachhang();
                khachHang.Email    = email;
                khachHang.Hotenkh  = name;
                khachHang.Quyen    = 2;
                khachHang.Ngaysinh = Convert.ToDateTime(birthday);
                if (gender == "male")
                {
                    khachHang.Gioitinh = true;
                }
                else
                {
                    khachHang.Gioitinh = false;
                }


                db.Khachhangs.Add(khachHang);
                db.SaveChanges();

                Session.Add("USER_SESSION", khachHang);
            }
            else
            {
                Session.Add("USER_SESSION", khachHang);
            }

            // Set the auth cookie
            FormsAuthentication.SetAuthCookie(email, false);
            return(RedirectToAction("Index", "Home"));
        }
Esempio n. 58
0
        private void LegacyRestApiAsyncExample()
        {
            var fb = new FacebookClient(_accessToken);

            // make sure to add the appropriate event handler
            // before calling the async methods.
            // GetCompleted     => GetAsync
            // PostCompleted    => PostAsync
            // DeleteCompleted  => DeleteAsync
            fb.GetCompleted += (o, e) =>
            {
                // incase you support cancellation, make sure to check
                // e.Cancelled property first even before checking (e.Error!=null).
                if (e.Cancelled)
                {
                    // for this example, we can ignore as we don't allow this
                    // example to be cancelled.

                    // you can check e.Error for reasons behind the cancellation.
                    var cancellationError = e.Error;
                }
                else if (e.Error != null)
                {
                    // error occurred
                    this.BeginInvoke(new MethodInvoker(
                                         () =>
                    {
                        MessageBox.Show(e.Error.Message);
                    }));
                }
                else
                {
                    // the request was completed successfully

                    // now we can either cast it to IDictionary<string, object> or IList<object>
                    // depending on the type. or we could use dynamic.
                    dynamic result = e.GetResultData();

                    // or you could also use the generic version;
                    bool isFan = e.GetResultData <bool>();

                    // since this is an async callback, make sure to be on the right thread
                    // when working with the UI.
                    this.BeginInvoke(new MethodInvoker(
                                         () =>
                    {
                        chkCSharpSdkFan.Checked = isFan;
                    }));
                }
            };

            dynamic parameters = new ExpandoObject();

            // any parameter that has "method" automatically is treated as rest api.
            parameters.method  = "pages.isFan";
            parameters.page_id = "162171137156411";  // id of http://www.facebook.com/csharpsdk official page

            // for rest api only, parameters is enough
            // the rest method is determined by parameters.method
            fb.GetAsync(parameters);
        }
Esempio n. 59
0
        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn(string ReturnUrl)
        {
            if (FacebookWebContext.Current.IsAuthenticated() && FacebookWebContext.Current.IsAuthorized())
            {
                FacebookClient fbClient   = new FacebookClient(FacebookWebContext.Current.AccessToken);
                dynamic        me         = fbClient.Get("me");
                string         facebookId = (string)me.id;
                string         userEmail  = (string)me.email;

                if (facebookId == null || userEmail == null)
                {
                    throw new FacebookOAuthException();
                }

                var user = market.Users.SingleOrDefault(u => u.Email == userEmail);

                if (user == null)
                {
                    //User does not exist in our DB, let us kick him out
                    var model = new LogOnModel();
                    ModelState.AddModelError("", "Oops! Looks like you have not yet registered for an account.");
                    fbClient.Delete(facebookId + "/permissions");
                    FormsAuthentication.SignOut();
                    //fbClient.Delete(Url.Action("LogOn", "Account", null, Request.Url.Scheme, Request.Url.Host));
                    return(View(model));
                }

                var fbUser = market.FacebookUsers.SingleOrDefault(f => f.Id == facebookId);

                if (fbUser == null)
                {
                    MembershipUser RegisteredUser = Membership.GetUser(user.Email.ToLower());

                    if (RegisteredUser != null)
                    {
                        if (!RegisteredUser.IsApproved)
                        {
                            //User is in our DB but has already requested access and is pending approval. Let us kick him out.
                            var model = new LogOnModel();
                            ModelState.AddModelError("", "Sorry, your account has not yet been activated. Stay tuned, we're almost ready for you.");
                            fbClient.Delete(facebookId + "/permissions");
                            FormsAuthentication.SignOut();
                            return(View(model));
                        }
                    }

                    var location = me.location;
                    if (location == null)
                    {
                        location = me.hometown;
                        if (location == null)
                        {
                            return(View());
                        }
                    }
                    string[] address = ((string)location.name).Split(',');
                    string   city    = address[0].Trim();
                    string   prov    = address[1].Trim();

                    //Now creating the facebook user profile. We can wire this to the regular user by using a foreign key
                    market.FacebookUsers.Add(new FacebookUser
                    {
                        Id             = facebookId,
                        UserModelEmail = (string)me.email,
                        AccessToken    = FacebookWebContext.Current.AccessToken,
                        IsApproved     = true,
                        Expires        = FacebookWebContext.Current.Session.Expires
                    });
                    log.Info("Account - Creating new Facebook user (" + (string)me.first_name + " " + (string)me.last_name + ")");
                    market.SaveChanges();
                }
                else
                {
                    if (!fbUser.IsApproved)
                    {
                        //User has requested access previously using facebook and is pending approval. Let us kick him out.
                        var model = new LogOnModel();
                        ModelState.AddModelError("", "Sorry, your account has not yet been activated. Stay tuned, we're almost ready for you.");
                        fbClient.Delete(facebookId + "/permissions");
                        FormsAuthentication.SignOut();
                        return(View(model));
                    }
                }
                //User is either created or he/she exists. Let us sign them in using email as the username.
                FormsAuthentication.SetAuthCookie((string)me.email, false);
                Session["USER_F_NAME"] = (string)me.first_name;
                log.Info("Account - User logged in (" + (string)me.email + ")");
                if (Url.IsLocalUrl(ReturnUrl))
                {
                    return(Redirect(ReturnUrl));
                }
                else
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }
            return(View());
        }
 public ApiResultSerializationTest()
 {
     app = new FacebookClient();
     //app.Session = new FacebookSession
     //{
     //    AccessToken = ConfigurationManager.AppSettings["AccessToken"],
     //};
 }