1

I am trying to fetch tweets using the example on GitHub, but I get an error "The underlying connection was closed: An unexpected error occurred in a submission". I can not understand. At first, I created the application on Twitter and took the keys generated by Twitter and added it to the application. I had doubts about 2 attributes that I don't know what they will be used for, and I don't know if they are causing problems:

1 - Website URL - I created a website on Wix to fill this field, but I didn't understand its use, since I just want to read tweets in a desktop application.

2 - Callback URL - Initially I didn't put anything, then I saw in a post that it was to put http://127.0.0.1/ I ran the application with this information, but again I don't know what it is for, because I'm going to get tweets from a desktop application .

Here are the code used and the error received!


using System;
using System.Linq;
using System.Threading.Tasks;
using LinqToTwitter;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main()
        {        
            MainAsync().Wait();
        }
        static async Task MainAsync()
        {
            var auth = new SingleUserAuthorizer
            {

                CredentialStore = new InMemoryCredentialStore()
                {
                    ConsumerKey = "MyConsumerKey",
                    ConsumerSecret = "MyConsumerSecret",
                    OAuthToken = "MYOAuthToken",
                    OAuthTokenSecret = "MYOAuthTokenSecret"
                }
            };
            var twitterCtx = new TwitterContext(auth);

            var searchResponse = await (from search in twitterCtx.Search
                                        where search.Type == SearchType.Search 
                                        &&  search.Query == "flamengo"
                                        select search).SingleOrDefaultAsync();

            if (searchResponse != null && searchResponse.Statuses != null)
                searchResponse.Statuses.ForEach(tweet =>
                    Console.WriteLine(
                        "User: {0}, Tweet: {1}",
                        tweet.User.ScreenNameResponse,
                        tweet.Text));
        }
    }
}


System.AggregateException was unhandled
  HResult=-2146233088
  Message=Um ou mais erros.
  Source=mscorlib
  StackTrace:
       em System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
       em System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
       em System.Threading.Tasks.Task.Wait()
       em ConsoleApplication3.Program.Main() na C:\Danilo\Docs\Visual Studio 2015\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs:linha 12
       em System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       em System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       em Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       em System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       em System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       em System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
       HResult=-2146233088
       Message=Ocorreu um erro ao enviar a solicitação.
       Source=mscorlib
       StackTrace:
            em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            em LinqToTwitter.Net.GetMessageHandler.<SendAsync>d__4.MoveNext()
         --- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---
            em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            em LinqToTwitter.TwitterExecute.<QueryTwitterAsync>d__48 1.MoveNext()
         --- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---
            em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            em LinqToTwitter.TwitterContext.<ExecuteAsync>d__136 1.MoveNext()
         --- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---
            em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            em LinqToTwitter.TwitterQueryProvider.<ExecuteAsync>d__8 1.MoveNext()
         --- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---
            em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            em LinqToTwitter.TwitterExtensions.<SingleOrDefaultAsync>d__5 1.MoveNext()
         --- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---
            em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            em System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
            em ConsoleApplication3.Program.<MainAsync>d__1.MoveNext() na C:\Danilo\Docs\Visual Studio 2015\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs:linha 29
       InnerException: 
            HResult=-2146233079
            Message=A conexão subjacente estava fechada: Erro inesperado em um envio.
            Source=System
            StackTrace:
                 em System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
                 em System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
            InnerException: 
                 HResult=-2146232800
                 Message=Não é possível ler os dados da conexão de transporte: Foi forçado o cancelamento de uma conexão existente pelo host remoto.
                 Source=System
                 StackTrace:
                      em System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
                      em System.Net.PooledStream.EndWrite(IAsyncResult asyncResult)
                      em System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
                 InnerException: 
                      ErrorCode=10054
                      HResult=-2147467259
                      Message=Foi forçado o cancelamento de uma conexão existente pelo host remoto
                      NativeErrorCode=10054
                      Source=System
                      StackTrace:
                           em System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
                           em System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
                      InnerException:

