コード例 #1
0
        private async void PublishStory()
        {
            var fb = new Facebook.FacebookClient(Session.ActiveSession.CurrentAccessTokenData.AccessToken);

            var postParams = new
            {
                name        = "Facebook SDK for .NET",
                caption     = "Build great social apps and get more installs.",
                description = "The Facebook SDK for .NET makes it easier and faster to develop Facebook integrated .NET apps.",
                link        = "http://facebooksdk.net/",
                picture     = "http://facebooksdk.net/assets/img/logo75x75.png"
            };

            try
            {
                dynamic fbPostTaskResult = await fb.PostTaskAsync("/me/feed", postParams);

                var result2 = (IDictionary <string, object>)fbPostTaskResult;

                var successMessageDialog = new Windows.UI.Popups.MessageDialog("Posted Open Graph Action, id: " + (string)result2["id"]);
                await successMessageDialog.ShowAsync();
            }
            catch (Exception ex)
            {
                MessageDialogHelper.Show("Exception during post: " + ex.Message);
            }
        }
コード例 #2
0
ファイル: FBLoginActivity.cs プロジェクト: YourmumisEZ/WTG
		protected override void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);
			fb = new FacebookClient();
			appId = Intent.GetStringExtra("AppId");
			permissions = Intent.GetStringExtra("Permissions");
			url = GetFacebookLoginUrl(appId, permissions);

			SetContentView (Resource.Layout.Login);
			WebView wv = FindViewById<WebView> (Resource.Id.FBWebView);
			wv.SetWebViewClient (new WebViewClient ());
			wv.Settings.JavaScriptEnabled = true;
			wv.LoadUrl (url);
//			WebView wv = new WebView (this);
//			wv.Settings.JavaScriptEnabled = true;
//			wv.Settings.SetSupportZoom(true);
//			wv.Settings.BuiltInZoomControls = true;
//			wv.Settings.LoadWithOverviewMode = true;
//			wv.ScrollBarStyle = ScrollbarStyles.OutsideOverlay;
//			wv.ScrollbarFadingEnabled = true;
//			wv.VerticalScrollBarEnabled = true;
//			wv.HorizontalScrollBarEnabled = true;			
//			//wv.SetWebViewClient (new FBWebClient (this));
//			//AddContentView(wv,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FillParent));
//			wv.LoadUrl(url);				
	}
コード例 #3
0
ファイル: DiscoverController.cs プロジェクト: mobarmg/inquire
        /*void fbPostCompleted(object sender, FacebookApiEventArgs e)
         * {
         *  string r;
         *
         *  if (e.Error == null)
         *      r = "ok";
         *  else
         *      r = String.Format("failed: {0}", e.Error.Message);
         *
         *  Helper.LogHelper.StatsLog(null, "fbUploadPhotoAjax() [async] ", r, null, null);
         * }*/

        public ActionResult fbGetUser(string id)
        {
            var     client = new Facebook.FacebookClient();
            dynamic me     = client.Get(id);

            return(Json(me, JsonRequestBehavior.AllowGet));
        }
コード例 #4
0
        public ActionResult Facebook()
        {
            var fb = new FacebookClient();
            Uri loginUrl;

            if (Request.Url.AbsoluteUri == "http://localhost:53624/Account/Facebook")
            {
                loginUrl = fb.GetLoginUrl(new
                {
                    client_id = "210504125641177",
                    client_secret = "d417ef6d72b9cdb430f938eb19c1b929",
                    redirect_uri = RedirectUri.AbsoluteUri,
                    response_type = "code",
                    scope = "user_birthday, email"
                });
            }
            else
            {
                loginUrl = fb.GetLoginUrl(new
                {
                    client_id = "118326544910444",
                    client_secret = "d2f09ce5b35cd32352d295be5df2ba39",
                    redirect_uri = RedirectUri.AbsoluteUri,
                    response_type = "code",
                    scope = "user_birthday, email"
                });
            }

            return Redirect(loginUrl.AbsoluteUri);
        }
コード例 #5
0
 public User Authenticate(string facebookAccessToken)
 {
     GameNickEntities entities = new GameNickEntities();
     FacebookClient fbclient = new FacebookClient(facebookAccessToken);
     dynamic me = fbclient.Get("me");
     long myId = (long)Convert.ToUInt64(me.id.ToString());
     var exists = from users in entities.Users
                  where users.FacebookID == myId
                  select users;
     if (exists.Count() > 0)
     {
         exists.First().Name = me.name;
         exists.First().FacebookAccessToken = facebookAccessToken;
         exists.First().GameNickAccessToken = Guid.NewGuid();
         entities.SaveChanges();
         User _me = exists.First();
         _me.Status.Load();
         _me.GameNicks.Load();
         return _me;
     }
     // ReSharper disable RedundantIfElseBlock
     else
     // ReSharper restore RedundantIfElseBlock
     {
         User user = User.CreateUser(myId, 0);
         user.Name = me.name;
         // check that the ID is updated to a new unique value when it's added
         entities.AddToUsers(user);
         entities.SaveChanges();
         // todo: update the userID before returing it
         return entities.Users.First(u => u.FacebookID == myId);//user;
     }
 }
コード例 #6
0
ファイル: FacebookController.cs プロジェクト: UrK/kululu_v1
        /// <summary>
        /// test if the specified users are admins of the fan page
        /// </summary>
        ///
        /// <param name="localbusinessId">
        /// local business ID
        /// </param>
        /// 
        /// <param name="userIds">
        /// list of users to be tested (JSON formatted array)
        /// </param>
        ///
        /// <returns>
        /// standard response with dictionary of users and their corresponding
        /// role: admin or not
        /// </returns>
        public virtual JsonResult ArePageAdmins(long localbusinessId,
            string userIds)
        {
            var localBusiness = Repository.Get<LocalBusiness>(localbusinessId);
            if (!localBusiness.IsOwner(CurrentUser.Id))
            {
                return BuildFailureResult(-1,
                    App_GlobalResources.Errors.accessDenied);
            }

            var accessToken = localBusiness.FBFanPageAccessToken;
            if (string.IsNullOrEmpty(accessToken))
            {
                return BuildFailureResult(-1,
                    App_GlobalResources.Errors.facebookAccessTokenNotStored);
            }

            var fbApp = new FacebookClient(accessToken);

            var serializer = new JavaScriptSerializer();
            var users = serializer.Deserialize<string[]>(userIds);
            var rslt = Dror.Common.Utils.Facebook.AreAdmins(
                fbApp,
                localBusiness.FanPageId,
                users,
                Logger);

            return BuildSuccessResult(1, rslt);
        }
        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);
            }
        }
