'========================
' Configuration Constants
'========================
Const CompanyName = "IS Testing Company"
Const UserId = "admin"
Const Password = "admin"
Const ProxyServer = ""
Const ProxyUserName = ""
Const ProxyPassword = ""
Const PollSeconds = 30
Const ServerName = "www.intersoft.co.nz"
Const RequestURL = "Http://www.intersoft.co.nz/LAP/Services/Request.asp"
Const NotifcationMessage = "There are % Open Loan Applications Not Yet Downloaded from the Web"

'=================
' Global Variables
'=================
Public mLAPWebRequest
Public mRst
public mCount
public mFinPower

'===========
' Initialise
'===========
WScript.StdOut.WriteLine "Started Polling Web Database at " & ServerName & " for Open Applications..."

'==========================
' Create Web Request Object
'==========================
Set mLAPWebRequest = New LAPWebRequest
With mLAPWebRequest
  .ClientCertificateName = ""
  .CompanyName = CompanyName
  .Password = Password
  .ProxyPassword = ProxyPassword
  .ProxyServer = ProxyServer
  .ProxyUserName = ProxyUserName
  .RequestURL = RequestURL
  .TimeOutSeconds = TimeOutSeconds
  .UserId = UserId
End With

'==========
' Main Loop
'==========
Do
  ' Query Web Database
  If mLAPWebRequest.ExecuteOpenRecordset("SELECT Count(*) FROM LAPApplication WHERE Status='Open'", mRst) Then
    ' OK
    mCount = mRst.Fields(0).Value
    WScript.StdOut.WriteLine "OK: " & mCount & " Open Applications"
    mRst.Close

    ' Notify finPOWER
    On Error Resume Next
    Set mFinPOWER = GetObject(, "isfinSupport5.finMessageHandler")
    mFinPower.PostMessage 2, Replace(NotifcationMessage, "%", "" & mCount), ""
    If Err.Number <> 0 Then
      WScript.StdOut.WriteLine "Note: Could not notify finPOWER. finPOWER is not running."
    Else
    End If
    On Error Goto 0
  Else
    ' Error
    WScript.StdOut.WriteLine ""
    WScript.StdOut.WriteLine "**** Error ****" 
    WScript.StdOut.WriteLine mLAPWebRequest.ErrorMessage
    WScript.StdOut.WriteLine ""
  End If

  ' Wait
  WScript.Sleep 1000 * PollSeconds
Loop

Stop






