private string GetTimelineData(HttpContext context)
        {
            try
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();

                TimelineParams inputParams = new TimelineParams();

                if (context.Request.Params["inputParameters"] != null)
                {
                    string jsonInput = HttpUtility.HtmlDecode(context.Request.Params["inputParameters"]);
                    inputParams = serializer.Deserialize<TimelineParams>(jsonInput);
                }

                if (string.IsNullOrEmpty(inputParams.ListName))
                    return serializer.Serialize(TimelineHelper.GetUserTimeline(inputParams));
                else
                    return serializer.Serialize(TimelineHelper.GetList(inputParams));
            }
            catch(Exception ex)
            {
                context.Response.StatusCode = 500;
                return string.Format("Error retrieving timeline: '{0}'", ex.Message);
            }

        }
Ejemplo n.º 2
0
        internal static string BuildAsyncTimelineOutput(TimelineParams inputParams, string CssClass)
        {
            string asyncBaseHtml = ResourceHelper.Includes(null, "async-base.html");
            
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            asyncBaseHtml = string.Format(asyncBaseHtml, VirtualPathUtility.ToAbsolute(ConfigHelper.GetAppSettingString(ConfigKey.HandlerPath, Constants.Configuration.HandlerPath)), serializer.Serialize(inputParams), CssClass);

            return asyncBaseHtml;
        }