コード例 #8
0
        private Uri GenerateLoginUrl(string appId, string extendedPermissions)
        {
            dynamic parameters = new ExpandoObject();

            parameters.client_id    = appId;
            parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";

            // 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 Facebook.FacebookClient();

            return(fb.GetLoginUrl(parameters));
        }
コード例 #9
0
ファイル: StatusPop.xaml.cs プロジェクト: tylorhl/FeedMaster
        private async void updateStatus(object sender, TappedRoutedEventArgs e)
        {
            PostButton.IsEnabled = false;
            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;
            string postText = "";
            StatusText.Document.GetText(Windows.UI.Text.TextGetOptions.None, out postText);
            parameters.message = postText.Replace("\r", "");
            dynamic result = null;

            try
            {
                result = await _fb.PostTaskAsync("me/feed", parameters);
            }
            catch (FacebookOAuthException ex)
            {
                Debug.WriteLine("Problem: " + ex.StackTrace);
                App.Progress.IsActive = false;
                App.Progress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                return;
            }

            App.Progress.IsActive = false;
            App.Progress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            statusBtn.closePostStatus();
        }
コード例 #10
0
        async private void Post_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            await this.loginButton.RequestNewPermissions("publish_actions");

            var facebookClient = new Facebook.FacebookClient(this.loginButton.CurrentSession.AccessToken);

            var postParams = new {
                message = Joke.Text
            };

            try
            {
                // me/feed posts to logged in user's feed
                dynamic fbPostTaskResult = await facebookClient.PostTaskAsync("/me/feed", postParams);

                var result = (IDictionary <string, object>)fbPostTaskResult;

                var successMessageDialog = new Windows.UI.Popups.MessageDialog("Posted Open Graph Action, id: " + (string)result["id"]);
                await successMessageDialog.ShowAsync();
            }
            catch (Exception ex)
            {
                var exceptionMessageDialog = new Windows.UI.Popups.MessageDialog("Exception during post: " + ex.Message);
                exceptionMessageDialog.ShowAsync();
            }
        }
コード例 #11
0
 protected void procesRequest()
 {
     if (Request.QueryString["op"] == "twitter")
     {
         string twtProfileId = Request.QueryString["id"].ToString();
         User user = (User)Session["LoggedUser"];
         strTwtArray = objtwtStatsHelper.getNewFollowers(user, twtProfileId,15);
         strTwtFollowing = objtwtStatsHelper.getNewFollowing(user, twtProfileId,15);
         // strTwtAge = objtwtStatsHelper.GetFollowersAgeWise(user);
         strIncomingMsg = objtwtStatsHelper.getIncomingMsg(user, twtProfileId,15);
         strDmRecieve = objtwtStatsHelper.getDirectMessageRecieve(user, twtProfileId);
         strDMSent = objtwtStatsHelper.getDirectMessageSent(user, twtProfileId);
         strSentMsg = objtwtStatsHelper.getSentMsg(user, twtProfileId,15);
         strRetweet = objtwtStatsHelper.getRetweets(user, twtProfileId,15);
         strAgeDiff = objtwtStatsRepo.getAgeDiffCount(twtProfileId, 15);
         strEngagement = objtwtStatsHelper.getEngagements(user, twtProfileId, 15);
         strInfluence = objtwtStatsHelper.getInfluence(user, twtProfileId, 15);
         Response.Write(strTwtArray + "@" + strTwtFollowing + "@" + strIncomingMsg + "@" + strDmRecieve + "@" + strDMSent + "@" + strSentMsg + "@" + strRetweet + "@" + strAgeDiff + "@" + strEngagement + "@" + strInfluence);
     }
     if (Request.QueryString["op"] == "facebook")
     {
         string fbProfileId = Request.QueryString["id"].ToString();
         User user = (User)Session["LoggedUser"];
        // objfbstatsHelper.getAllGroupsOnHome.InnerHtml = fbUser;
         strFbAgeArray = objfbstatsHelper.getLikesByGenderAge(fbProfileId, user.Id, 10);
         strPageImpression = objfbstatsHelper.getPageImressions(fbProfileId, user.Id, 10);
         strLocationArray = objfbstatsHelper.getLocationInsight(fbProfileId, user.Id, 10);
         objfbstatsHelper.getPostDetails(fbProfileId, user.Id, 10);
         FacebookClient fb = new FacebookClient();
         fb.AccessToken = Request.QueryString["access"].ToString();
         dynamic pagelikes = fb.Get(fbProfileId);
         string strval = pagelikes.likes.ToString() + " Total Likes " + pagelikes.talking_about_count + " People talking about this.";
         Response.Write(strFbAgeArray + "_" + strPageImpression + "_" + strLocationArray + "_" + strval);
     }
 }
