Hi! I created a stream and besides the text of a tweet, I want to get the coordinates.

Feb 16, 2015 at 11:46 PM
Hello!


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tweetinvi;
using TwitterStream;


namespace TwitterStream
{
class Program
{

    static void Main(string[] args)
    {
        TwitterCredentials.SetCredentials(...);

        TwitterStream();
        Console.ReadLine();

    }

    private static void TwitterStream()
    {

        var stream = Stream.CreateSampleStream();
        stream.TweetReceived += (sender, args) =>
        {
            Console.WriteLine(args.Tweet.Coordinates.Latitude);
        };

        stream.StartStream();
    }


}
}

If I try to get only the text, it works fine, but if I want the location, it throws me an exception: "An exception of type 'System.NullReferenceException' occurred in TwitterStream.exe but was not handled in user code".

Any help would be appreciated.

Thanks!
Feb 17, 2015 at 3:43 PM
Edited Feb 17, 2015 at 3:45 PM
Hello,

The coordinates are not always available in a Tweet.
Lots of users decide to not publish their coordinates as part of their public tweets.

Therefore you need to always check if the Coordinates property of a tweet is not null.
private static void TwitterStream()
{
    var stream = Stream.CreateSampleStream();

    stream.TweetReceived += (sender, args) =>
    {
        var tweet = args.Tweet;
                
        var hasUserPublishedWithLocation = tweet.Coordinates != null;
        if (hasUserPublishedWithLocation)
        {
            Console.WriteLine(tweet.Coordinates.Latitude);
        }
    };
            
    stream.StartStream();
}
Linvi
Marked as answer by linvi on 2/17/2015 at 7:43 AM
Feb 17, 2015 at 4:31 PM
Hi!

Thanks for the reply. After I submitted the post, I did just what you suggested and it worked.

I don't know if you are familiar with the SignalR framework, but I want to have the stream in a SignalR Hub class and to pass the tweets to JavaScript and, say make an alert on the webpage. I am experiencing some difficulties, mainly because I am not so familiar with anonymous functions in C#.
    public void TwitterStream()
    {
        TwitterCredentials.SetCredentials(...)
        var stream = Stream.CreateSampleStream();
        stream.TweetReceived += (sender, args) =>
        {
            Clients.All.alert(args.Tweet.Text);

        };

        stream.StartStream();
    }
Now, the alert function that is called is implemented in the JavaScript code.
Note that if I change the function so that it only passes a static message to the alert function, it will work.

Thanks!