' Collection of code snippets by Arne Vajhøj 
' (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
﻿Imports System
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Web.Script.Serialization
Imports System.Xml.Serialization

Namespace Test1
    <XmlRoot(ElementName := "t1")> _
    Public Class T1
        Public Property f1() As Integer
        Public Property f2() As String
        Public Sub New()
            Me.New(0, "")
        End Sub
        Public Sub New(f1 As Integer, f2 As String)
            Me.f1 = f1
            Me.f2 = f2
        End Sub
        Public Overrides Function ToString() As String
            Return String.Format("{{{0},{1}}}", f1, f2)
        End Function
    End Class
    <XmlRoot(ElementName := "t1array")> _
    Public Class T1Array
        <XmlElement(ElementName := "t1")> _
        Public Property t1array() As T1()
        Public Sub New()
            Me.New(New T1(-1) {})
        End Sub
        Public Sub New(array As T1())
            Me.t1array = array
        End Sub
    End Class
    Public NotInheritable Class Util
        Private Sub New()
        End Sub
        Public Shared Function Object2XML(o As Object) As String
            Dim ser As New XmlSerializer(o.[GetType]())
            Using sw As New StringWriter()
                ser.Serialize(sw, o)
                Return sw.ToString().Replace("utf-16", "utf-8") ' StringWriter end up with "utf-16" which is not good
            End Using
        End Function
        Public Shared Function XML2Object(Of T)(xml As String) As T
            Dim ser As New XmlSerializer(GetType(T))
            Using sr As New StringReader(xml)
                Return DirectCast(ser.Deserialize(sr), T)
            End Using
        End Function
        Public Shared Function Object2JSON(o As Object) As String
            Dim ser As New JavaScriptSerializer()
            Dim sb As New StringBuilder()
            ser.Serialize(o, sb)
            Return sb.ToString()
        End Function
        Public Shared Function JSON2Object(Of T)(xml As String) As T
            Dim ser As New JavaScriptSerializer()
            Return DirectCast(ser.Deserialize(xml, GetType(T)), T)
        End Function
        Public Shared Function Object2String(o As Object, typ As String) As String
            If typ = "application/xml" Then
                Return Util.Object2XML(o)
            ElseIf typ = "application/json" Then
                Return Util.Object2JSON(o)
            Else
                Throw New Exception("Unknown type: " & typ)
            End If
        End Function
        Public Shared Function String2Object(Of T)(s As String, typ As String) As T
            If typ = "application/xml" Then
                Return Util.XML2Object(Of T)(s)
            ElseIf typ = "application/json" Then
                Return Util.JSON2Object(Of T)(s)
            Else
                Throw New Exception("Unknown type: " & typ)
            End If
        End Function
        Public Shared Function GetAllLines(stm As Stream) As String
            Using sr As New StreamReader(stm)
                Return sr.ReadToEnd()
            End Using
        End Function
    End Class
    Public Class ClientManual
        Private Shared Sub TestGetOne(urlprefix As String, f1 As Integer, acctyp As String)
            Dim request As HttpWebRequest = DirectCast(WebRequest.Create(urlprefix & "/t1/" & f1), HttpWebRequest)
            request.Method = WebRequestMethods.Http.[Get]
            request.Accept = acctyp
            Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
            Console.WriteLine(CInt(response.StatusCode) \ 100 = 2)
            Dim contyp As String = response.ContentType.Split(";"C)(0)
            Dim respbody As String = Util.GetAllLines(response.GetResponseStream())
            Console.WriteLine(Util.String2Object(Of T1)(respbody, contyp))
            response.Close()
        End Sub
        Private Shared Sub TestGetAll(urlprefix As String, acctyp As String)
            Dim request As HttpWebRequest = DirectCast(WebRequest.Create(urlprefix & "/t1"), HttpWebRequest)
            request.Method = WebRequestMethods.Http.[Get]
            request.Accept = acctyp
            Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
            Console.WriteLine(CInt(response.StatusCode) \ 100 = 2)
            Dim contyp As String = response.ContentType.Split(";"C)(0)
            Dim respbody As String = Util.GetAllLines(response.GetResponseStream())
            Dim a As T1()
            If acctyp = "application/xml" Then
                a = Util.String2Object(Of T1Array)(respbody, contyp).t1array
            Else
                a = Util.String2Object(Of T1())(respbody, contyp)
            End If
            For Each o As T1 In a
                Console.Write(o)
            Next
            Console.WriteLine()
            response.Close()
        End Sub
        Private Shared Sub TestGetSome(urlprefix As String, start As Integer, finish As Integer, acctyp As String)
            Dim request As HttpWebRequest = DirectCast(WebRequest.Create(urlprefix & "/t1?start=" & start & "&finish=" & finish), HttpWebRequest)
            request.Method = WebRequestMethods.Http.[Get]
            request.Accept = acctyp
            Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
            Console.WriteLine(CInt(response.StatusCode) \ 100 = 2)
            Dim contyp As String = response.ContentType.Split(";"C)(0)
            Dim respbody As String = Util.GetAllLines(response.GetResponseStream())
            Dim a As T1()
            If acctyp = "application/xml" Then
                a = Util.String2Object(Of T1Array)(respbody, contyp).t1array
            Else
                a = Util.String2Object(Of T1())(respbody, contyp)
            End If
            For Each o As T1 In a
                Console.Write(o)
            Next
            Console.WriteLine()
            response.Close()
        End Sub
        Private Shared Sub TestPost(urlprefix As String, contyp As String, o As T1, acctyp As String)
            Dim request As HttpWebRequest = DirectCast(WebRequest.Create(urlprefix & "/t1"), HttpWebRequest)
            request.Method = WebRequestMethods.Http.Post
            request.Accept = acctyp
            request.ContentType = contyp
            Dim reqbody As String = Util.Object2String(o, contyp)
            request.GetRequestStream().Write(Encoding.UTF8.GetBytes(reqbody), 0, Encoding.UTF8.GetByteCount(reqbody))
            Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
            Console.WriteLine(CInt(response.StatusCode) \ 100 = 2)
            Dim contyp2 As String = response.ContentType.Split(";"C)(0)
            Dim respbody As String = Util.GetAllLines(response.GetResponseStream())
            Console.WriteLine(Util.String2Object(Of T1)(respbody, contyp2))
            response.Close()
        End Sub
        Private Shared Sub TestPut(urlprefix As String, contyp As String, o As T1)
            Dim request As HttpWebRequest = DirectCast(WebRequest.Create(urlprefix & "/t1/" & o.f1), HttpWebRequest)
            request.Method = WebRequestMethods.Http.Put
            request.ContentType = contyp
            Dim reqbody As String = Util.Object2String(o, contyp)
            request.GetRequestStream().Write(Encoding.UTF8.GetBytes(reqbody), 0, Encoding.UTF8.GetByteCount(reqbody))
            Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
            Console.WriteLine(CInt(response.StatusCode) \ 100 = 2)
            response.Close()
        End Sub
        Private Shared Sub TestDelete(urlprefix As String, f1 As Integer)
            Dim request As HttpWebRequest = DirectCast(WebRequest.Create(urlprefix & "/t1/" & f1), HttpWebRequest)
            request.Method = "DELETE"
            Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
            Console.WriteLine(CInt(response.StatusCode) \ 100 = 2)
            response.Close()
        End Sub
        Private Shared Sub Test(urlprefix As String, typ As String)
            Console.WriteLine("**** " & urlprefix & " (" & typ & ") ****")
            TestGetOne(urlprefix, 123, typ)
            TestGetAll(urlprefix, typ)
            TestGetSome(urlprefix, 10, 12, typ)
            TestPost(urlprefix, typ, New T1(123, "ABC"), typ)
            TestPut(urlprefix, typ, New T1(123, "ABC"))
            TestDelete(urlprefix, 123)
        End Sub
        Private Shared Sub Test(urlprefix As String)
            Test(urlprefix, "application/xml")
            Test(urlprefix, "application/json")
        End Sub
        Public Shared Sub Main(args As String())
            Test("http://localhost:8080/wsrest/testapi1")
            Test("http://localhost:8080/wsrest/testapi2")
            Test("http://localhost:8080/wsrest/testapi3")
            Test("http://localhost/testapi.ashx")
            Test("http://localhost/testapi.svc")
            Test("http://localhost/testapi")
            Test("http://localhost:81/testapi.php")
        End Sub
    End Class
End Namespace