コード例 #12
0
 private void GetDp(FBDialog fbd)
 {
     try
     {
         client             = new FacebookClient();
         client.AccessToken = fbd.access_token;
         dynamic me = client.Get("me?fields=picture.width(300),email,name,gender,birthday");
         if (me != null)
         {
             btnLogin.Visibility   = Visibility.Collapsed;
             txtPost.Visibility    = Visibility.Visible;
             btnPost.Visibility    = Visibility.Visible;
             lblPost.Visibility    = Visibility.Visible;
             rectDetail.Visibility = Visibility.Visible;
             Uri         uri       = new Uri(Convert.ToString(me.picture.data.url), UriKind.Absolute);
             ImageSource imgSource = new BitmapImage(uri);
             dpImage.Source    = imgSource;
             lblName.Content   = "Hello " + me[2] + " !!";
             lblEmail.Content  = "You logged in with email id :" + me[1];
             lblGender.Content = "Gender: " + me[3];
             string birthday = "Birthday : " + me[4];
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Problem while connecting to Facebook, please try again..");
         btnLogin.Visibility = Visibility.Collapsed;
     }
 }
コード例 #13
0
        public StreamItemCollection ExtendAccesstoken()
        {
            try
            {
                string accesstoken = "";

                string appid = "";
                string appsecret = "";

                FacebookClient client = new FacebookClient();
                dynamic Me = client.Get("oauth/access_token", new
                {
                    client_id = appid,
                    client_secret = appsecret,
                    grant_type = "fb_exchange_token",
                    fb_exchange_token = accesstoken,
                    redirect_uri ="http://www.example.com",
                });

            }
            catch (Exception exc)
            {

                throw;
            }

            return null;
        }
コード例 #14
0
        public StreamItemCollection GetStreamItemCollection()
        {
            try
            {
                ExtendAccesstoken();

                string accesstoken = "";

                string appid = "";
                string appsecret = "";

                FacebookClient client = new FacebookClient();
                dynamic Me = client.Get(@"me/home");

                string aboutMe = Me.about;

            }
            catch (Exception exc)
            {

                throw;
            }

            return null;
        }
コード例 #15
0
        public Dictionary<DateTime, int> getFacebookPageLikes(string PageId, string Accesstoken, int days)
        {


            //string accesstoken = "CAACEdEose0cBAMQVEgKsHtUogOZCQ9vtBZB6FjsUWuZCVEzVUU01yecHqo1fVpTfQq65tmMUfmlafhmGtzmUY6ZCmZBrEXWMp1sfBLMvtdB7c1HBkSBGxbqT0q0nQY6ZBmtPBhg84IrXy4jBjRdMmP1Mh8hlOC9TRuy86jabDi2ccOyeRXYVZA7vuj4HDYgLhrwlNubCYvkENa6nPuY1PCgkuCv1cS8rXMZD";
            try
            {
                long since = DateTime.Now.AddDays(-days).ToUnixTimestamp();
                long until = DateTime.Now.ToUnixTimestamp();
                FacebookClient fb = new FacebookClient();
                fb.AccessToken = Accesstoken;
                //dynamic kasdfj = fb.Get("v2.3/me/permissions");
                dynamic kajlsfdj = fb.Get("v2.0/" + PageId + "/insights/page_fans?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString());
                string facebookSearchUrl = "https://graph.facebook.com/v2.3/" + PageId + "/insights/page_fans?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString() + "&access_token=" + Accesstoken;
                string outputface = getFacebookResponse(facebookSearchUrl);
                Dictionary<DateTime, int> LikesByDay = new Dictionary<DateTime, int>();
                LikesByDay = getFacebookLikesDictonary(outputface);

                return LikesByDay;
            }
            catch (Exception ex)
            {
                return new Dictionary<DateTime, int>();
            }

        }
コード例 #16
0
        public JsonResult Create(string facebookToken)
        {
            var client = new FacebookClient(facebookToken);
            dynamic user = client.Get("me");

            string userId = user.id;
            var siteUser = DocumentSession.Query<User>()
                                          .SingleOrDefault(x => x.Id == userId);

            if(siteUser == null)
            {
                var newUser = new User
                                  {
                                      Name = user.name,
                                      Roles = { Role.User }
                                  };

                DocumentSession.Store(newUser, user.id);
                siteUser = newUser;
            }

            FormsAuthentication.SetAuthCookie(siteUser.Id, false);

              return Json(new { user.id, user.name });
        }
コード例 #17
0
        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);
            }
        }
コード例 #18
0
        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;
        }
コード例 #19
0
    //HTTPMODULE!!
    protected void Page_Load(object sender, EventArgs e)
    {
        if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
            if (User.IsInRole("Triphulcas"))
                WelcomeMessage = Resources.Resource1.SnippetTriphulcasWelcomeMessage;

            if (!String.IsNullOrEmpty(User.AccessToken))
                {
                    try
                    {                        
                        var client = new FacebookClient(User.AccessToken);
                        dynamic result = client.Get("me", new { fields = "id" });
                        pImage.Src = String.Format(Resources.Resource1.FacebookPictureUrl, result.id);
                        pWelcome.InnerText = WelcomeMessage;
                        pLogout.Attributes.Remove("hidden");
                        pLogout.Attributes["style"] = "display:block";
                    }
                    catch (FacebookOAuthException)
                    {
                    }
                }            
        }
        
        else
        {
            //ugly, I know.
            pWelcome.InnerHtml = String.Format("{0} <a class=\"popup\" href=\"/authentication.aspx\">{1}</a>.", 
                Resources.Resource1.SnippetShowFaceBeforeLink, 
                Resources.Resource1.SnippetShowFaceLink);
        }
    }
コード例 #20
0
 private void btnGetFriendsList_Click(object sender, RoutedEventArgs e)
 {
     FacebookClient client = new FacebookClient(Token());
     string fqlFriendsList = "SELECT uid2 FROM friend where uid1=me()";
     client.GetCompleted += new EventHandler<FacebookApiEventArgs>(client_GetCompleted);
     client.QueryAsync(fqlFriendsList, Token());
 }
コード例 #21
0
 public ActionResult Connect(string returnUrl)
 {
     // TODO: Rebuild functionality using CoffeeScript implementation and new C# API
     var fb = new FacebookClient();
     var loginUri = fb.GetLoginUrl(new { state = returnUrl });
     return Redirect(loginUri.AbsoluteUri);
 }
