Android Question Basics of B4XSerializator and VB.NET

mmieher

Active Member
Licensed User
I am trying to get the basics down of using B4XSerializator to communicate with a VB.NET server.

I get a "Header Checksum Illegal" in the VB code after ConvertBytesToObject on ReadObject at Dim t As Byte = br.ReadByte(). Code attached is my attempt to convert Erel's C# code to VB.

After researching the error I inspected the bytes received on the server. In a previous post, one of the Erels stated that the byte stream should start with 0x78, 0x9C.

Mine does not. The first six bytes are 0x50,0x00,0x00,0x00,0x78,0xEF.

Any idea what I am doing wrong?

Marc

B4A Code:
B4X:
Sub Process_Globals
   
    Private ser As B4XSerializator
    Type MyMessage (sndData As String)
   
End Sub
Sub WriteTestData
    Dim mm As MyMessage
    mm.Initialize
    mm.sndData = "Hello!"
   
    Log("Sending mm")
    CallSub2(Starter, "SendData", ser.ConvertObjectToBytes(mm))
   
End Sub
VB.NET Code:
B4X:
Protected Sub ClientSession()
        Dim myCompleteMessage As StringBuilder = New StringBuilder()
        Debug.Print("ClientSession = " & clientSocket.Connected)
        If clientSocket.Connected = False Then
            Debug.Print("Client Not Connected")
            Return
        End If
        While (True)
            If clientSocket.Connected = False Then
                Debug.Print("Disconnect")
                Exit While
            End If
            Try
                Dim networkStream As NetworkStream = clientSocket.GetStream()
                Debug.Print("canRead = " & networkStream.CanRead)
                If networkStream.CanRead Then
                    Dim myReadBuffer(1024) As Byte
                    Dim numberOfBytesRead As Integer = 0
                    Debug.Print("DataAvailable = " & networkStream.DataAvailable)
                    ' Incoming message may be larger than the buffer size.
                    Do
                        numberOfBytesRead = networkStream.Read(myReadBuffer, 0, myReadBuffer.Length)
                        myCompleteMessage.AppendFormat("{0}", Encoding.UTF8.GetString(myReadBuffer, 0, numberOfBytesRead))
                    Loop While networkStream.DataAvailable
                    Debug.Print("Received Bytes = " & myCompleteMessage.Length)
                    ' Print out the received message to the console.
                    Debug.Print("You received the following message : " + myCompleteMessage.ToString())
                End If
            Catch ex As Exception
                Debug.Print(ex.ToString)
            End Try
            If myCompleteMessage.Length > 0 Then
                Debug.Print(vbCrLf & "DESERIALIZE")
                Dim ByteArray As Byte() = System.Text.Encoding.UTF8.GetBytes(myCompleteMessage.ToString())
                Dim B4Xs As New B4X.B4XSerial
                Debug.Print(myCompleteMessage.ToString)
                MsgRecord = B4Xs.ConvertBytesToObject(ByteArray)
            End If
        End While
    End Sub
 

Attachments

  • B4XSerial.zip
    2 KB · Views: 140

mmieher

Active Member
Licensed User
Thank you, Erel. I would love to use B4J but I have to talk to a Sage Software database using Sage's ODBC driver. No JDBC driver available from Sage.
 
Upvote 0

mmieher

Active Member
Licensed User
Ok, I noticed that in the ZIP file that has the C# code, there is also B4XSerializator.dll, which I have added as a reference in my VB.NET code.

Also, to eliminate my human error in the B4A code, I am using Erel's "Network Example" app to send a B4XSerializator object to my server program.

However, I still get the Header Checksum Illegal error when calling ConvertBytesToObject.

I know this is not a Microsoft forum, but I must be doing something simple incorrectly.

Marc

ICSharpCode.SharpZipLib.SharpZipBaseException
HResult=0x80131600
Message=Header checksum illegal
Source=ICSharpCode.SharpZipLib
StackTrace:
at ICSharpCode.SharpZipLib.Zip.Compression.Inflater.DecodeHeader()
at ICSharpCode.SharpZipLib.Zip.Compression.Inflater.Decode()
at ICSharpCode.SharpZipLib.Zip.Compression.Inflater.Inflate(Byte[] buffer, Int32 offset, Int32 count)
at ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.Stream.ReadByte()
at System.IO.BinaryReader.ReadByte()
at WpfApplication1.B4XSerializator.readObject()
at WpfApplication1.B4XSerializator.ConvertBytesToObject(Byte[] Bytes)
at PMCTechServer10.handleClient.ClientSession() in C:\VBSource\AA-VB.NET\PMCTechServer10\PMCTechServer10\PMCTechServer10\MainForm.vb:line 151
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

VB.NET CODE
B4X:
Protected Sub ClientSession()
        Dim ReadBuffer(clientSocket.ReceiveBufferSize) As Byte
        Dim BytesRead As Integer
        Debug.Print("ClientSession = " & clientSocket.Connected)
        While (True)
            If clientSocket.Connected = False Then
                Debug.Print("Disconnect")
                Exit While
            End If
            Try
                Dim networkStream As NetworkStream = clientSocket.GetStream()
                Debug.Print("canRead = " & networkStream.CanRead)
                If networkStream.CanRead Then
                    BytesRead = networkStream.Read(ReadBuffer, 0, ReadBuffer.Length)
                    Debug.Print("BytesRead: " & BytesRead)
                End If
            Catch ex As Exception
                Debug.Print(ex.ToString)
            End Try
            If BytesRead > 0 Then
                Debug.Print(vbCrLf & "DESERIALIZE")
                Dim rcvBytes(BytesRead) As Byte
                System.Buffer.BlockCopy(ReadBuffer, 0, rcvBytes, 0, BytesRead)
                Dim B4Xs As New WpfApplication1.B4XSerializator
                MsgRecord = B4Xs.ConvertBytesToObject(rcvBytes)
 
