Domanda Cast specificato non valido utilizzando il controllo WebBrowser

Matty80

Utente Bronze
18 Settembre 2020
45
11
0
25
Ultima modifica:
Ciao, sto usando il pacchetto Telegram.bot da nuget e ricevo l'ultimo messaggio dal client. Con quest'ultimo, sto impostando l'attributo di una casella di testo su una pagina Web by WebBrowser.
Il codice che sto usando è:

Codice:
Private Sub InsertLink(link as string)
 
         MsgBox(link)
 
         WebBrowser1.Document.GetElementById("video_url").SetAttribute("value", link)
          WebBrowser1.Document.GetElementById("submitButton").InvokeMember("click")
          Catch ex As Exception
          MsgBox(ex.Message)
         End Try
     End Sub
 
     Private Sub form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
         Dim botid As String = "my bot api"
         Dim bot As New TelegramBotClient(botid)
 
         Dim cts = New CancellationTokenSource()
         Dim options = New ReceiverOptions With {
             .AllowedUpdates = Array.Empty(Of UpdateType)()
         }
         bot.StartReceiving(updateHandler:=AddressOf HandleUpdateAsync, errorHandler:=AddressOf HandleErrorAsync, options, cts.Token)
         Console.ReadLine()
     End Sub
     Public link As String
 
     Private Async Function HandleUpdateAsync(botClient As ITelegramBotClient,
                                         update As Update,
                                         cancellationToken As CancellationToken) As Task
 
         Try
             If update.Message IsNot Nothing Then
 
                 link = update.Message.text
                 InsertLink(link)
           
 
             End If
         Catch ex As Exception
             MsgBox(ex.Message)
         End Try
     End Function
 
     Private Function HandleErrorAsync(botClient As ITelegramBotClient,
                                 exception As Exception,
                                 cancellationToken As CancellationToken) As Task
         Console.WriteLine(exception)
         Return Task.CompletedTask
 
     End Function
 End Class

Il problema si presenta quando devo passare la variabile link al Private Sub InsertLink, poiché suppongo che HandleUpdateAsync sta operando in un thread separato, quindi ricevo l'errore Il cast specificato non è valido sull'ex.message di InsertLink. Come posso evitare in questo caso il cross thread e passargli correttamente la Stringa variabille Link ? Inoltre, potete indicarmi come eseguire correttamente L'await del metodo asincrono in HandleUpdateAsync() - e delgestore degli errori, HandleErrorAsync()?

L'intero codice di per se riceve correttamente il messaggio da telegram. Semplicemente passa la variabile Link di tipo String da Function HandleUpdateAsync alla Private Sub InsertLink.
Usando BreakPoints noto che Ricevo il messaggio dal client in un formato stringa e lo passo al sub privato InsertLink in un formato stringa e successivamente lo sto passando al browser web, ecco perché non capisco l'errore di cast.
Guarda la gif, il testo viene ricevuto e passato attraverso ogni passaggio, quindi non capisco il non funzionamento.. grazie
Collegamento GIF

StackTrace
Codice:
Exception thrown: 'System.InvalidCastException' in System.Windows.Forms.dll
System.InvalidCastException: Cast specificato non valido.
   in System.Windows.Forms.UnsafeNativeMethods.IHTMLDocument2.GetLocation()
   in System.Windows.Forms.WebBrowser.get_Document()
   in YoutubeToMp3.form1.InsertLink(Object link) in C:\Users\matty\Desktop\DOCUMENTI\Programmazione\YoutubeToMp3\YoutubeToMp3\Form1.vb:riga 57
   in YoutubeToMp3.form1.VB$StateMachine_4_HandleUpdateAsync.MoveNext() in C:\Users\matty\Desktop\DOCUMENTI\Programmazione\YoutubeToMp3\YoutubeToMp3\Form1.vb:riga 91
--- Fine traccia dello stack da posizione precedente dove è stata generata l'eccezione ---
   in System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   in System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   in Telegram.Bot.Extensions.Polling.DefaultUpdateHandler.<HandleUpdateAsync>d__3.MoveNext() in /_/src/Telegram.Bot.Extensions.Polling/DefaultUpdateHandler.cs:riga 37
--- Fine traccia dello stack da posizione precedente dove è stata generata l'eccezione ---
   in System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   in System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   in System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   in Telegram.Bot.Extensions.Polling.DefaultUpdateReceiver.<ReceiveAsync>d__4.MoveNext() in /_/src/Telegram.Bot.Extensions.Polling/DefaultUpdateReceiver.cs:riga 105
--- Fine traccia dello stack da posizione precedente dove è stata generata l'eccezione ---
   in System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   in System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   in Telegram.Bot.TelegramBotClientPollingExtensions.<ReceiveAsync>d__7.MoveNext() in /_/src/Telegram.Bot.Extensions.Polling/Extensions/TelegramBotClientPollingExtensions.cs:riga 319
--- Fine traccia dello stack da posizione precedente dove è stata generata l'eccezione ---
   in System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   in System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   in Telegram.Bot.TelegramBotClientPollingExtensions.<>c__DisplayClass3_0.<<StartReceiving>b__0>d.MoveNext() in /_/src/Telegram.Bot.Extensions.Polling/Extensions/TelegramBotClientPollingExtensions.cs:riga 148

Inoltre ci tengo a precisare che la il SetAttribute del WebBrowser funziona alla perfezione usando un bottone e InsertLink("ciao")

edit: nella gif, il parametro link non é duchiarato come string nella private sub. É un mio errore che ho dimenticato di correggere, ma confermo che l errore che ottengo é lo stesso identico usando Private Sub InsertLink(link as string)
edit2: gif aggiornata con breakpoints