コード例 #22
0
ファイル: FacebookAgent.cs プロジェクト: SeshuMiriyala/MQ163
        /// <summary>
        /// Posts the messages and Picture to the MQ163 Feeds
        /// </summary>
        /// <param name="postData">Data to be posted</param>
        /// <returns>Returns True: If posted successfully. 
        /// Exception: If post is unsuccessfull</returns>
        internal bool AddPost(IFacebookPostData postData)
        {
            try
            {
                string accessToken = GetPageAccessToken();
                string albumID = GetAlbumID();
                var fb = new FacebookClient();
                postData.AccessToken = accessToken;

                string path = string.Format("{0}/photos?access_token={1}", albumID, accessToken);
                dynamic publishResponse;
                if (null != postData.TaggedUserEmail)
                    publishResponse = client.PostTaskAsync(path, postData.GetPostObject(GetUserID(postData.TaggedUserEmail).Id));
                else
                    publishResponse = client.PostTaskAsync(path, postData.GetPostObject(String.Empty));

                while (publishResponse.Status == TaskStatus.WaitingForActivation) ;
                if (publishResponse.Status == TaskStatus.RanToCompletion)
                    return true;
                else if (publishResponse.Status == TaskStatus.Faulted)
                {
                    throw (new InvalidOperationException((((Exception)publishResponse.Exception).InnerException).Message, (Exception)publishResponse.Exception));
                }
                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #23
0
ファイル: FacebookLayer.cs プロジェクト: otarazan/socialermap
        /*
        public FacebookLayer()
        {
            authorizer = new CanvasAuthorizer { Perms = "publish_stream" };
            if (authorizer.Authorize())
            {
                fbClient = new FacebookClient(CurrentSession.AccessToken);
                User = new FacebookUser();
                try
                {
                    var me = (IDictionary<string, object>) fbClient.Get("me");

                    User.FacebookId = (string) me["id"];
                    User.FacebookName = (string) me["first_name"];
                }
                catch
                {
                    isAccessTokenValid = false;
                    return;
                }
                isAccessTokenValid = true;
                IDictionary<string, object> friendsData = (IDictionary<string, object>) fbClient.Get("me/friends");
                facebookData = new FacebookData(User, friendsData);
                SortedFriends = facebookData.SortedFriends;
            }
        }
        */
        public FacebookLayer(CanvasAuthorizer auth)
        {
            this.authorizer = auth;
            if (this.authorizer.Authorize())
            {
                fbClient = new FacebookClient(CurrentSession.AccessToken);
                User = new FacebookUser();
                try
                {
                    var me = (IDictionary<string, object>) fbClient.Get("me");

                    User.FacebookId = (string) me["id"];
                    User.FacebookName = (string) me["first_name"];
                }
                catch
                {
                    isAccessTokenValid = false;
                    return;
                }
                isAccessTokenValid = true;
                IDictionary<string, object> friendsData = (IDictionary<string, object>) fbClient.Get("me/friends");
                facebookData = new FacebookData(User, (IList<object>)friendsData["data"]);

            }
        }
コード例 #24
0
        public FrmFacebookPost()
        {
            client = new FacebookClient();

            client.PostCompleted += (o, args) =>
            {

                if (args.Error != null)
                {
                    var error = args.Error as FacebookApiException;
                    if (error.ErrorCode == 190)
                    {
                        Dispatcher.BeginInvoke(() => MessageBox.Show("Authorization Error"));
                        SaveToken(null);
                        client.AccessToken = null;
                        return;
                    }
                    Dispatcher.BeginInvoke(() => MessageBox.Show(error.Message));
                    return;
                }

                var result = (IDictionary<string, object>)args.GetResultData();

                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Message posted successfully");
                    Browser.Visibility = System.Windows.Visibility.Collapsed;
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        StrCommonObject = JsonConvert.SerializeObject(ObjCommon);
                        NavigationService.Navigate(new Uri("/Pages/FrmProgress.xaml?common=" + StrCommonObject, UriKind.Relative));
                    });
                });
            };

            if (GetToken() != null)
                client.AccessToken = GetToken();

            InitializeComponent();

            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                Dispatcher.BeginInvoke(() => { MessageBox.Show("No Internet Connection, Try again later"); });
                return;
            }

            //If we already have an access token, then just post, otherwise move to the login page
            if (client.AccessToken == null)
            {
                var parameters = new Dictionary<string, object>();
                parameters["client_id"] = FBApiID;
                parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
                parameters["response_type"] = "token";
                parameters["display"] = "touch";
                parameters["scope"] = ExtendedPermisions;
                Browser.Visibility = System.Windows.Visibility.Visible;
                string t = client.GetLoginUrl(parameters).AbsoluteUri;
                Browser.Navigate(client.GetLoginUrl(parameters));
            }
        }
コード例 #25
0
        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);
        }
コード例 #26
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            fb = new FacebookClient ();
            appId = Intent.GetStringExtra ("AppId");
            extendedPermissions = Intent.GetStringExtra ("ExtendedPermissions");
            url = GetFacebookLoginUrl (appId, extendedPermissions);

            WebView webView = new WebView(this);
            webView.Settings.JavaScriptEnabled = true;
            webView.Settings.SetSupportZoom(true);
            webView.Settings.BuiltInZoomControls = true;
            webView.Settings.LoadWithOverviewMode = true; //Load 100% zoomed out
            webView.ScrollBarStyle = ScrollbarStyles.OutsideOverlay;
            webView.ScrollbarFadingEnabled = true;

            webView.VerticalScrollBarEnabled = true;
            webView.HorizontalScrollBarEnabled = true;

            webView.SetWebViewClient(new FBWebClient (this));
            webView.SetWebChromeClient(new FBWebChromeClient (this));

            AddContentView(webView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.FillParent));

            webView.LoadUrl(url);
        }
        private void btnUpload_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(_filename))
            {
                MessageBox.Show("Please select the image file first.");
                return;
            }

            var mediaObject = new FacebookMediaObject
            {
                ContentType = "image/jpeg",
                FileName = Path.GetFileName(_filename)
            }
                                  .SetValue(File.ReadAllBytes(_filename));

            progressBar1.Value = 0;

            var fb = new FacebookClient(_accessToken);
            fb.UploadProgressChanged += fb_UploadProgressChanged;
            fb.PostCompleted += fb_PostCompleted;

            // for cancellation
            _fb = fb;

            fb.PostAsync("/me/photos", new Dictionary<string, object> { { "source", mediaObject } });
        }