DaniloPF
  • 67
  • 7
  • 2
    Your code is working for me and I can't reproduce the problem. Looking at the innermost exception, I did see an error code #10054 - might indicate that it has something to do with your network. Your callback URL matches mine. My app permissions are set to Read, Write, and DM, though I don't think that matters for a Search. Maybe try doing a raw .NET HttpClient request to the RequestToken endpoint (https://developer.twitter.com/en/docs/basics/authentication/api-reference/request_token) and see if you get the same error. – Joe Mayo Mar 25 '20 at 02:19
  • Thanks, I changed the permissions, because I was not with DM permission, now it is Read, write, and Direct Messages I tested it again, doing the debug, and the same problem happened. If I understood correctly, after I run var auth = new SingleUserAuthorizer {...}, I would already have an authorization or not from twitter to do the research, correct? Is there any place where I can look at the auth variable or twitterCtx where I can make sure that the authorization is ok? The error only occurs at the time of the search, but I don't know if it comes from a previous non-authorization. – DaniloPF Mar 25 '20 at 14:15
  • About the suggestion to make a gross .NET HttpClient request to the RequestToken endpoint, according to the link you sent me, I started reading, but I confess that I have no basis to understand at this point, I think I will have to study hard and calmly, to make sure I am doing the correct access, so I looked for a solution that encapsulated these processes. But I will study. – DaniloPF Mar 25 '20 at 14:15
  • About the suggestion of being a network, it is possible, but the network works for all the applications I use, I thought of testing it on another network, but because of the quarantine here in Brazil, I cannot leave now, I must test it later. I read a little about the code 10054, and I saw that in some posts they mentioned the antivirus as being a problem. Can be? I use avast! – DaniloPF Mar 25 '20 at 14:16
  • 1
    You can use Fiddler to watch the traffic and see which call is returning the error. My thinking was that it might be some issue with communicating with Twitter and it might be interesting to see if *any* HTTP call to the Twitter API would work. If you suspect a problem with the anti-virus, you could find out by turning the anti-virus off and run the code again. – Joe Mayo Mar 25 '20 at 15:24
  • I disabled the antivirus and the problem remained. If I understood correctly, after I run var auth = new SingleUserAuthorizer {...}, I would already have an authorization or not from twitter to do the research, correct? Is there any variable where I can look at the auth variable or twitterCtx where I can make sure that the authorization is ok? The error only occurs at the time of the search, but I don't know if it comes from a previous non-authorization. – DaniloPF Mar 25 '20 at 15:47
  • 1
    You can use Fiddler (https://www.telerik.com/fiddler) it's a free download and lets you watch HTTP traffic. It might give more details on what the problem is. – Joe Mayo Mar 25 '20 at 16:12
  • Thanks! I downloaded the software, but I couldn't understand the traffic and I didn't understand what was going on, in fact I don't even know what to look for there. But I couldn't identify anything that could clarify the problem! I will try to run on another network, in due course. But I was wondering if the access authorization for the app created on twitter worked, I am suspicious of this authorization. – DaniloPF Mar 25 '20 at 19:20
  • 1
    Right - authorization is often the 1st hurdle, which is why the 401 part of the FAQ is so long. Most of the requests are from tracking traffic in your browser and/or apps. You can minimize Fiddler traffic by closing browsers or anything else that might be accessing the Internet. – Joe Mayo Mar 25 '20 at 21:06
  • I decided to test the program on another computer, on the same network. All tests were done using VisualStudio 2015 debugging. The problem occurred on both computers. I decided to make a build (it was an insight!) And ran the executable program! Surprise! It worked on the second computer. I brought the executable for the first one and it worked too! I did the same build process on the first computer and it also worked. I managed to retrieve the tweets. Now, I need to understand why with Debug it gives the network error and with the executable it works well, but linqToTwitter worked fine! – DaniloPF Mar 26 '20 at 15:50
  • So glad to hear you've made progress! – Joe Mayo Mar 26 '20 at 18:04

1 Answers1

1

This looks similar to the question we resolved here, where the problem was needing to set to TLS 1.2 because it was an older .NET version:

Visual Studio 2015 - Debug with HTTP connection problems

Joe Mayo
  • 7,501
  • 7
  • 41
  • 60