Ejemplo n.º 3
0
        internal static string RenderTimelineIncludes(TimelineParams inputParams, string CssClass = "tweet-container", bool isAsync = false)
        {

            RoutingHelper.RegisterRoutes();

            if (isAsync)
                return BuildAsyncTimelineOutput(inputParams, CssClass);
            else
                return BuildTimelineOutput(inputParams, CssClass);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Public method to build timeline output to be consumed by page.
        /// </summary>
        /// <param name="tweetCount"></param>
        /// <param name="showReplies"></param>
        /// <param name="includeRetweets"></param>
        /// <param name="screenName"></param>
        /// <param name="listName"></param>
        /// <param name="CssClass"></param>
        /// <param name="isAsync"></param>
        /// <returns>A string containing the html to output to the page</returns>
        public static string RenderTimelineIncludes(int tweetCount, bool showReplies, bool includeRetweets, string screenName = null, string listName = null, string CssClass = "tweet-container", bool isAsync = false)
        {

            TimelineParams inputParams = new TimelineParams();
            inputParams.TweetCount = tweetCount;
            inputParams.ShowReplies = showReplies;
            inputParams.ScreenName = screenName;
            inputParams.ListName = listName;
            inputParams.IncludeRetweets = includeRetweets;

            return RenderTimelineIncludes(inputParams, CssClass, isAsync);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Gets a timeline collection based on the supplied parameters and builds the html for output
        /// </summary>
        /// <param name="tweetCount"></param>
        /// <param name="showReplies"></param>
        /// <param name="screenName"></param>
        /// <param name="CssClass"></param>
        /// <returns></returns>
        public static string BuildTimelineOutput(TimelineParams inputParams, string CssClass = "tweet-container")
        {

            //string htmlBase = ResourceHelper.Includes(null, "tweet-layout.html");
            //Regex placeHolderExp = new Regex(@"(?<=\{)[\w\.]+(:\w+)?(?=\})");
            
            StringBuilder tweetBuilder = new StringBuilder();

            try
            {

                tweetBuilder.AppendLine(string.Format("<div class='{0}'>", CssClass));
                tweetBuilder.AppendLine("<ul>");

                List<Status> tweets;

                if (string.IsNullOrEmpty(inputParams.ListName))
                    tweets = TimelineHelper.GetUserTimeline(inputParams);
                else
                    tweets = TimelineHelper.GetList(inputParams);


                if (tweets != null && tweets.Count > 0)
                {
                    foreach (Status tweet in tweets)
                    {
                        DateTime tweetCreated = tweet.CreatedAt.ToLocalTime();

                        //string tweetOutput = htmlBase;
                        //Match match = placeHolderExp.Match(tweetOutput);
                        //while (match != null)
                        //{
                        //    MapTweetToHtml(tweet, tweetOutput, match.Value);
                        //    match = match.NextMatch();
                        //}

                        tweetBuilder.AppendLine("<li>");
                        tweetBuilder.AppendLine("<div class='user-container'>");
                        tweetBuilder.AppendLine(string.Format("<a class='user-link' href='{0}{1}' target='_blank'>", Constants.Configuration.TwitterUrl, tweet.User.Identifier.ScreenName));
                        tweetBuilder.AppendLine(string.Format("<img class='user-image' src='{0}' />", tweet.User.ProfileImageUrl));
                        tweetBuilder.AppendLine("</a>");
                        tweetBuilder.AppendLine("</div>");
                        tweetBuilder.AppendLine("<div class='tweet-container'>");
                        tweetBuilder.AppendLine(string.Format("<a class='tweet-screenName' href='{0}{1}' target='_blank'>{1}</a>", Constants.Configuration.TwitterUrl, tweet.User.Identifier.ScreenName));
                        tweetBuilder.AppendLine(string.Format("<p class='tweet-content'>{0}</p>", ParseTweetText(tweet.Text)));
                        tweetBuilder.AppendLine(string.Format("<span class='tweet-date'>{0}</span>", tweetCreated.ToString("dd MMM yyyy")));
                        tweetBuilder.AppendLine(string.Format("<span class='tweet-time'>{0}</span>", tweetCreated.ToString("hh:mm:ss")));
                        tweetBuilder.AppendLine(string.Format("<span class='tweet-time-passed'>{0}</span>", GetTimePassed(tweetCreated)));
                        tweetBuilder.AppendLine("</div>");
                        tweetBuilder.AppendLine("</li>");
                    }
                }

                tweetBuilder.AppendLine("</ul>");
                tweetBuilder.AppendLine("</div>");
            
            }
            catch
            {
                return "<p class='service-error'>Unable to contact twitter service.</p>";
            }

            return tweetBuilder.ToString();

        }
Ejemplo n.º 6
0
 /// <summary>
 /// Builds a parameter string to use as part of the cache key
 /// </summary>
 /// <returns></returns>
 private static string BuildParamString(TimelineParams inputParams)
 {
     return string.Format("TweetCount={0}&ShowReplies={1}&ScreenName={2}&IncludeRetweets={3}&ListName={4}", inputParams.TweetCount, inputParams.ShowReplies, inputParams.ScreenName, inputParams.IncludeRetweets, inputParams.ListName);
 }
Ejemplo n.º 7
0
        /// <summary>
        /// calls the twitter api to get timeline results for a user
        /// </summary>
        /// <returns></returns>
        public static List<Status> GetUserTimeline(TimelineParams inputParams)
        {
            // check the cache for existing data
            List<Status> tweets = (List<Status>)CacheHelper.GetFromCache(CacheKey.UserTimeline, BuildParamString(inputParams));
            if (tweets == null)
            {
                tweets = new List<Status>();

                ulong lastTweetId = 0;
                string searchScreenName;

                // a valid context
                TwitterContext context = ContextHelper.GetContext();

                // if a screen name has not been provided then get the current users screen name and last tweet id
                if (string.IsNullOrEmpty(inputParams.ScreenName))
                {
                    User authenticatedUser = ContextHelper.GetAuthenticatedUser();
                    searchScreenName = authenticatedUser.Identifier.ScreenName;

                    if (authenticatedUser.Status != null)
                        lastTweetId = ulong.Parse(authenticatedUser.Status.StatusID);
                }
                // if a screen name has been provided then get the user and store thier last tweet id
                else
                {
                    searchScreenName = inputParams.ScreenName;

                    var users = from u in context.User
                                where u.Type == UserType.Show
                                    && u.ScreenName == inputParams.ScreenName
                                select u;

                    User user = users.SingleOrDefault();
                    lastTweetId = ulong.Parse(user.Status.StatusID);
                }

                try
                {
                    // Here it is necesary to get the tweets in chunks and add the results to the tweets list
                    // as the number of results returned from the api call is effectively up to the count supplied
                    // due to limitations in the twitter REST api

                    //set a max loops value as a backup
                    int maxloops = 5, count = 0;

                    while (tweets.Count < inputParams.TweetCount && count < maxloops)
                    {
                        //increment the count
                        count++;

                        List<Status> chunkList;

                        chunkList = (from tweet in context.Status
                                     where tweet.Type == StatusType.User
                                         && tweet.ExcludeReplies == !inputParams.ShowReplies
                                         && tweet.IncludeRetweets == inputParams.IncludeRetweets
                                         && tweet.Count == inputParams.TweetCount
                                         && tweet.ScreenName == searchScreenName
                                         && tweet.MaxID == lastTweetId
                                     orderby tweet.CreatedAt descending
                                     select tweet).ToList();

                        // add the chunk items into the tweet list
                        foreach (Status tweet in chunkList)
                        {
                            if (tweets.Count < inputParams.TweetCount)
                            {
                                tweets.Add(tweet);
                            }
                        }

                        // store the last tweet recieved so we dont get the same ones next loop (-1 to prevent re-retrieving the last tweet)
                        if (tweets.Count > 0)
                            lastTweetId = ulong.Parse(chunkList[chunkList.Count - 1].StatusID) - 1;
                    }

                    CacheHelper.AddToCache(tweets, ConfigHelper.GetAppSetting<int>(ConfigKey.TwitterCacheDuration, 20), CacheKey.UserTimeline, BuildParamString(inputParams));

                }
                catch (TwitterQueryException ex)
                {

                }
            }

            return tweets;
        }
Ejemplo n.º 8
0
        /// <summary>
        /// calls the twitter api to get tweets form a list
        /// </summary>
        /// <returns></returns>
        public static List<Status> GetList(TimelineParams inputParams)
        {
            // check the cache for existing data
            List<Status> tweets = (List<Status>)CacheHelper.GetFromCache(CacheKey.UserTimeline, BuildParamString(inputParams));
            if (tweets == null)
            {
                tweets = new List<Status>();

                string searchScreenName = inputParams.ScreenName;
                ulong lastTweetId = 0;

                // a valid context
                TwitterContext context = ContextHelper.GetContext();

                // if a screen name has not been provided then get the current users screen name
                if (string.IsNullOrEmpty(inputParams.ScreenName))
                {
                    User authenticatedUser = ContextHelper.GetAuthenticatedUser();
                    searchScreenName = authenticatedUser.Identifier.ScreenName;
                }
                
                try
                {
                    // Here it is necesary to get the tweets in chunks and add the results to the tweets list
                    // as the number of results returned from the api call is effectively up to the count supplied
                    // due to limitations in the twitter REST api

                    //set a max loops value as a backup
                    int maxloops = 5, count = 0;

                    while (tweets.Count < inputParams.TweetCount && count < maxloops)
                    {
                        //increment the count
                        count++;

                        List<Status> chunkList;

                        if (lastTweetId == 0)
                        {

                            chunkList = (from list in context.List
                                         where list.Type == ListType.Statuses
                                             && list.OwnerScreenName == searchScreenName
                                             && list.Slug == inputParams.ListName // name of list to get statuses for
                                             && list.Count == inputParams.TweetCount
                                         select list)
                                         .First().Statuses;
                        }
                        else
                        {
                            chunkList = (from list in context.List
                                              where list.Type == ListType.Statuses
                                                  && list.OwnerScreenName == searchScreenName
                                                  && list.Slug == inputParams.ListName // name of list to get statuses for
                                             && list.Count == inputParams.TweetCount
                                                  && list.MaxID == lastTweetId
                                              select list)
                                         .First().Statuses;
                        }
                        // add the chunk items into the tweet list
                        foreach (Status tweet in chunkList)
                        {
                            if (tweets.Count < inputParams.TweetCount && (inputParams.IncludeRetweets || (tweet.RetweetedStatus == null || tweet.RetweetedStatus.User == null)))
                            {
                                tweets.Add(tweet);
                            }
                        }

                        // store the last tweet recieved so we dont get the same ones next loop (-1 to prevent re-retrieving the last tweet)
                        if (tweets.Count > 0)
                            lastTweetId = ulong.Parse(chunkList[chunkList.Count - 1].StatusID) - 1;
                    }

                    CacheHelper.AddToCache(tweets, ConfigHelper.GetAppSetting<int>(ConfigKey.TwitterCacheDuration, 20), CacheKey.UserTimeline, BuildParamString(inputParams));

                }
                catch (TwitterQueryException ex)
                {

                }
            }

            return tweets;
        }
Ejemplo n.º 9
0
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            TimelineParams inputParams = new TimelineParams();
            inputParams.TweetCount = TweetCount;
            inputParams.ShowReplies = ShowReplies;
            inputParams.ScreenName = ScreenName;
            inputParams.IncludeRetweets = ShowRetweets;
            inputParams.ListName = ListName;

            writer.Write(HtmlHelper.RenderTimelineIncludes(inputParams, CssClass, IsAsync));
        }