コード例 #28
0
ファイル: GraphApi.cs プロジェクト: Adron/Regiztry
        public static void GetSampleWithoutAccessToken()
        {
            try
            {
                var fb = new FacebookClient();

                var result = (IDictionary<string, object>)fb.Get("/4");

                var id = (string)result["id"];
                var name = (string)result["name"];
                var firstName = (string)result["first_name"];
                var lastName = (string)result["last_name"];

                Console.WriteLine("Id: {0}", id);
                Console.WriteLine("Name: {0}", name);
                Console.WriteLine("First Name: {0}", firstName);
                Console.WriteLine("Last Name: {0}", lastName);
                Console.WriteLine();

                // Note: This json result is not the orginal json string as returned by Facebook.
                Console.WriteLine("Json: {0}", result.ToString());
            }
            catch (FacebookApiException ex)
            {
                // Note: make sure to handle this exception.
                throw;
            }
        }
コード例 #29
0
        public RedirectToRouteResult FacebookCallback(string code)
        {
            var fb = new Facebook.FacebookClient();

            try
            {
                dynamic result = fb.Post("oauth/access_token", new
                {
                    client_id     = "",
                    client_secret = "",
                    redirect_uri  = RedirectUri.AbsoluteUri,
                    code          = code
                });

                var accessToken = result.access_token;
                Session["AccessToken"] = accessToken;
                fb.AccessToken         = accessToken;

                dynamic me   = fb.Get("me?fields=first_name,last_name,id,email");
                User    user = new User();
                user.login           = me.first_name.ToString() + "FB";
                user.email           = me.email.ToString();
                user.password        = me.id.ToString();
                user.validationEmail = true;
                UserService.InserNew(user);
            }
            catch { }
            return(RedirectToAction("Index", "Account"));
        }
コード例 #30
0
        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;
        }
コード例 #31
0
ファイル: BaseController.cs プロジェクト: UrK/kululu_v1
 protected BaseController(IRepository repository, FacebookClient app,
     ILogger logger)
 {
     Repository = repository;
     FacebookApp = app;
     Logger = logger;
 }
コード例 #32
0
ファイル: FQL.cs プロジェクト: rehabriad/MyNokat
        public static void MultiQuery(string accessToken)
        {
            var query1 = "SELECT uid FROM user WHERE uid=me()";
            var query2 = "SELECT profile_url FROM user WHERE uid=me()";

            try
            {
                var fb = new FacebookClient(accessToken);

                var result = (IList<object>)fb.Query(query1, query2);

                var result0 = ((IDictionary<string, object>)result[0])["fql_result_set"];
                var result1 = ((IDictionary<string, object>)result[1])["fql_result_set"];

                Console.WriteLine("Query 0 result: {0}", result0);
                Console.WriteLine();
                Console.WriteLine("Query 1 result: {0}", result1);
                Console.WriteLine();

                // Note: This json result is not the orginal json string as returned by Facebook.
                Console.WriteLine("Json: {0}", result.ToString());
            }
            catch (FacebookApiException ex)
            {
                // Note: make sure to handle this exception.
                throw;
            }
        }
コード例 #33
0
        public void SetToken(string token)
        {
            if (token == null) throw new ArgumentNullException("token");

            Token = token;
            _client = null;
        }
コード例 #34
0
ファイル: FQL.cs プロジェクト: rehabriad/MyNokat
        public static void SingleQuery(string accessToken)
        {
            var query = string.Format("SELECT uid,pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1={0})", "me()");

            try
            {
                var fb = new FacebookClient(accessToken);

                var result = (IList<object>)fb.Query(query);

                foreach (var row in result)
                {
                    var r = (IDictionary<string, object>)row;
                    var uid = (long)r["uid"];
                    var picSquare = (string)r["pic_square"];

                    Console.WriteLine("User Id: {0}", uid);
                    Console.WriteLine("Picture Square: {0}", picSquare);
                    Console.WriteLine();
                }

                // Note: This json result is not the orginal json string as returned by Facebook.
                Console.WriteLine("Json: {0}", result.ToString());
            }
            catch (FacebookApiException ex)
            {
                // Note: make sure to handle this exception.
                throw;
            }
        }
コード例 #35
0
ファイル: AccountController.cs プロジェクト: tep-pl/Radar
        public ActionResult FacebookCallback(string code)
        {
            var fb = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id = "462931197153588",
                client_secret = "82c4ec01d4516d06889341aed8857e5b",
                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?fields=first_name,last_name,id,email");
            string email = me.email;

            // Set the auth cookie
            FormsAuthentication.SetAuthCookie(email, false);

            return RedirectToAction("Index", "Home");
        }
コード例 #36
0
        public FacebookLoginDialog(string appId, string extendedPermissions)
        {
            if (string.IsNullOrEmpty(appId))
                throw new ArgumentNullException("appId");

            var fb = new FacebookClient();

            IDictionary<string, object> loginParameters = new Dictionary<string, object>();

            loginParameters["client_id"] = appId;
            loginParameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";

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

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

            // add the 'scope' parameter only if we have extendedPermissions.
            if (!string.IsNullOrEmpty(extendedPermissions))
            {
                // A comma-delimited list of permissions
                loginParameters["scope"] = extendedPermissions;
            }

            // when the Form is loaded navigate to the login url.
            _loginUrl = fb.GetLoginUrl(loginParameters);

            InitializeComponent();
        }
コード例 #37
0
ファイル: FB.cs プロジェクト: kashwaa/fb_group_archiver
        public static FacebookClient GetClient(bool reload=false)
        {
            if (reload)
               client = null;
               if (client!=null)
               {
               return client;
               }

               try
               {
               client = new FacebookClient(Data.Get("token"));

               me = client.Get("me/");

               }
               catch (WebExceptionWrapper)
               {
               throw new NoConnection();
               }
               catch (Exception)
               {

               return null;
               }

               return client;
        }
