コード例 #1
0
        public ActionResult OAuth(string access_token, string expires)
        {
            DateTime expiresOn = DateTime.MaxValue;

            if (!String.IsNullOrEmpty(expires) && expires != "0")
            {
                expiresOn = DateTimeConvertor.FromUnixTime(expires);
            }

            FacebookClient fbClient   = new FacebookClient(access_token);
            dynamic        me         = fbClient.Get("me?fields=id,name");
            long           facebookId = Convert.ToInt64(me.id);

            // TODO: add this to the account
            //this.Repository.Add(new FacebookUser
            //{
            //    AccessToken = accessToken,
            //    Expires = expiresOn,
            //    FacebookId = facebookId,
            //    Name = (string)me.name,
            //});

            FormsAuthentication.SetAuthCookie(facebookId.ToString(), false);

            // prevent open redirection attack by checking if the url is local.
            return(View());
        }
コード例 #2
0
            public void ShouldConvertCorrectly()
            {
                var dateTime = new DateTime(2012, 1, 28, 18, 14, 33, DateTimeKind.Utc);

                var result = DateTimeConvertor.ToIso8601FormattedDateTime(dateTime);

                Console.WriteLine(result);
            }
コード例 #3
0
                public void ShouldReturnCorrectUnixTime()
                {
                    var dateTime = new DateTime(2012, 1, 28, 18, 14, 33, DateTimeKind.Utc);

                    var result = DateTimeConvertor.ToUnixTime(dateTime);

                    Assert.Equal(1327774473, result);
                }
コード例 #4
0
        public void ToIso8601FormattedDateTime()
        {
            var dateTime = DateTimeConvertor.FromIso8601FormattedDateTime("2011-08-04T07:00:00+0000");

            var result = DateTimeConvertor.ToIso8601FormattedDateTime(dateTime);

            Assert.Equal(result, "2011-08-04T07:00:00Z");
        }
コード例 #5
0
        public void ConvertToAndFromUnixTime_String()
        {
            var unixTimeInString = "1213513200";

            var fbUnix   = DateTimeConvertor.FromUnixTime(unixTimeInString);
            var unixTime = DateTimeConvertor.ToUnixTime(fbUnix);

            Assert.Equal(unixTimeInString, unixTime.ToString());
        }
コード例 #6
0
        public void ConvertToAndFromUnixTime_Double()
        {
            var unixTimeInDouble = 1213513200;

            var fbUnix   = DateTimeConvertor.FromUnixTime(unixTimeInDouble);
            var unixTime = DateTimeConvertor.ToUnixTime(fbUnix);

            Assert.Equal(unixTimeInDouble, unixTime);
        }
コード例 #7
0
            public void ShouldNotContainDecimal()
            {
                var dateTime = new DateTime(2012, 1, 28, 18, 14, 33, 18, DateTimeKind.Utc);

                var result = DateTimeConvertor.ToUnixTime(dateTime);

                Assert.DoesNotContain(".", result.ToString(CultureInfo.InvariantCulture));
                Assert.Equal("1327774473", result.ToString(CultureInfo.InvariantCulture));
            }
コード例 #8
0
        public void ReturnsUnixTimeEquivalent()
        {
            DateTimeOffset dateTime = new DateTimeOffset(2010, 9, 16, 0, 0, 0, TimeSpan.FromHours(-7));
            var            expected = 1284620400;

            var actual = DateTimeConvertor.ToUnixTime(dateTime);

            Assert.Equal(expected, actual);
        }
コード例 #9
0
        public void ReturnsDateTimeEquivalent()
        {
            var unixTimeinDouble = 1284620400;
            var expected         = new DateTimeOffset(2010, 9, 16, 0, 0, 0, TimeSpan.FromHours(-7));

            var actual = DateTimeConvertor.FromUnixTime(unixTimeinDouble);

            Assert.Equal(expected, actual);
        }
コード例 #10
0
ファイル: Form1.cs プロジェクト: krugerable/FacebookApi
        private void scheduleLink(string pageToken, string pageid, string link, DateTime schedule)
        {
            FacebookClient fbclient = new FacebookClient(pageToken);
            string         dts      = DateTimeConvertor.ToUnixTime(schedule).ToString();
            dynamic        parms    = new ExpandoObject();

            parms.link      = link;
            parms.published = false;
            parms.scheduled_publish_time = dts;
            fbclient.Post(pageid + "/feed", parms);
        }
