Imports System.Net

Public Class BPWebClient
    Inherits WebClient

    Private m_userAgent As String
    Private m_timeout As Integer
    Private m_cookies As New CookieCollection()


    ''' <summary>
    ''' The user agent string to use.
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property UserAgent() As String
        Get
            Return m_userAgent
        End Get
        Set(ByVal value As String)
            m_userAgent = value
        End Set
    End Property

    ''' <summary>
    ''' The timout in seconds
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Timout() As Integer
        Get
            Return m_timeout
        End Get
        Set(ByVal value As Integer)
            ' Convert it to milliseconds
            m_timeout = value * 1000
        End Set
    End Property

    Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
        Dim request As WebRequest = MyBase.GetWebRequest(address)

        If TypeOf (request) Is HttpWebRequest Then
            With CType(request, HttpWebRequest)
                .CookieContainer = New System.Net.CookieContainer()

                ' Add in the old cookies from last response
                For Each c As Cookie In m_cookies
                    .CookieContainer.Add(c)
                Next

                .UserAgent = m_userAgent
                If m_timeout > 1 Then
                    .Timeout = m_timeout
                End If
            End With
        End If

        Return request
    End Function

    Protected Overrides Function GetWebResponse(ByVal request As System.Net.WebRequest) As System.Net.WebResponse
        Dim response As WebResponse = MyBase.GetWebResponse(request)

        If TypeOf (response) Is HttpWebResponse Then
            With CType(response, HttpWebResponse)
                ' Save the cookies so we can use them in the next request
                m_cookies = .Cookies
            End With
        End If

        Return response
    End Function

End Class