コード例 #38
0
        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);
        }
コード例 #39
0
        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"));
                }
            }
        }
コード例 #40
0
 private FBQueryManager()
 {
     m_token            = "";
     m_fbClient         = null;
     m_userInfo         = null;
     m_conversations    = null;
     m_messages         = null;
     m_next             = "";
     m_apiExceededError = false;
 }
コード例 #41
0
    public static async Task <bool> EnsureRequiredPermissions(Facebook.FacebookClient facebookClient, params string[] Permissions)
    {
        var requiredPermissions = new List <String>(Permissions);
        var userPerms           = await GetArrayAsync <UserPermission>(facebookClient, "me/permissions");

        var allowed = from e in userPerms where e.Granted select e.Permission;

        requiredPermissions.RemoveAll(o => allowed.Contains(o));
        return(requiredPermissions.Count == 0);
    }
コード例 #42
0
        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);
        }
コード例 #43
0
ファイル: Settings.xaml.cs プロジェクト: abbad/EventsFinder
        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;
        }
コード例 #44
0
        /// <summary>
        /// Gets the picture info.
        /// </summary>
        /// <param name="pUserId">The user id.</param>
        /// <returns></returns>
        /// <exception cref="System.ApplicationException">pUserId cannot be null</exception>
        public dynamic GetPictureInfo(string pUserId)
        {
            if (pUserId == null)
            {
                throw new ApplicationException("pUserId cannot be null");
            }

            var fb = new Facebook.FacebookClient(this.GetAppAccessToken());

            return(fb.Get(string.Concat(pUserId, "/picture")));
        }
コード例 #45
0
        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());
        }
コード例 #46
0
ファイル: Tea.aspx.cs プロジェクト: MnHung/kerkertea
        /// <summary>
        /// 設為封面照片
        /// </summary>
        /// <param name="fbApp"></param>
        /// <param name="PhotoID"></param>
        private void SetCoverPhoto(Facebook.FacebookClient fbApp, string PhotoID)
        {
            dynamic param = new ExpandoObject();

            param = new
            {
                access_token  = Session["PageAccessToken"].ToString(),
                cover         = PhotoID,
                no_feed_story = true
            };

            fbApp.Post(_pageID, param);
        }
コード例 #47
0
        public ActionResult Facebook()
        {
            Facebook.FacebookClient fb = new Facebook.FacebookClient();
            var loginUrl = fb.GetLoginUrl(new
            {
                client_id     = "<Your application ID>",
                redirect_uri  = RedirectUri.AbsoluteUri,
                response_type = "code",
                scope         = "email,publish_actions,user_posts,publish_pages,manage_pages,user_likes"
            });

            return(Redirect(loginUrl.AbsoluteUri));
        }
コード例 #48
0
        private void webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            // whenever the browser navigates to a new url, try parsing the url.
            // the url may be the result of OAuth 2.0 authentication.
            var fb = new Facebook.FacebookClient();
            FacebookOAuthResult oauthResult;

            if (fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
            {
                // The url is the result of OAuth 2.0 authentication
                if (oauthResult.IsSuccess)
                {
                    Settings1.Default.FacebookToken = oauthResult.AccessToken;
                    fb.AccessToken = Settings1.Default.FacebookToken;

                    //now retrieve all connected accounts and if there are more than one then display combobox allows user to choose which account he want to use
                    JsonObject fbAccounts = (JsonObject)fb.Get("/me/accounts");

                    ListItem <string> item = new ListItem <string>(Strings.FacebookLoginWindow_DefaultAccount, oauthResult.AccessToken);
                    cmbFacebookAccounts.Items.Add(item);

                    foreach (dynamic account in (IEnumerable)fbAccounts["data"])
                    {
                        item = new ListItem <string>(account["name"], account["access_token"]);
                        cmbFacebookAccounts.Items.Add(item);
                    }
                    if (cmbFacebookAccounts.Items.Count == 1)
                    {
                        DialogResult = true;
                        Close();
                    }
                    else
                    {
                        cmbFacebookAccounts.SelectedIndex = 0;
                        webBrowser.Visibility             = Visibility.Collapsed;
                        pnlChooseAccount.Visibility       = Visibility.Visible;
                    }
                }
                else
                {
                    //var errorDescription = oauthResult.ErrorDescription;
                    //var errorReason = oauthResult.ErrorReason;
                    DialogResult = false;
                    Close();
                }
            }
            else
            {
                // The url is NOT the result of OAuth 2.0 authentication.
            }
        }
コード例 #49
0
    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);
    }
コード例 #50
0
        private async void PublishStory()
        {
            try
            {
                SetProgressIndicator("Publish Status", true);
                try
                {
                    await this.loginButton.RequestNewPermissions("publish_stream");

                    var facebookClient = new Facebook.FacebookClient(this.loginButton.CurrentSession.AccessToken);

                    var postParams = new
                    {
                        message     = Text_Status.Text,
                        name        = (DTO_Class.Song_Post.Name == null && DTO_Class.Song_Post.Artist.Name == null) ? "Music Room for Window Phone" : DTO_Class.Song_Post.Name + " -- " + DTO_Class.Song_Post.Artist.Name,
                        caption     = "Application for Window Phone", /* -- DuyNguyenIT Developer"*/
                        description = "Come here with music, let's draw your life! Share from Music Room Window Phone",
                        link        = "http://www.windowsphone.com/vi-vn/store/app/musicroom/8d67625c-9c09-4a0e-b6d4-6fe29aa37f7a",
                        picture     = (DTO_Class.Song_Post.Image == null || DTO_Class.Song_Post.URL == null) ? "http://cdn.marketplaceimages.windowsphone.com/v8/images/575e6ab1-00bb-456c-bc9d-82b794a11db9?imageType=ws_icon_large" : DTO_Class.Song_Post.Image
                    };

                    try
                    {
                        dynamic fbPostTaskResult = await facebookClient.PostTaskAsync("/me/feed", postParams);

                        var result = (IDictionary <string, object>)fbPostTaskResult;

                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show("Successful! Your status is posted");
                        });
                    }
                    catch (Exception ex)
                    {
                        SetProgressIndicator("", false);
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show("Fail post! Have exception is :' " + ex.Message + "' !", "Error", MessageBoxButton.OK);
                        });
                    }
                    SetProgressIndicator("", false);
                }
                catch { SetProgressIndicator("", false); }
            }
            catch { }
        }