'=========================================
' LAPWebRequest Class
'
' Copyright 2006 Intersoft Systems Limited
'=========================================
Class LAPWebRequest

  ' Connection Properties
  Public ClientCertificateName
  Public ProxyPassword
  Public ProxyServer
  Public ProxyUserName
  Public RequestURL
  Public TimeOutSeconds

  ' Other Properties
  Public CompanyName
  Public ErrorMessage
  Public Password
  Public UserId
	
  Private Sub Class_Initialize()
	
    ' Set Defaults
    TimeOutSeconds = 30
	
  End Sub
	
  Public Function ExecuteOpenRecordset(ByVal SQLQuery, _
                                       ByRef rst)

    Dim RequestXML
    Dim ResponseXMLDocument
    Dim XMLNode
    Dim stm

      ' Assume success
      ExecuteOpenRecordset = True
	  
      ' Form Request
      RequestXML = "<SQLQuery>" + SQLQuery + "</SQLQuery>"

      ' Execute
      If ExecuteRequest("OpenRecordset", "1.0", "", RequestXML, ResponseXMLDocument) Then
        ' Retrieve results
        Set XMLNode = ResponseXMLDocument.selectSingleNode("/Message/Response/xml")
        If XMLNode Is Nothing Then
          ExecuteOpenRecordset = False
          ErrorMessage = "The XML response from 'OpenRecordset' does not include the expected information."
        Else
          ' Read XML into ADO Recordset
          On Error Resume Next
          Set rst = CreateObject("ADODB.Recordset")
          Set stm = CreateObject("ADODB.Stream")
          With stm
            .Open
            .WriteText XMLNode.XML
            .Position = 0
          End With
          rst.Open stm
          stm.Close
	      
          ' Check for Errors
          If Err.number <> 0 Then
            ExecuteOpenRecordset = False
            ErrorMessage = Err.Description
          End If
          On Error Goto 0
        End If
      Else
        ExecuteOpenRecordset = False
      End If
	  
      ' Tidy Up
      Set XMLNode = Nothing
      Set ResponseXMLDocument = Nothing
      Set stm = Nothing

  End Function

  Private Function ExecuteRequest(ByVal ServiceName, _
                                  ByVal ServiceVersion, _
                                  ByVal RequestId, _
                                  ByVal RequestXML, _
                                  ByRef ResponseXMLDocument)

  Dim HTTPRequest
  Dim Request
  Dim ResponseXML
  Dim strTemp
  Dim XMLDocument
  Dim XMLNode

    ' Assume Success
    ExecuteRequest = True
  
    ' Initialise
    ResponseXML = ""

    ' Attempt to create ServerXMLHTTP40 Object
    On Error Resume Next
    Set HTTPRequest = CreateObject("MSXML2.ServerXMLHTTP.4.0")

    If Err.Number = 0 Then
      ' Check URL
      If Len(RequestURL) = 0 Then
        ExecuteRequest = False
        ErrorMessage = "Please define the 'Request URL'."
      ElseIf Len(UserId) = 0 Or Len(Password) = 0 Then
        ExecuteRequest = False
        ErrorMessage = "Please define the UserId and Password."
      End If
    Else
      ' Error creating object
      ExecuteRequest = False
      ErrorMessage = "MSXML version 4.0 does not appear to be installed on this computer. This is required to access the Loan Application website." + vbNewLine + vbNewLine + Err.Description
    End If
  
    ' Create XML Request message
    If ExecuteRequest Then
      ' Start Message
      Request = Request + "<?xml version='1.0'?>"
      Request = Request + "<Message Type='Intersoft Loan Application'>"
    
      ' Header Information
      Request = Request + "<Header>"
      Request = Request + "<Service>" + ServiceName + "</Service>"
      Request = Request + "<Version>" + ServiceVersion + "</Version>"
      Request = Request + "<UserId>" + UserId + "</UserId>"
      Request = Request + "<Password>" + Password + "</Password>"
      Request = Request + "<CompanyName>" + CompanyName + "</CompanyName>"
      Request = Request + "<RequestId>" + RequestId + "</RequestId>"
      Request = Request + "<Application>"
      Request = Request + "<Name>" + ActiveDocument.AttachedTemplate.Name + "</Name>"
      Request = Request + "<Version>1.0</Version>"
      Request = Request + "<User></User>"
      Request = Request + "<DateTime></DateTime>"
      Request = Request + "</Application>"
      Request = Request + "</Header>"
    
      ' Request Information
      Request = Request + "<Request>"
      Request = Request + RequestXML
      Request = Request + "</Request>"
    
      ' End Message
      Request = Request + "</Message>"
    End If

    If ExecuteRequest Then
      ' Trap any errors
      On Error Resume Next

      ' Perform the request
      With HTTPRequest
        ' Set Proxy details
        If Len(ProxyServer) = 0 Then
          .setProxy SXH_PROXY_SET_DIRECT
        ElseIf ProxyServer = "[PRECONFIG]" Then
          .setProxy SXH_PROXY_SET_PRECONFIG
        Else
          .setProxy SXH_PROXY_SET_PROXY, ProxyServer
        End If
        If Len(ProxyUserName) <> 0 Then
          .setProxyCredentials ProxyUserName, ProxyPassword
        End If

        ' Set Timeout
        .setTimeouts (TimeOutSeconds * 1000), (TimeOutSeconds * 1000), (TimeOutSeconds * 1000), (TimeOutSeconds * 1000)
      
        ' Set Client Certificate
        If Len(ClientCertificateName) <> 0 Then
          .setOption SXH_OPTION_SELECT_CLIENT_SSL_CERT, ClientCertificateName
        End If

        ' Submit the request
        .Open "POST", RequestURL, False
        .Send Request

        If Err.Number = 0 Then
          ' Pick up the response
          ResponseXML = .responseText

          ' Check the status returned
          Select Case .Status
            Case 200
            Case Else
              ExecuteRequest = False
              ErrorMessage = "An unexpected Status response of '" & .StatusText & "' (" & .Status & ") was received attempting to contact '" + RequestURL '."
          End Select
        Else
          ExecuteRequest = False

          Select Case Err.Number
            Case -2147012889
              strTemp = Err.Description & vbNewLine & vbNewLine
              strTemp = strTemp & "Possible causes of this error are:" & vbNewLine & vbNewLine
              strTemp = strTemp & "1. Your Proxy Server settings are incorrect." & vbNewLine
             strTemp = strTemp & "2. Your Request URL is not setup correctly."
           Case Else
             strTemp = Err.Description & vbNewLine & vbNewLine
             strTemp = strTemp & "Possible causes of this error are:" & vbNewLine & vbNewLine
             strTemp = strTemp & "1. You do not have a connection to the Internet." & vbNewLine
             strTemp = strTemp & "2. Your connection details (Proxy Server or Request URL) are not setup correctly." & vbNewLine
             strTemp = strTemp & "3. The Loan Application website has failed to respond to this request."
           End Select

           ErrorMessage = strTemp
        End If
      End With
    End If
  
    ' Check Valid XML
    If ExecuteRequest Then
      ' Load XML
      Set XMLDocument = CreateObject("MSXML2.DOMDocument.4.0")
      XMLDocument.loadXML ResponseXML
  
      ' Check for an Error
      If XMLDocument.parseError.ErrorCode <> 0 Then
        ExecuteRequest = False
        strTemp = "The XML response from '" + ServiceName + "' was not a valid XML document." + vbNewLine + vbNewLine
        strTemp = strTemp + "Message" + vbTab + ": " + XMLDocument.parseError.Reason
        strTemp = strTemp + "Error" + vbTab + ": " & XMLDocument.parseError.ErrorCode
        If Len(XMLDocument.parseError.srcText) <> 0 Then
          strTemp = strTemp + vbNewLine + "Source" + vbTab + ": " + XMLDocument.parseError.srcText
          If XMLDocument.parseError.linepos <> 0 Then strTemp = strTemp + vbNewLine + "Position" + vbTab + ": " & XMLDocument.parseError.linepos
        End If
        ErrorMessage = strTemp
      End If
    End If
  
    ' Check format is valid and find Exception tag if present
    If ExecuteRequest Then
      ' Check that response is enclosed in a Message tag
      Set XMLNode = XMLDocument.selectSingleNode("/Message")
      If XMLNode Is Nothing Then
          ExecuteRequest = False
          ErrorMessage = "Response does not contain a 'Message' tag."
      Else
        ' Check for Exception
        Set XMLNode = XMLDocument.selectSingleNode("/Message/Exception")
        If Not XMLNode Is Nothing Then
          ExecuteRequest = False
          ErrorMessage = "Execution of Web Service '" + ServiceName + "' failed. The following error was returned." + vbNewLine + vbNewLine + XMLNode.Text
        End If
      
        ' Check for Response
        If ExecuteRequest Then
          Set XMLNode = XMLDocument.selectSingleNode("/Message/Response")
          If XMLNode Is Nothing Then
            ExecuteRequest = False
            ErrorMessage = "The response from this service does not contain a 'Response' tag."
          Else
            Set ResponseXMLDocument = XMLDocument
          End If
        End If
      End If
    End If

    ' Tidy Up
    Set HTTPRequest = Nothing
    Set XMLDocument = Nothing
    Set XMLNode = Nothing

  End Function

End Class