コード例 #11
0
        public void FromIso8601FormattedDateTime()
        {
            var result = DateTimeConvertor.FromIso8601FormattedDateTime("2011-08-04T07:00:00+0000");

            Assert.Equal(result.Year, 2011);
            Assert.Equal(result.Month, 8);
            Assert.Equal(result.Day, 4);

            Assert.Equal(result.Hour, 7);
            Assert.Equal(result.Minute, 0);
            Assert.Equal(result.Second, 0);
        }
コード例 #12
0
                public void ShouldConvertToDateTimeCorrectly()
                {
                    var result = DateTimeConvertor.FromUnixTime("1327774473");

                    Assert.Equal(2012, result.Year);
                    Assert.Equal(1, result.Month);
                    Assert.Equal(28, result.Day);

                    Assert.Equal(18, result.Hour);
                    Assert.Equal(14, result.Minute);
                    Assert.Equal(33, result.Second);
                }
コード例 #13
0
            public void FromZ()
            {
                var result = DateTimeConvertor.FromIso8601FormattedDateTime("2012-01-28T18:14:33Z");

                Assert.Equal(2012, result.Year);
                Assert.Equal(1, result.Month);
                Assert.Equal(28, result.Day);

                Assert.Equal(18, result.Hour);
                Assert.Equal(14, result.Minute);
                Assert.Equal(33, result.Second);
            }