コード例 #51
0
ファイル: Tea.aspx.cs プロジェクト: MnHung/kerkertea
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            Facebook.FacebookClient fb = PreparePhoto();

            //_fileName = "Koala.jpg";
            string ImagePath = Server.MapPath("~/img/" + _fileName);

            byte[] filebytes = System.IO.File.ReadAllBytes(ImagePath);

            // 上傳照片
            JsonObject result = UploadPhoto(fb, ImagePath, filebytes, null);

            // 設為封面
            //SetCoverPhoto(fb, result["id"].ToString());

            //string txt = string.Format("<p>上傳成功: <a href='https://www.facebook.com/photo.php?fbid={0}' target='_blank'>點擊這裡查看照片</a>,並<a href='https://www.facebook.com/{1}' target='_blank'>看看</a>是否已經設為封面了", result["id"].ToString(), _pageID);
            //Response.Write(txt);
        }
コード例 #52
0
 public ActionResult Facebook()
 {
     try
     {
         var fb       = new Facebook.FacebookClient();
         var loginUrl = fb.GetLoginUrl(new
         {
             client_id     = "",
             client_secret = "",
             redirect_uri  = RedirectUri.AbsoluteUri,
             response_type = "code",
             scope         = "email"
         });
         return(Redirect(loginUrl.AbsoluteUri));
     }
     catch { }
     return(View("Index"));
 }
コード例 #53
0
        /// <summary>
        ///  Function that will try to reserve a person in an event.
        /// </summary>
        /// <param name="eID"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        async public Task <bool> RSVPEvent(string eID, String status)
        {
            var fb         = new Facebook.FacebookClient(App.AccessToken);
            var parameters = new Dictionary <string, object>();

            parameters["access_token"] = App.AccessToken;
            bool result;

            try
            {
                result = (bool)await fb.PostTaskAsync(String.Format(@"/{0}/{1}", eID, status), parameters);
            }
            catch (Facebook.FacebookOAuthException)
            {
                result = false;
            }
            return(result);
        }
コード例 #54
0
        private async void PostToWall(string status)
        {
            try
            {
                facebookClient = new Facebook.FacebookClient(App.fbaccesstokenkey);
                var parameters = new Dictionary <string, object>();
                //var parameters1 = new Dictionary<string, object>();

                parameters["message"]     = status;
                parameters["caption"]     = string.Empty;
                parameters["description"] = string.Empty;
                parameters["req_perms"]   = "publish_stream";
                parameters["scope"]       = "publish_stream";
                parameters["type"]        = "normal";
                dynamic fbPostTaskResult = null;
                if (imageStatus)
                {
                    var mediaObject = new FacebookMediaObject
                    {
                        ContentType = "image/jpeg",
                        FileName    = "pokemon.jpg"
                    }.SetValue(byteImage);
                    parameters["source"] = mediaObject;
                    fbPostTaskResult     = await facebookClient.PostTaskAsync("/me/photos", parameters);
                }
                else
                {
                    fbPostTaskResult = await facebookClient.PostTaskAsync("/me/feed", parameters);
                }
                var result = (IDictionary <string, object>)fbPostTaskResult;

                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Posted Open Graph Action, id: " + (string)result["id"], "Result", MessageBoxButton.OK);
                });
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Exception during post: " + ex.ToString(), "Error", MessageBoxButton.OK);
                });
            }
        }
コード例 #55
0
ファイル: Tea.aspx.cs プロジェクト: MnHung/kerkertea
        private FacebookClient PreparePhoto()
        {
            // 選擇的粉絲專頁
            //_pageID = ddlPageID.SelectedValue;
            //_pageID = "1474910372779635";
            // 照片檔名
            //_fileName = tbFileName.Text;

            printMessage("Image name :" + _fileName);

            Facebook.FacebookClient fb = new Facebook.FacebookClient(Session["accessToken"].ToString());

            printMessage("# access token again :" + Session["accessToken"].ToString());

            IDictionary <string, object> dic = (IDictionary <string, object>)fb.Get("/me/accounts");

            // 列出所有我管理的粉絲專頁
            IList <object> dicy = (IList <object>)dic["data"];
            IDictionary <string, object> page = null;

            for (int i = 0; i <= dicy.Count - 1; i++)
            {
                page = (IDictionary <string, object>)dicy[i];

                // 如果是這次要上傳的粉絲專頁 ID
                if (page["id"].ToString() == _pageID)
                {
                    // 取得粉絲專頁的 access_token,才能針對粉絲專頁做 graph api 動作
                    //CAAJ1UqBRmVEBALIU6CtOWPWcRtmcpPnY82NHMxndEAHwg72LDdgqD47u0jrsBH92fDlxSFa5VkJHZAxwWNfvyrMkPJ4docUM3Af98QnnefVYeMWu7TApray7feamYUDhk9nRadCLkIbme4IDfA6NAj8iKlvFZC2LIEujRYaZAuX12LkA2fm
                    string pageAccessToken = page["access_token"].ToString();
                    pageAccessToken            = "CAAJ1UqBRmVEBALIU6CtOWPWcRtmcpPnY82NHMxndEAHwg72LDdgqD47u0jrsBH92fDlxSFa5VkJHZAxwWNfvyrMkPJ4docUM3Af98QnnefVYeMWu7TApray7feamYUDhk9nRadCLkIbme4IDfA6NAj8iKlvFZC2LIEujRYaZAuX12LkA2fm";
                    fb.AccessToken             = pageAccessToken;
                    Session["PageAccessToken"] = pageAccessToken;
                    break;
                }
            }

            if (Session["PageAccessToken"] == null || string.IsNullOrEmpty(Session["PageAccessToken"].ToString()))
            {
                Response.Write("無法管理此粉絲專頁: " + _pageID);
                Response.End();
            }
            return(fb);
        }
