0
votes

I am trying to call Streaming API filter inside my .net webpage.

I did create an app on twitter and took the credentials needed(consumer key,consumer secret,access token and access token secret)

This is the code am using

 Public Function StreamAPI()
    Dim url As String = "https://stream.twitter.com/1.1/statuses/filter.json?track=example.com/example"


    Dim oauthconsumerkey As String = "consumerkey"
    Dim oauthconsumersecret As String = "consumersecret"
    Dim oauthsignaturemethod As String = "HMAC-SHA1"
    Dim oauthversion As String = "1.0"
    Dim oauthtoken As String = "token"
    Dim oauthtokensecret As String = "tokenkey"

    Dim oauthnonce As String = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
    Dim timeSpan As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, _
        0, DateTimeKind.Utc)
    Dim oauthtimestamp As String = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
    Dim basestringParameters As New SortedDictionary(Of String, String)()
    basestringParameters.Add("track", "example.com/example")
    basestringParameters.Add("oauth_version", oauthversion)
    basestringParameters.Add("oauth_consumer_key", oauthconsumerkey)
    basestringParameters.Add("oauth_nonce", oauthnonce)
    basestringParameters.Add("oauth_signature_method", oauthsignaturemethod)
    basestringParameters.Add("oauth_timestamp", oauthtimestamp)
    basestringParameters.Add("oauth_token", oauthtoken)

    Dim baseString As New StringBuilder()
    baseString.Append("GET" + "&")
    baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split("?"c)(0)) + "&"))
    For Each entry As KeyValuePair(Of String, String) In basestringParameters
        baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")))
    Next


    Dim finalBaseString As String = baseString.ToString().Substring(0, baseString.Length - 3)


    Dim signingKey As String = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" + EncodeCharacters(Uri.EscapeDataString(oauthtokensecret))

    'Sign the request
    Dim hasher As New HMACSHA1(New ASCIIEncoding().GetBytes(signingKey))
    Dim oauthsignature As String = Convert.ToBase64String(hasher.ComputeHash(New ASCIIEncoding().GetBytes(finalBaseString)))


    Dim webRequest__1 As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
    Dim authorizationHeaderParams As New StringBuilder()
    authorizationHeaderParams.Append("OAuth ")
    authorizationHeaderParams.Append("oauth_nonce=" + """" + Uri.EscapeDataString(oauthnonce) + """,")
    authorizationHeaderParams.Append("oauth_signature_method=" + """" + Uri.EscapeDataString(oauthsignaturemethod) + """,")
    authorizationHeaderParams.Append("oauth_timestamp=" + """" + Uri.EscapeDataString(oauthtimestamp) + """,")
    authorizationHeaderParams.Append("oauth_consumer_key=" + """" + Uri.EscapeDataString(oauthconsumerkey) + """,")
    If Not String.IsNullOrEmpty(oauthtoken) Then
        authorizationHeaderParams.Append("oauth_token=" + """" + Uri.EscapeDataString(oauthtoken) + """,")
    End If
    authorizationHeaderParams.Append("oauth_signature=" + """" + Uri.EscapeDataString(oauthsignature) + """,")
    authorizationHeaderParams.Append("oauth_version=" + """" + Uri.EscapeDataString(oauthversion) + """")
    webRequest__1.Headers.Add("Authorization", authorizationHeaderParams.ToString)

    webRequest__1.Method = "GET"
    webRequest__1.ContentType = "application/x-www-form-urlencoded"

    webRequest__1.Timeout = 3 * 60 * 1000
    Try

        Dim webResponse As HttpWebResponse = TryCast(webRequest__1.GetResponse(), HttpWebResponse)

        Dim dataStream As System.IO.Stream = webResponse.GetResponseStream()
        ' Open the stream using a StreamReader for easy access.
        Dim reader As New StreamReader(dataStream)
        ' Read the content.
        Dim responseFromServer As String
        responseFromServer = reader.ReadToEnd()
        Return responseFromServer
    Catch ex As Exception
    End Try

End Function

The function doesnt return anything. At row containingreader.ReadToEnd() in debug mode it is showing "Unable to evaluate expression".

The same code works correctly if the url is in this format https://api.twitter.com/1.1/application/rate_limit_status.json or https://api.twitter.com/1.1/search/tweets.json?q=example

Any reason why it doesn't work for stream apis? I cant use search api since it doesn't return all results I need, for example tweets containing urls are not returned by search api.

I did try tweetinvi library for .net projects as suggested by twitter website.

Public Sub Twit()
    Dim oauthconsumerkey As String = "consumerkey"
    Dim oauthconsumersecret As String = "consumersecret"
    Dim oauthsignaturemethod As String = "HMAC-SHA1"
    Dim oauthversion As String = "1.0"
    Dim oauthtoken As String = "token"
    Dim oauthtokensecret As String = "tokensecret"

    Auth.SetUserCredentials(oauthconsumerkey, oauthconsumersecret, oauthtoken, oauthtokensecret)
    Auth.ApplicationCredentials = New TwitterCredentials(oauthconsumerkey, oauthconsumersecret, oauthtoken, oauthtokensecret)

    Dim filteredStream = Tweetinvi.Stream.CreateFilteredStream()
    filteredStream.AddTrack("example")
    Dim txt As String = ""


    AddHandler filteredStream.MatchingTweetReceived, Sub(sender As Object, args As Tweetinvi.Core.Events.EventArguments.MatchedTweetReceivedEventArgs)
                                                         Console.WriteLine(args.Tweet.Text)
                                                         txt &= args.Tweet.Text
                                                     End Sub

    filteredStream.StartStreamMatchingAllConditions()

End Sub

But this is not returning anything. The event is not getting called and i am not getting any result.

Both methods failed.Is there any other clear example that I can use to call statuses/filter from vb.net webpages?

1

1 Answers

0
votes

I am the developer of Tweetinvi.

Your code looks correct. Would you please let me know what exception you receive.

Also, I am not sure to understand if this code is invoked directly in the page (I am not familiar with WebForms), but please not that StartStreamMatchingAllConditions will be blocking the Thread it runs in until the stream stop.

If you want this to be running behind the scene you will want to use the async version : StartStreamMatchingAllConditionsAsync().

Finally, the way I send stream tweets to a UI is by using WebSocket and send information from the server to a javascript handler.