Imports System.Net
Imports System.Runtime.CompilerServices

''' <summary>
''' A set of extensions for remoting and network services.
''' </summary>
''' <remarks></remarks>
Public Module RemotingExtensions

    ''' <summary>
    ''' Converts an IP end point to its XML-safe string representation.
    ''' </summary>
    ''' <param name="endPoint">The IP end point to convert.</param>
    ''' <returns>An XML-safe string representation of an IP end point.</returns>
    ''' <remarks></remarks>
    <Extension()> _
    Public Function ToSerial(ByVal endPoint As IPEndPoint) As String
        If (endPoint Is Nothing) Then _
            Return Nothing
        Return String.Format("{0}@{1}", endPoint.Address, endPoint.Port)
    End Function

    ''' <summary>
    ''' Returns an IP end point generated from its XML-safe string representation.
    ''' </summary>
    ''' <param name="ipFormat">The XML-safe string representation of the IP end point.</param>
    ''' <returns>an IP end point generated from its XML-safe string representation.</returns>
    ''' <remarks></remarks>
    <Extension()> _
    Public Function FromSerialIP(ByVal ipFormat As String) As IPEndPoint
        If (String.IsNullOrEmpty(ipFormat)) Then _
            Return Nothing

        ' Split at delimiter
        Dim endPointArr = Split(ipFormat, "@")
        If (endPointArr IsNot Nothing AndAlso endPointArr.Length = 2) Then
            Try
                Dim ip As IPAddress = IPAddress.Parse(endPointArr(0))
                Dim port As Integer = Integer.Parse(endPointArr(1))
                Return New IPEndPoint(ip, port)
            Catch ex As OverflowException
            Catch ex As FormatException
            End Try
        End If
        Return Nothing
    End Function

End Module