Upvote 0

Erel

Administrator
Staff member
Licensed User
Complete example of deserializing a file created with B4XSerializator:
B4X:
Imports System.IO
Class MainWindow

    Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)

        Dim b() As Byte = File.ReadAllBytes("C:\Users\H\Downloads\projects\WpfApplication1\WpfApplication1\1.dat")
        Dim ser As B4XSerializator = New B4XSerializator()

        Dim list As IList = ser.ConvertBytesToObject(b)
        For i = 0 To list.Count - 1
            Dim number As Integer = list(i)
            Console.WriteLine(number)


        Next


    End Sub
End Class

File created with:
B4X:
Dim l1 As List
l1.Initialize
For i = 1 To 1000
   l1.Add(i)
Next
Dim out As OutputStream = File.OpenOutput(File.DirApp, "1.dat", False)
Dim ser As B4XSerializator
Dim b() As Byte = ser.ConvertObjectToBytes(l1)
out.WriteBytes(b, 0, b.Length)
out.Close
 
Upvote 0

mmieher

Active Member
Licensed User
Complete example of deserializing a file created with B4XSerializator:
B4X:
Imports System.IO
Class MainWindow

    Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)

        Dim b() As Byte = File.ReadAllBytes("C:\Users\H\Downloads\projects\WpfApplication1\WpfApplication1\1.dat")
        Dim ser As B4XSerializator = New B4XSerializator()

        Dim list As IList = ser.ConvertBytesToObject(b)
        For i = 0 To list.Count - 1
            Dim number As Integer = list(i)
            Console.WriteLine(number)


        Next


    End Sub
End Class

File created with:
B4X:
Dim l1 As List
l1.Initialize
For i = 1 To 1000
   l1.Add(i)
Next
Dim out As OutputStream = File.OpenOutput(File.DirApp, "1.dat", False)
Dim ser As B4XSerializator
Dim b() As Byte = ser.ConvertObjectToBytes(l1)
out.WriteBytes(b, 0, b.Length)
out.Close


Thank you! Now I am getting somewhere.
 
Upvote 0
Marc,

I have been interested by your post as I am just starting with B4XSerializator in B4A.
Did you reach to use B4XSerializator to communicate with a VB.NET server ?

Could you let me (us) know how you finally make your test herebefore work fine ?

Olivier
 
Upvote 0

KMatle

Expert
Licensed User
You can create a list with maps or a map and convert it to a json string. Convert this string to bytes and send it. On .net convert it back. Very easy and this works for all platforms as long you use the same charset.
 
Upvote 0
Thank you KMatle for your reply.

I agree with you about the json suggestion. I already use it !

Behind my last post, there is a choice I have to do. I have a common UI on a tool install on a android device with B4A. With a vb.net program I prepare a file to customize this B4A UI. Then, with this UI, the android device generate a json file as the result of its manipulation and is supposed to send it back to the desktop.

To communicate file asynchronously between android device and desktop and if I well understand, I should be able to use B4XSerializator through WiFi network or Bluetooth.
Am I right ? Any suggestion ?
 
Upvote 0
Erel,
You said it is not a must to use B4Xserializator for my purpose. Why ?

On my side :
I work with your "filetransfer" presented in this post : https://www.b4x.com/android/forum/t...nd-and-receive-files-with-asyncstreams.30493/
And I work with the .net implementation presented in this post : https://www.b4x.com/android/forum/threads/net-filetransfer-implement-asyncstreams-prefix-mode.30741/

Every things work unless, a problem with the CC contentChooser to chose the file to transfer from device to PC. the pointer is null when a file is selected.
Do you have any idea what occurs ? (If I need to start a new thread let me know because the other one is closed)

Olivier,

Error occurred on line: 213 (Main)
java.lang.NullPointerException
at java.io.File.<init>(File.java:323)
at anywheresoftware.b4a.objects.streams.File.Exists(File.java:96)
at b4a.example.filetransfer.main._cc_result(main.java:882)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:732)
at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:348)
at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:255)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:144)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:176)
at anywheresoftware.b4a.phone.Phone$ContentChooser$1.ResultArrived(Phone.java:865)
at anywheresoftware.b4a.BA$4.run(BA.java:568)
at anywheresoftware.b4a.BA.setActivityPaused(BA.java:442)
at b4a.example.filetransfer.main$ResumeMessage.run(main.java:306)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7050)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
** Activity (main) Resume **
 
Upvote 0
I have followed your advice. Everything works, file transfer through the b4x-network-asynchronous is effectively really easier with this method.

Only 1 thing strange : On the example download, I haven't be able to connect the B4A device to the B4J desktop, only the B4J desktop to the B4A device. Any idea of what could be the problem ?

Olivier.
 
Upvote 0
Top