question

PieterSouvereyns-2931 avatar image
0 Votes"
PieterSouvereyns-2931 asked karenpayneoregon commented

Convert C to vbnet

I have an existing vbnet program. With this I want to make a connection with a SSE server send events from openhab.
I have found a basic program but it is in C, so I'm trying to convert it to vb.
I don' have error anymore in studio but it doesn't run.
It stops with the line:
Using StreamReader As New StreamReader(Await client.GetStreamAsync(url))

Anyone an Idea. Or maybe a starting point for vbnet ? Or an example in vbnet?

C:
namespace ConsoleApp2
{
class Program
{
static async Task Main(string[] args)
{
HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(5);
string url = $"http://localhost:8080/rest/events";
while (true)
{
try
{
Console.WriteLine("Establishing connection");
using (var streamReader = new StreamReader(await client.GetStreamAsync(url)))
{
while (!streamReader.EndOfStream)
{
var message = await streamReader.ReadLineAsync();
Console.WriteLine($"Received message: {message}");
}
}
}
catch (Exception ex)
{
//Here you can check for
//specific types of errors before continuing
//Since this is a simple example, i'm always going to retry
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine("Retrying in 5 seconds");
await Task.Delay(TimeSpan.FromSeconds(5));
}
}
}
}
}

vbnet

Module Program
Public Sub Main(args As String())
ReadAndDisplayAsync()
End Sub

 Async Sub ReadAndDisplayAsync()
     Dim client As HttpClient = New HttpClient()
     client.Timeout = TimeSpan.FromSeconds(5)
     Dim url As String = $"http://localhost:8080/rest/events"
     While (True)
         Try
             Console.WriteLine("Establishing connection")
             'Dim aaa As Stream = Await client.GetStreamAsync(url)
             Using StreamReader As New StreamReader(Await client.GetStreamAsync(url))
                 'Using streamReader As New StreamReader(await client.GetStreamAsync(url))
                 While (Not StreamReader.EndOfStream)
                     Dim message = Await StreamReader.ReadLineAsync()
                     Console.WriteLine($"Received price update: {message}")
                 End While
             End Using
         Catch ex As Exception
             Console.WriteLine("xxxx")
             '//Here you can check for 
             '//specific types of errors before continuing
             '//Since this Is a simple example, i'm always going to retry
             Console.WriteLine($"Error: {ex.Message}")
             Console.WriteLine("Retrying in 5 seconds")
             'await Task.Delay(TimeSpan.FromSeconds(5))
             'Task.Delay(TimeSpan.FromSeconds(5))
             'Dim result As String = Await WaitAsynchronouslyAsync()
             WaitAsynchronouslyAsync()
         End Try
     End While
 End Sub
 Public Async Function WaitAsynchronouslyAsync() As Task(Of String)
     Await Task.Delay(10000)
     Return "Finished"
 End Function

End Module

dotnet-visual-basic
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

JackJJun-MSFT avatar image
0 Votes"
JackJJun-MSFT answered

Hi @PieterSouvereyns-2931 ,

The VB. NET code converted from C# is :

 Async Function Main(ByVal args As String()) As Task
     Dim client As HttpClient = New HttpClient()
     client.Timeout = TimeSpan.FromSeconds(5)
     Dim url As String = $"http://localhost:8080/rest/events"
     Dim isDelay = False
     While True

         Try
             Console.WriteLine("Establishing connection")

             Using streamReader = New StreamReader(Await client.GetStreamAsync(url))

                 While Not streamReader.EndOfStream
                     Dim message = Await streamReader.ReadLineAsync()
                     Console.WriteLine($"Received message: {message}")
                 End While
             End Using
             isDelay = False
         Catch ex As Exception
             Console.WriteLine($"Error: {ex.Message}")
             Console.WriteLine("Retrying in 5 seconds")
             isDelay = True
         End Try
         If isDelay Then
             Await Task.Delay(TimeSpan.FromSeconds(5))
         End If
     End While
 End Function

Give it a try and if you get any exceptions, please provide a detailed description of the exception.
Hope it could be helpful.

