Can it be done in vb.net? I've looked online but haven't been able to find anything. If anyone can help me with this, I'd really appreciate it :)

How are you wanting it to be serialized is a good follow-up question? It's possible to use both binary serialization of any object or xml serialization (of which I've only used on datatables). If you just want to send strings through a socket, then I would use the following:

ByteArrayToSendToSocket = Text.Encoding.ASCII.GetBytes(StringToSend)

and the reverse :

StringReturnedFromSocket= System.Text.Encoding.ASCII.GetString(ByteArrayReceivedFromSocket,0,ByteArrayRecievedFromSocket.Length)

For binary serialization:

''' <summary>
    ''' Converts an object to bytes and returns the byte array
    ''' </summary>
    ''' <param name="object">The object to convert into bytes</param>
    ''' <exception cref="Exception">Thrown in any event with the inner exception being the original exception thrown.</exception>
    Public Shared Function ConvertObjectToBytes(ByVal [object] As Object) As Byte()
        Dim byReturn As Byte() = Nothing
        Dim sStream As IO.MemoryStream = Nothing

        Try
            'Create stream
            sStream = New IO.MemoryStream()
            'Initialize BinaryFormater
            Dim bfTemp As New BinaryFormatter
            'Serializes any object into the memorystream
            bfTemp.Serialize(sStream, [object])
            'Returns the stream into an array of bytes
            byReturn = sStream.ToArray

        Catch ex As Exception
            Throw New Exception(String.Format("Exception occured in {0}:{1}{2}", System.Reflection.MethodBase.GetCurrentMethod().Name, vbCrLf & vbCrLf, ex.Message), ex)
        Finally
            If Not sStream Is Nothing Then sStream = Nothing
        End Try

        Return byReturn

    End Function

    ''' <summary>
    ''' Converts an array of bytes into an object
    ''' </summary>
    ''' <param name="bytes">The array of bytes to convert</param>
    ''' <exception cref="Exception">Thrown in any event with the inner exception being the original exception thrown.</exception>
    Public Shared Function ConvertBytesToObject(ByVal [bytes] As Byte()) As Object
        Dim oReturn As Object = Nothing
        Dim sStream As IO.MemoryStream = Nothing

        Try
            'Create stream
            sStream = New IO.MemoryStream(bytes)
            'Initialize BinaryFormater
            Dim bfTemp As New BinaryFormatter
            'Return stream to the beginning
            sStream.Position = 0
            'Deserialize stream into object of any type
            oReturn = bfTemp.Deserialize(sStream)

        Catch ex As Exception
            Throw New Exception(String.Format("Exception occured in {0}:{1}{2}", System.Reflection.MethodBase.GetCurrentMethod().Name, vbCrLf & vbCrLf, ex.Message), ex)
        Finally
            If Not sStream Is Nothing Then sStream = Nothing
        End Try

        Return oReturn
    End Function

For XML serialization for data tables:

