Search code examples
c#asp.nettweetstweetsharp

how to get all tweets on hashtag using Tweetsharp


How can I get all tweets on behalf of specific hashtag/keyword and display it on View page? The only solution found returns a null exception.

public ActionResult TweetView(string txtTwitterName)
{
    //TwitterService("consumer key", "consumer secret");
    var service = new TwitterService("", "");

    //AuthenticateWith("Access Token", "AccessTokenSecret");
    service.AuthenticateWith("", "");

    TwitterSearchResult tweets = service.Search(new SearchOptions { Q = txtTwitterName, SinceId=29999 });
    IEnumerable<TwitterStatus> status = tweets.Statuses;
    ViewBag.Tweets = tweets;

    return View();
}

View :

IEnumerable<TwitterStatus> tweets = ViewBag.Tweets as IEnumerable<TwitterStatus>;
foreach (var tweet in tweets)
{
    <div class="tweet">
        <div class="picture">
            <img src="@tweet.User.ProfileImageUrl" alt="@tweet.User.ScreenName" title="@tweet.User.ScreenName" />
        </div>
        <div class="info">
            <span>@tweet.User.Name, @tweet.User.Description - @tweet.User.Location </span>
            <br />
            <a href="https://twitter.com/statuses/@tweet.Id" class="text">
                @tweet.Text
            </a>
            <div class="action">
                @tweet.CreatedDate.AddHours(3).ToString("d/M/yyyy HH:mm:ss")
            </div>
        </div>
        <div class="clear">

        </div>

    </div>
}

Solution

  • for the null value, in your view :

    IEnumerable<TwitterStatus> status = ViewBag.Tweets as IEnumerable<TwitterStatus>;
    if(status != null )
    {
        foreach (var tweet in status)
        {
            <div class="tweet">
                <div class="picture">
                    <img src="@tweet.User.ProfileImageUrl" alt="@tweet.User.ScreenName"     
                     title="@tweet.User.ScreenName" />
                </div>
                <div class="info">
                    <span>@tweet.User.Name, @tweet.User.Description - @tweet.User.Location </span>
                    <br />
                        <a href="https://twitter.com/statuses/@tweet.Id" class="text">
                    @tweet.Text
                    </a>
                    <div class="action">
                        @tweet.CreatedDate.AddHours(3).ToString("d/M/yyyy HH:mm:ss")
                    </div>
                    </div>
                <div class="clear">
    
                </div>
    
            </div>
       }
    }
    

    and for your Controller, modify the last code by :

    ViewBag.Tweets = status;
    

    I hope this post will help, thx :)