コード例 #14
0
        //
        // GET: /Account/OAuth/

        public ActionResult OAuth(string code, string state)
        {
            FacebookOAuthResult oauthResult;

            if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current)
                    {
                        RedirectUri = new Uri(RedirectUrl)
                    };
                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                    string  accessToken = tokenResult.access_token;

                    var expiresOn = DateTime.MaxValue;

                    if (tokenResult.ContainsKey("expires"))
                    {
                        DateTimeConvertor.FromUnixTime(tokenResult.expires);
                    }

                    var     fbClient   = new FacebookClient(accessToken);
                    dynamic me         = fbClient.Get("me?fields=id,name");
                    long    facebookId = Convert.ToInt64(me.id);

                    InMemoryUserStore.Add(new FacebookUser
                    {
                        AccessToken = accessToken,
                        Expires     = expiresOn,
                        FacebookId  = facebookId,
                        Name        = (string)me.name,
                    });

                    FormsAuthentication.SetAuthCookie(facebookId.ToString(), false);

                    // prevent open redirection attack by checking if the url is local.
                    if (Url.IsLocalUrl(state))
                    {
                        return(Redirect(state));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
コード例 #15
0
 private string CreateScheduleStatusPost(Post post, bool isPublished, DateTime scheduleTime)
 {
     try
     {
         Dictionary <string, object> parameters = new Dictionary <string, object>();
         parameters.Add("message", post.Message);
         if (!isPublished)
         {
             parameters.Add("published", "0");
             parameters.Add("scheduled_publish_time", DateTimeConvertor.ToUnixTime(DateTime.Now.AddHours(1)));
             //parameters.Add("scheduled_publish_time", DateTimeConvertor.ToUnixTime(scheduleTime));
         }
         return(postManager.CreatePost(parameters));
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
コード例 #16
0
        //
        // GET: /Account/OAuth/

        public ActionResult OAuth(string code, string state)
        {
            FacebookOAuthResult oauthResult;

            if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    string redirectUrl = "http://" + Request.Url.Host + "/Account/OAuth/";
                    var    oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
                    oAuthClient.RedirectUri = new Uri(redirectUrl);
                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                    string  accessToken = tokenResult.access_token;

                    DateTime expiresOn = DateTime.MaxValue;

                    if (tokenResult.ContainsKey("expires"))
                    {
                        DateTimeConvertor.FromUnixTime(tokenResult.expires);
                    }

                    FacebookClient fbClient   = new FacebookClient(accessToken);
                    dynamic        me         = fbClient.Get("me?fields=id,name");
                    long           facebookId = Convert.ToInt64(me.id);

                    FormsAuthentication.SetAuthCookie(facebookId.ToString(), false);

                    // prevent open redirection attack by checking if the url is local.
                    if (Url.IsLocalUrl(state))
                    {
                        return(Redirect(state));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
コード例 #17
0
ファイル: Form1.cs プロジェクト: krugerable/FacebookApi
        private void ScheduleVideo(string pageToken, string pageid, string vidPath, DateTime schedDate, string description)
        {
            FacebookClient fbclient   = new FacebookClient(pageToken);
            string         dts        = DateTimeConvertor.ToUnixTime(schedDate).ToString();
            dynamic        parameters = new ExpandoObject();

            parameters.scheduled_publish_time = dts;
            parameters.published = false;

            if (description != null)
            {
                parameters.message = description;
            }

            parameters.source = new FacebookMediaObject
            {
                ContentType = "video/" + Path.GetExtension(vidPath),
                FileName    = vidPath
            }.SetValue(File.ReadAllBytes(vidPath));


            fbclient.Post(pageid + "/videos", parameters);
        }
コード例 #18
0
        internal async static Task GetPageData(string query, int numToProcess, string userAccessToken, CancellationToken cancelToken)
        {
            int processedPostsCount = 0;

            try
            {
                do
                {
                    var fb = new FacebookClient(userAccessToken);
                    //chance to cancel before looping
                    if (cancelToken.IsCancellationRequested)
                    {
                        break;
                    }

                    // hack for Twitter-FB-IB (1 year of posts) project: query += "&since=" + MainForm.DateTimeToUnixTimestamp(new DateTime(2015,09,01));
                    dynamic postsResult = fb.Get(query);

                    //process single post
                    var data = postsResult.data;
                    if (data == null)
                    {
                        data = new JsonArray(1);
                        data.Add(postsResult);
                    }

                    //process post array
                    if (data != null && data.Count > 0)
                    {
                        var posts = (JsonArray)data;

                        int numInBatch = 0;
                        foreach (dynamic p in posts)
                        {
                            processedPostsCount++;
                            numInBatch++;

                            try
                            {
                                Post post = CreatePostFromJson(p);

                                StringBuilder sb = new StringBuilder(Environment.NewLine);
                                sb.AppendFormat("\t----- PROCESSING #{0} of {1} [batch: {2}/{3}]-----", processedPostsCount, numToProcess, numInBatch, posts.Count); sb.AppendLine();
                                sb.AppendFormat("\tfrom  : {0} (postid: {1})", post.UserName, post.PostId); sb.AppendLine();
                                sb.AppendLine("\tmsg     :" + ShortenText(post.Message));
                                sb.AppendLine("\tcreated : " + post.CreatedTime);
                                sb.AppendFormat("\tlikes : {0} || comments : {1} || shares {2}", post.NumLikes, post.NumComments, post.NumShares); sb.AppendLine();
                                sb.Append("\t-------------------------------------------------");
                                MainForm.LogOutput(sb.ToString());

                                Task <int> savePostAsyncResult = DbTasks.SavePostAsync(post);

                                // *** disable getting likes .
                                // *** 2016-11-23
                                //Task<int> likesFromPostResult = Task.Run<int>(() => ProcessLikesFromPost(post, p as object, cancelToken));
                                Task <int> commentsResult = Task.Run <int>(() => ProcessComments(post, p as object)); //not cancellable

                                #region unused
                                //int[] results = await Task.WhenAll(
                                //    DbTasks.SavePostAsync(post) //save post to db async
                                //    , Task.Run<int>(() => ProcessLikesFromPost(post, p as object, cancelToken)) //process likes async
                                //    , Task.Run<int>(() => ProcessComments(post, p as object)) //process comments async
                                //    );
                                #endregion
                                int numPosts = await savePostAsyncResult;

                                // *** disable getting likes .
                                // *** 2016-11-23
                                int numComments = await commentsResult; //when comments complete
                                if (!cancelToken.IsCancellationRequested)
                                {
                                    MainForm.UpdateCommentNext(""); //all comments were processed successfully
                                }

                                int numLikes = -1;
                                //int numLikes = await likesFromPostResult; //when likes complete
                                //if (!cancelToken.IsCancellationRequested)
                                //{
                                //    MainForm.UpdateLikeNext(""); //all likes were processed successfully
                                //}

                                MainForm.LogOutput(string.Format("#{0} ({1}-{2}) processed with {3} comments and {4} likes", processedPostsCount, post.UserName, post.PostId, numComments, numLikes));
                            }
                            catch (FacebookApiException ex)
                            {
                                if (ex is FacebookOAuthException)
                                {
                                }
                                if (ex is FacebookApiLimitException)
                                {
                                    //this has never been encounted.
                                }

                                // handle all exceptions the same way anyway :(
                                StringBuilder msg = new StringBuilder(ex.Message);
                                msg.AppendLine();

                                try
                                {
                                    var debug = AuthTasks.DebugTokenAsync(App.AppToken, userAccessToken);
                                    //{ "data": { "app_id": 138483919580948, "application": "Social Cafe", "expires_at": 1352419328, "is_valid": true, "issued_at": 1347235328, "scopes": [ "email", "publish_actions" ], "user_id": 1207059 } }

                                    bool     isValid         = debug.is_valid;
                                    DateTime expiresDateTime = DateTimeConvertor.FromUnixTime(debug.expires_at);

                                    msg.AppendFormat("UserAccessToken valid [{0}], expires at [{1}-{2}]", isValid, expiresDateTime.ToShortDateString(), expiresDateTime.ToShortTimeString());
                                    msg.AppendLine();

                                    if (debug.error != null)
                                    {
                                        var error = debug.error;
                                        msg.AppendFormat("    ERRORS: code [{0}] subcode[{1}] message [{2}]", error.code, error.subcode, error.message);
                                        msg.AppendLine();
                                    }
                                    else
                                    {
                                        msg.AppendLine("    No token errors");
                                    }
                                }
                                catch (Exception tokenDebugEx)
                                {
                                    MainForm.LogOutput("  Error trying to debug UserAccessToken: " + tokenDebugEx.Message);
                                }

                                msg.Append("Sleeping for 30 seconds then continuing");
                                MainForm.LogOutput(msg.ToString());

                                Delay(ThirtySeconds);
                            }
                        }
                    }

                    query = postsResult.paging != null ? postsResult.paging.next : null;

                    //chance to cancel after each post
                    if (cancelToken.IsCancellationRequested)
                    {
                        break;
                    }
                    if (query != null)
                    {
                        Delay(FiveSeconds);
                    }
                } while (query != null && !cancelToken.IsCancellationRequested && processedPostsCount < numToProcess);

                if (cancelToken.IsCancellationRequested)
                {
                    MainForm.LogOutput("***** CANCELLED *****");
                }
                else
                {
                    MainForm.LogOutput(processedPostsCount + " posts processed. No more posts left");
                }
            }
            catch (Exception ex)
            {
                MainForm.LogOutput(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }
コード例 #19
0
        //
        // GET: /Account/OAuth/

        public ActionResult OAuth(string code, string state)
        {
            FacebookOAuthResult oauthResult;

            if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
                    oAuthClient.RedirectUri = new Uri(redirectUrl);

                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                    string  accessToken = tokenResult.access_token;

                    DateTime expiresOn = DateTime.MaxValue;

                    if (tokenResult.ContainsKey("expires"))
                    {
                        DateTimeConvertor.FromUnixTime(tokenResult.expires);
                    }

                    FacebookClient fbClient   = new FacebookClient(accessToken);
                    dynamic        me         = fbClient.Get("me?fields=id,name,email,birthday,gender");
                    long           facebookId = Convert.ToInt64(me.id);

                    InMemoryUserStore.Add(new FacebookUser
                    {
                        AccessToken = accessToken,
                        Expires     = expiresOn,
                        FacebookId  = facebookId,
                        Name        = (string)me.name,
                    });

                    var user = Membership.GetUser(facebookId.ToString());

                    FormsAuthentication.SetAuthCookie(facebookId.ToString(), false);

                    string      format   = "d";
                    CultureInfo provider = CultureInfo.InvariantCulture;
                    DateTime    birthday = new DateTime();
                    try
                    {
                        birthday = DateTime.ParseExact(me.birthday, format, provider);
                    }
                    catch
                    {
                    }

                    if (user == null)
                    {
                        var u = Membership.CreateUser(facebookId.ToString(), Guid.NewGuid().ToString());
                        using (BestPlaceEntities db = new BestPlaceEntities())
                        {
                            db.bp_Profile_Create((Guid)u.ProviderUserKey,
                                                 facebookId.ToString(),
                                                 (string)me.name,
                                                 Transfer.GetPictureUrl(facebookId.ToString()),
                                                 (string)me.email,
                                                 null,
                                                 birthday,
                                                 ((string)me.gender == "male") ? true : false,
                                                 null, null);
                        }
                    }
                    else
                    {
                        using (BestPlaceEntities db = new BestPlaceEntities())
                        {
                            db.bp_Profile_Update((Guid)user.ProviderUserKey,
                                                 (string)me.name,
                                                 (string)me.email,
                                                 null,
                                                 birthday,
                                                 ((string)me.gender == "male") ? true : false,
                                                 null, null);
                        }
                    }

                    // prevent open redirection attack by checking if the url is local.
                    if (Url.IsLocalUrl(state))
                    {
                        return(Redirect(state));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
コード例 #20
0
 public void GivenEmptyThrowsArgumnetNullException()
 {
     Assert.Throws <ArgumentNullException>(() => DateTimeConvertor.FromIso8601FormattedDateTime(string.Empty));
 }
コード例 #21
0
 public void GivenNullThrowsArgumentNullException()
 {
     Assert.Throws <ArgumentNullException>(() => DateTimeConvertor.FromIso8601FormattedDateTime(null));
 }
コード例 #22
0
 private void _Build(DateTime dateTime)
 {
     sb.AppendFormat("'{0}' ", DateTimeConvertor.ToUnixTime(dateTime));
 }