''' <summary>
    ''' Converts a datatable into an XML string
    ''' </summary>
    ''' <param name="datatable">The datatable to convert</param>
    ''' <remarks>Deprecated use ConvertObjectIntoBytes</remarks>
    ''' <exception cref="Exception">Thrown in any event with the inner exception being the original exception thrown.</exception>
    Public Shared Function ConvertDataTableToString(ByVal [datatable] As DataTable) As String
        Dim sReturn As String = String.Empty
        Dim sStream As IO.MemoryStream = Nothing
        Dim sWriter As IO.StreamWriter = Nothing
        Try
            'Initialize stream and writer
            sStream = New IO.MemoryStream
            sWriter = New IO.StreamWriter(sStream)

            'Determine if name exists, add if not. Otherwise exception is thrown on WriteXML
            If datatable.TableName.Length = 0 Then datatable.TableName = "Temp Table"
            'Set the serializationformat for writing XML. Otherwise exception is thrown on WriteXML
            datatable.RemotingFormat = SerializationFormat.Xml

            'Write datatable to stream
            datatable.WriteXml(sWriter, mode:=XmlWriteMode.WriteSchema)
            sWriter.Flush()

            'Initialize the byte for writing to
            Dim sByteTemp(CInt(sStream.Length)) As Byte

            'Reset the stream to the beginning
            sStream.Position = 0
            'Write the stream to the byte
            sStream.Read(sByteTemp, 0, sByteTemp.Length)

            'Conver the byte array into a string
            sReturn = System.Text.Encoding.ASCII.GetString(sByteTemp)

            'Close the streamwriter and stream
            sWriter.Close()
        Catch ex As Exception
            Throw New Exception(String.Format("Exception occured in {0}:{1}{2}", System.Reflection.MethodBase.GetCurrentMethod().Name, vbCrLf & vbCrLf, ex.Message), ex)
        Finally
            'Dispose of the stream and the reader in all instances
            If sStream Is Nothing Then sStream = Nothing
            If Not sWriter Is Nothing Then sWriter = Nothing
        End Try

        Return sReturn
    End Function

    ''' <summary>
    ''' Converts and XML string into a datatable
    ''' </summary>
    ''' <param name="string">The XML string to convert</param>
    ''' <remarks>Deprecated use ConvertObjectIntoBytes</remarks>
    ''' <exception cref="Exception">Thrown in any event with the inner exception being the original exception thrown.</exception>
    Public Shared Function ConvertStringIntoDatatable(ByVal [string] As String) As DataTable
        Dim dtReturn As DataTable = Nothing
        Dim sStream As IO.MemoryStream = Nothing
        Dim sReader As IO.StreamReader = Nothing

        Try
            'Initialize the stream, writer and datatable
            sStream = New IO.MemoryStream(Text.Encoding.ASCII.GetBytes([string]))
            sReader = New IO.StreamReader(sStream)
            dtReturn = New DataTable

            'Populate the datatable
            dtReturn.ReadXml(sStream)

            'Close the reader
            sReader.Close()

        Catch ex As Exception
            Throw New Exception(String.Format("Exception occured in {0}:{1}{2}", System.Reflection.MethodBase.GetCurrentMethod().Name, vbCrLf & vbCrLf, ex.Message), ex)
        Finally
            'Dispose of the stream and the reader in all instances
            If sStream Is Nothing Then sStream = Nothing
            If Not sReader Is Nothing Then sReader = Nothing
        End Try

        Return dtReturn

    End Function
    ''' <summary>
    ''' Converts the entire string into bytes()
    ''' </summary>
    ''' <param name="string">The string to convert</param>
    ''' <remarks>Deprecated use ConvertObjectIntoBytes</remarks>
    ''' <exception cref="Exception">Thrown in any event with the inner exception being the original exception thrown.</exception>
    Public Shared Function ConvertStringToBytes(ByVal [string] As String) As Byte()
        Dim byReturn() As Byte = Nothing

        Try
            byReturn = Text.Encoding.ASCII.GetBytes([string])
        Catch ex As Exception
            Throw New Exception(String.Format("Exception occured in {0}:{1}{2}", System.Reflection.MethodBase.GetCurrentMethod().Name, vbCrLf & vbCrLf, ex.Message), ex)
        End Try

        Return byReturn
    End Function
    ''' <summary>
    ''' Converts the entire array of bytes into a string
    ''' </summary>
    ''' <param name="bytes">The byte array to convert</param>
    ''' <remarks>Deprecated use ConvertObjectIntoBytes</remarks>
    ''' <exception cref="Exception">Thrown in any event with the inner exception being the original exception thrown.</exception>
    Public Shared Shadows Function ConvertBytesToString(ByVal [bytes] As Byte()) As String
        Dim sReturn As String = String.Empty

        Try
            sReturn = ConvertBytesToString(bytes, 0, bytes.Length)
        Catch ex As Exception
            Throw New Exception(String.Format("Exception occured in {0}:{1}{2}", System.Reflection.MethodBase.GetCurrentMethod().Name, vbCrLf & vbCrLf, ex.Message), ex)
        End Try

        Return sReturn
    End Function

    ''' <summary>
    ''' Converts the specified section of the bytes array into a string
    ''' </summary>
    ''' <param name="bytes">The byte array to convert</param>
    ''' <param name="start">The starting index</param>
    ''' <param name="length">The number of characters to convert</param>
    ''' <remarks>Better to use the <see cref="ConvertBytesToString"></see> with a single argument of bytes().
    ''' Deprecated use ConvertObjectIntoBytes</remarks>
    Public Shared Shadows Function ConvertBytesToString(ByVal [bytes] As Byte(), ByVal [start] As Integer, ByVal [length] As Integer) As String
        Dim sReturn As String = String.Empty

        Try
            sReturn = System.Text.Encoding.ASCII.GetString(bytes, start, length)
        Catch ex As Exception
            Throw New Exception(String.Format("Exception occured in {0}:{1}{2}", System.Reflection.MethodBase.GetCurrentMethod().Name, vbCrLf & vbCrLf, ex.Message), ex)
        End Try

        Return sReturn
    End Function

With the binary serailization functions, they return in bytes which you can then pass to the sockets data. Once on the other size, you need to un-convert them back into the object and so long as the object has not been (insert word for missing bits or incomplete) then you're object will come out the way it went in.

With the XML serialization I have shown, I'm taking a datatable and creating an XML string, then converting the string into a byte array which is then being passed to the socket for sending.

For any custom object to be serialized you have to use <Serializable()> _ attribute before the class and the class must implement ISerializable. (According to this link)

I don't really have any production ready code, but for my testing purposes, the above listed procedures seemed to work out.

Hope this helps,
~Stevoni

Thanks for the quick reply Stevoni! Let me try this out and ill let you know if i got it to work. Thanks again!