コード例 #56
0
        public Uri getLogoutURL()
        {
            // TODO: There is a bug with the logout
            dynamic parameters = new System.Dynamic.ExpandoObject();

            parameters.access_token = m_token;
            parameters.next         = FBQueryManager.LOGOUT_URL;

            Facebook.FacebookClient FBClient = new Facebook.FacebookClient();
            FBClient.AccessToken = m_token;
            FBClient.AppId       = m_APP_ID;
            FBClient.AppSecret   = m_APP_SECRET;

            // string redirectUrl = "";
            // string accessToken = "";
            // new Uri("https://www.facebook.com/logout.php?next=" + redirectUrl + "&access_token=" + accessToken)

            return(FBClient.GetLogoutUrl(parameters));
        }
コード例 #57
0
        public Uri getLoginURL()
        {
            dynamic parameters = new System.Dynamic.ExpandoObject();

            parameters.client_id    = m_APP_ID;
            parameters.redirect_uri = m_SUCCESS_URI;

            // 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.
            string extendedPermissions = "read_mailbox";

            parameters.scope = extendedPermissions;

            // generate the login url

            dynamic token = null;

            Facebook.FacebookClient FBClient = new Facebook.FacebookClient();
            try
            {
                token = FBClient.Get("oauth/access_token", new
                {
                    client_id     = m_APP_ID,     // "1465357507096514"
                    client_secret = m_APP_SECRET, // "ac5817c4f2dd07bf18137d7297d4015c"
                    grant_type    = "client_credentials"
                });
            }
            catch (WebExceptionWrapper)
            {
                ErrorMessages.WebConnectionFailure();
                return(null);
            }
            FBClient.AccessToken = token.access_token;
            FBClient.AppId       = m_APP_ID;
            FBClient.AppSecret   = m_APP_SECRET;

            return(FBClient.GetLoginUrl(parameters));
        }
コード例 #58
0
        /// <summary>
        /// Gets the authenticated user info.
        /// </summary>
        /// <param name="pAccessTokenRequest">The access token request.</param>
        /// <param name="pCSRFstateRequest">The CSRF state code request.</param>
        /// <param name="pSessionState">State of the HttpSessionState.</param>
        /// <returns></returns>
        /// <exception cref="System.ApplicationException">pAccessTokenRequest or pCSRFstateRequest cannot be null</exception>
        /// <exception cref="System.Security.SecurityException">invalid CSRF</exception>
        public dynamic GetAuthenticatedUserInfo(string pAccessTokenRequest, string pCSRFstateRequest, HttpSessionStateBase pSessionState)
        {
            if (string.IsNullOrEmpty(pAccessTokenRequest))
            {
                throw new ApplicationException("pAccessTokenRequest cannot be null");
            }
            if (pSessionState == null)
            {
                throw new ApplicationException("pSessionState cannot be null");
            }
            if (pSessionState["state"].ToString() != pCSRFstateRequest)
            {
                throw new System.Security.SecurityException("Invalid pCSRFstateRequest value");
            }

            var fb = new Facebook.FacebookClient(pAccessTokenRequest);

            return(fb.Get("me"));
        }
コード例 #59
0
        private async void PublishStory()
        {
            SetProgressIndicator("Publish Status", true);
            try
            {
                await this.loginButton.RequestNewPermissions("publish_stream");

                var facebookClient = new Facebook.FacebookClient(this.loginButton.CurrentSession.AccessToken);

                var postParams = new
                {
                    message     = Text_Status.Text,
                    name        = (DTO_Class.Song_Post.Name == null && DTO_Class.Song_Post.Artist.Name == null)? "Ứng dụng Music Room for Window Phone": DTO_Class.Song_Post.Name + " -- " + DTO_Class.Song_Post.Artist.Name,
                    caption     = "Application for Window Phone", /* -- Nguyễn Duy Nguyên Developer"*/
                    description = "Âm nhạc thăng hoa, dâng tràn cảm xúc! Được chia sẽ từ Ứng dụng Music Room Window Phone",
                    link        = (DTO_Class.Song_Post.URL == null) ? "http://facebooksdk.net/": DTO_Class.Song_Post.URL,
                    picture     = (DTO_Class.Song_Post.Image == null || DTO_Class.Song_Post.URL == null) ? "http://facebooksdk.net/assets/img/logo75x75.png" : DTO_Class.Song_Post.Image
                };

                try
                {
                    dynamic fbPostTaskResult = await facebookClient.PostTaskAsync("/me/feed", postParams);

                    var result = (IDictionary <string, object>)fbPostTaskResult;

                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("Successful! Your status is posted");
                    });
                }
                catch (Exception ex)
                {
                    SetProgressIndicator("", false);
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("Fail post! Have exception is :' " + ex.Message + "' !", "Error", MessageBoxButton.OK);
                    });
                }
                SetProgressIndicator("", false);
            }
            catch { SetProgressIndicator("", false); }
        }
コード例 #60
0
        /// <summary>
        /// Gets the custom graph data.
        /// </summary>
        /// <param name="pUserId">The user id.</param>
        /// <param name="pGraph">The graph term. <example>/picture</example><example>/books</example></param>
        /// <returns></returns>
        /// <exception cref="System.ApplicationException">pUserId or pGraph cannot be null</exception>
        public dynamic GetCustomGraphData(string pUserId, string pGraph)
        {
            if (pUserId == null)
            {
                throw new ApplicationException("pUserId cannot be null");
            }
            if (pGraph == null)
            {
                throw new ApplicationException("pGraph cannot be null");
            }

            if (pGraph[0] != '/')
            {
                pGraph = string.Concat("/", pGraph);
            }

            var fb = new Facebook.FacebookClient(this.GetAppAccessToken());

            return(fb.Get(string.Concat(pUserId, pGraph)));
        }