Best Regards,
Jack

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

PieterSouvereyns-2931 avatar image
0 Votes"
PieterSouvereyns-2931 answered

It give the same problem.
At line "Using streamReader = New StreamReader(Await client.GetStreamAsync(url))"
It displays:
(process 11040) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .
Because visual is complaining about the main, I hve tried to put it after a button on a form.
There it does his job. This i my goal to put it on a form.
But he takes the focus to that sub and the form isn't reachabel anymore.
Is it possible to avoid this?

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered

See if this will work for you.

  • One button to run

  • One button to cancel (for errors), you could also setup a timeout or use a counter where if hit terminate the process.

    Imports System.IO
    Imports System.Net.Http
    Imports System.Threading

    Public Class Form1

       Private _cancellationTokenSource As New CancellationTokenSource()
        
         Private Async Function Demo(token As CancellationToken, secondsDelay As Integer) As Task(Of String)
        
             While True
                 Try
        
                     Await Task.Delay(secondsDelay, token)
        
                     Using client = New HttpClient()
        
                         Dim response = Await client.GetAsync("http://httpbin.org/get",
                                                      HttpCompletionOption.ResponseHeadersRead)
        
                         response.EnsureSuccessStatusCode()
        
                         Using stream = Await response.Content.ReadAsStreamAsync()
                             Using streamReader As New StreamReader(stream)
                                 Return Await streamReader.ReadToEndAsync()
                             End Using
                         End Using
                     End Using
        
                 Catch httpRequestException As HttpRequestException
                     Const msg = "Response status code does not indicate success: 404 (NOT FOUND)."
                     If httpRequestException.Message.Contains(msg) Then
                         Console.WriteLine("404 error")
                     End If
        
                     If token.IsCancellationRequested Then
                         token.ThrowIfCancellationRequested()
                         Return String.Empty
                     End If
        
                 Catch generalException As Exception
                     Console.WriteLine(generalException.Message)
                 End Try
             End While
        
             Return String.Empty
        
         End Function
        
         Private Async Sub RunButton_Click(sender As Object, e As EventArgs) Handles RunButton.Click
        
             If _cancellationTokenSource.IsCancellationRequested Then
                 _cancellationTokenSource.Dispose()
                 _cancellationTokenSource = New CancellationTokenSource()
             End If
        
             Try
                 Dim contents = Await Demo(_cancellationTokenSource.Token, 5)
                 Console.WriteLine(contents)
             Catch ex As Exception
                 Console.WriteLine("Failed")
             End Try
        
         End Sub
        
         Private Sub CancelDemo2Button_Click(sender As Object, e As EventArgs) Handles CancelDemo2Button.Click
             _cancellationTokenSource.Cancel()
         End Sub
     End Class
    

In the above we expect

 {
   "args": {}, 
   "headers": {
     "Host": "httpbin.org", 
     "X-Amzn-Trace-Id": "Root=1-6050ae05-0398eea53b2d18322a42d8e8"
   }, 
   "origin": "159.121.204.129", 
   "url": "http://httpbin.org/get"
 }


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

PieterSouvereyns-2931 avatar image
0 Votes"
PieterSouvereyns-2931 answered karenpayneoregon commented

It gives your output.
So I changed the url.
This stops with the ReadToEndAsync, this doens't return with the openhab server
I change ReadToEndAsync to ReadLineAsync
And the While token.IsCancellationRequested = False also in the runbutton.
This works for a part because I have to read more lines.
Tried with a While (Not streamReader.EndOfStream) but then I get the same that he doesn't return

When I debug and look at the straeamreader i get when it is freezing and returning to the main application this message
![78503-image.png][1]
'system.io.streamreader.enofstream.get' timed out and needed to be aborted in an unsafe way. This may have corrupted the target process.


image.png (13.5 KiB)
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

One idea is to install Telerik Fiddler (it's free) and examine messages for the code. Besides monitoring you can (once you have learned Fiddler) run restful actions there.


0 Votes 0 ·