Basically all I'm trying to do is fill a data set and send it over the network. The data set has just a bunch of names in it. Im going to try and send it to another list box on another computer.

Basically all I'm trying to do is fill a data set and send it over the network. The data set has just a bunch of names in it. Im going to try and send it to another list box on another computer.

Try the following. It uses the functions that I had provided you earlier.

'Sender Side
        Dim dsSender As New DataSet()
        Dim bySend As Byte() = ConvertObjectToBytes(dsSender)
        'Un-rem and fill proper values once reciever side is set up
        'Dim socSender As New Socket()
        'socSender.Send(bySend)

        'Reviever side
        'Un-rem once reciever side is set up
        'socSender.Receive(bySend)
        Dim dsReciever As DataSet = CType(ConvertBytesToObject(bySend), DataSet)

I'm assuming that you already have the sockets communicating and are only worried about the serialization. If you need to get the sockets to work, let me know.

Okay Ill try that. It might take me a while to figure it out but ill get back to you :)

With my current project using the .Net Compact Framework, I've had to delve into the usage of XML serialization more. It's much more of a PITA than the binary serialization, but the CF doesn't have binary formatters in it.

If you're not using the .Net Compact Framework, then I wouldn't worry about reading the rest.

XML Serialization has a limitation that the object being serialized must be predefined and the private variables are not serialized unless they are attached to a Public Property. Objects must also have 0 argument constructors in order for the serializer to re-create them.

Because of the first issue, I'm doing a two step serialization process since I'm wrapping the users object to be passed with my own information. After their object is serialized to XML or binary, I add it to my string variable and then serialize the object I'm going to pass.

In my examples, replace "SocketObject" with the object you are wanting to serialize and you should be good to go.
Serialize:

''' <summary>
        ''' Converts a SocketObject to a byte array
        ''' </summary>
        ''' <param name="Object">The socketobject to convert</param>
        ''' <returns></returns>
        ''' <remarks>The SocketObject.Data propert should already have been serialized</remarks>
        Public Shared Function ConvertSocketObjectToXMLByteArray(ByVal [Object] As SocketObject) As Byte()
            Dim byReturn As Byte() = Nothing
            Try
                Dim inStream As New IO.MemoryStream()
                Dim xmlSerial As Xml.Serialization.XmlSerializer = New Xml.Serialization.XmlSerializer(GetType(SocketObject))
                xmlSerial.Serialize(inStream, [Object])
                byReturn = inStream.ToArray
            Catch ex As Exception
                Throw
            End Try

            Return byReturn
        End Function

Deserialize:

''' <summary>
        ''' Converts a string of an XML'd SocketObject into the SocketObject
        ''' </summary>
        ''' <param name="string">The string that is to be converted</param>
        Public Shared Function ConvertXMLStringToSocketObject(ByVal [string] As String) As SocketObject
            Dim oReturn As SocketObject = Nothing

            Try
                Dim inStream As New IO.MemoryStream(System.Text.Encoding.ASCII.GetBytes([string]))
                Dim xmlSerial As Xml.Serialization.XmlSerializer = New Xml.Serialization.XmlSerializer(GetType(SocketObject))
                oReturn = CType(xmlSerial.Deserialize(inStream), SocketObject)
            Catch ex As Exception
                Throw
            End Try

            Return oReturn
        End Function

Note: I have seen a few XML serializers that say they will serialize anything, but I couldn't get them to work properly with custom types. I didn't try to hard either as I had an epiphany about serializing the secondary object while getting a soda.

I know you mentioned you were going to look into the serialization mentioned previously, but this is a follow up to my first post after I had some frustrations with the .Net Compact Framework.

This is a follow up to the previous post quoted above.

If you're not using the .Net Compact Framework, then I wouldn't worry about reading the rest.

With my current project using the .Net Compact Framework, I've had to delve into the usage of XML serialization more. It's much more of a PITA than the binary serialization, but the CF doesn't have binary formatters in it.

The above statement is true, but I had decided to go with the remoting option given by the System.Runtime.Remoting (which as you can guess is not available in .Net CF).

I had spent many hours researching different solutions as well as using a socket serialization as I had mentioned above, but remoting is much easier (yet frustrating for the first few tutorials) and decided to use a third party to control the remoting.

I'm very hesitant to use third party applications or dll's because they cost money and I can't see what they do. But after reading hundreds of posts mentioning the .Net CF remoting solution from As Good As It Gets I checked it out and love it. They have a 60 day free trial and although the documentation is limited with slight modification to your normal desktop remoting process, the .Net CF is now able to use remoting and efficiently (after the first connection).

I by no means am trying to plug for the company other than them offering a very good solution to a problem that I could not get around with my novice to intermediate programming skills.

They also have a .Net CF serialization dll as well which mimics the usage in the desktop world.

Anyway, I wanted to add that to this thread in order to keep the same train of thought.

This article has been dead for over six months. Start a new discussion instead.