Imports System.Data
Imports System.Data.SqlClient
Imports ESRI.ArcGIS.Carto
Imports ESRI.ArcGIS.Geodatabase
Imports ESRI.ArcGIS.ADF.Web.DataSources

Partial Class MultiSelect
  Inherits System.Web.UI.Page
  Implements ICallbackEventHandler
  Private _callbackArg As String
  Private selectedSiteCount As Integer = -1

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim oNetwork As HISNetwork
    Dim sMsg As String
    'Dim oCurrentNetwork As HISNetwork
    If Not Page.IsCallback And Not Page.IsPostBack Then
      'Dim networkID As String = Nothing
      'Dim variableList As String
      'oCurrentNetwork = Me.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
      'networkID = oCurrentNetwork.Name
      'variableList = queryVariables(networkID)
      'ddlVariables.Attributes.Add("onChange", "selectVariableM(this.value)")
    End If

    Dim cbReference As String = Page.ClientScript.GetCallbackEventReference(Page, "message", ApSConfigAHS.CB_CBGeneralServerProc, "context")
    Dim cbScript As String = "function " + ApSConfigAHS.CB_CB2Server + "(message, context){" + cbReference + ";}"
    Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), ApSConfigAHS.CB_CB2Server, cbScript, True)
    sMsg = Request("MSG")
    oNetwork = Me.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
    Me.Title = oNetwork.TagName & ". " & sMsg

    'Dim m_checkAvailabilityCallback As String = Page.ClientScript.GetCallbackEventReference(Me, "message", ApSConfigAHS.CB_CBGeneralServerProc, "ctx", True)
    'Dim cbScriptCheckAvailability As String = "function  cbCheckAvailability(message,ctx) " & _
    '                "{" & m_checkAvailabilityCallback & ";" & "}"
    'Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "cbCheckAvailability", cbScriptCheckAvailability, True)

    'Dim m_addToCartMultipleCallback As String = Page.ClientScript.GetCallbackEventReference(Me, "message", ApSConfigAHS.CB_CBGeneralServerProc, "ctx", True)
    'Dim cbScriptAddToCartMultiple As String = "function  cbAddToCartMultiple(message,ctx) " & _
    '                "{" & m_addToCartMultipleCallback & ";" & "}"
    'Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "cbAddToCartMultiple", cbScriptAddToCartMultiple, True)

    'Dim m_getVariableListMultipleCallback As String = Page.ClientScript.GetCallbackEventReference(Me, "message", ApSConfigAHS.CB_CBGeneralServerProc, "ctx", True)
    'Dim cbScriptGetVariableListMultiple As String = "function  cbGetVariableList(message,ctx) " & _
    '                "{" & m_getVariableListMultipleCallback & ";" & "}"
    'Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "cbGetVariableList", cbScriptGetVariableListMultiple, True)


  End Sub
  '/ <summary>
  '/ Common method for calling error page, passing specific parameters and messages
  '/ </summary>
  Private Sub callErrorPage(ByVal errorMessage As String, ByVal exception As Exception)
    Session("ErrorMessage") = errorMessage
    Session("Error") = exception
    Page.Response.Redirect("ErrorPage.aspx", True)
  End Sub 'callErrorPage

  ''' <summary>
  ''' Get all variables.
  ''' </summary>
  ''' <returns></returns>
  ''' <remarks></remarks>
  Public Function LoadVariablesM() As String
    Dim ds As Long = DateTime.Now.Ticks
    ' construct a SQL query to get the list of ALL the variables measured for selected network
    Dim stationCount As Integer = -1
    Dim varName, varCode As String
    Dim SiteCodesList As String = ""
    Dim myConn As SqlConnection = Nothing
    Dim myCmd As SqlCommand = Nothing
    Dim myReader As SqlDataReader = Nothing
    Dim isSiteCodesAvailable As Boolean = False
    Dim sqlStr2 As String = ""
    'Dim networkId As String = "2" ' default 2, NWIS
    Dim oNetwork As HISNetwork
    Dim sCon As String
    Dim sReturn As String = ""
    Dim n As Integer
    Dim sb As StringBuilder = New StringBuilder

    Try
      oNetwork = Me.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
      sCon = oNetwork.DBConnection    'ConfigurationManager.ConnectionStrings(ApSConfigAHS.K_ODEConn).ConnectionString
      'networkId = ApSConfigAHS.GetNetworkID(oNetwork.Name)
      myConn = New SqlConnection
      myConn.ConnectionString = sCon
      myCmd = New SqlCommand
      myCmd.CommandText = ApSConfigAHS.QueryVariables_SQLQUERY_NETWORK_VARIABLES
      myCmd.CommandType = CommandType.Text
      myCmd.CommandTimeout = ApSConfigAHS.CMD_TimeOut
      'Dim networkIdParam As SqlParameter = New SqlParameter
      'networkIdParam.ParameterName = "@networkId"
      'networkIdParam.SqlDbType = SqlDbType.Int
      'networkIdParam.Size = 50
      'networkIdParam.Direction = ParameterDirection.Input
      'networkIdParam.Value = networkId
      'myCmd.Parameters.Add(networkIdParam)
      myCmd.Connection = myConn
      myCmd.Connection.Open()
      myReader = myCmd.ExecuteReader()
      n = 0
      While myReader.Read()
        Try
          varCode = myReader(ApSConfigAHS.FD_VARIABLECODE).ToString.Trim     ' "VariableCode"
          varName = myReader(ApSConfigAHS.FD_VARIABLENAME).ToString.Trim     ' "VariableName"
          If ((varCode.Length <> 0) And (varName.Length <> 0)) Then
            If n = 0 Then
              sb.Append(varCode & ApSConfigAHS.K_Sep2 & varName)
              'sReturn = varCode & ApSConfigAHS.K_Sep2 & varName
            Else
              sb.Append(ApSConfigAHS.K_PP & varCode & ApSConfigAHS.K_Sep2 & varName)
              'sReturn = sReturn & ApSConfigAHS.K_PP & varCode & ApSConfigAHS.K_Sep2 & varName
            End If
            n = n + 1
          End If
        Catch ex As Exception
        End Try
      End While
      sReturn = sb.ToString
    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("LoadVariablesM:" & ex.Message & ", " & ex.StackTrace, True, True, False)
      End If
      selectedSiteCount = -1
      sReturn = "<error>" & ex.Message & ", " & ex.StackTrace & "</error>"
    Finally
      If Not myCmd Is Nothing Then
        myCmd.Dispose()
      End If
      If Not myConn Is Nothing Then
        If ((myConn.State = ConnectionState.Open) OrElse (myConn.State = ConnectionState.Connecting) OrElse (myConn.State = ConnectionState.Broken)) Then
          myConn.Close()
        End If
        myConn.Dispose()
      End If

      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogDSTime) = ApSConfigAHS.DebugType.LogDSTime) Then
        ApSConfigAHS.Write2Log("LoadVariablesM:", True, ds, False)
      End If
    End Try
    Return sReturn
  End Function
  Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
    Return RaiseCallbackEvent2(_callbackArg)
  End Function
  Public Overridable Function RaiseCallbackEvent2(ByVal responseString As String) As String
    ' break out the responseString into a querystring
    Dim keyValuePairs As Array = responseString.Split("&".ToCharArray())
    Dim m_queryString As New NameValueCollection()
    Dim keyValue() As String
    Dim response As String = ""
    If keyValuePairs.Length > 0 Then
      Dim i As Integer
      For i = 0 To keyValuePairs.Length - 1
        keyValue = keyValuePairs.GetValue(i).ToString().Split("=".ToCharArray())
        m_queryString.Add(keyValue(0), keyValue(1))
      Next i
    Else
      keyValue = responseString.Split("=".ToCharArray())
      If keyValue.Length > 0 Then
        m_queryString.Add(keyValue(0), keyValue(1))
      End If
    End If ' isolate control type and mode
    Dim controlType As String = m_queryString(ApSConfigAHS.CB_ControlType)   ' "ControlType")
    Dim eventArg As String = m_queryString(ApSConfigAHS.CB_EventArg)         ' "EventArg")
    Dim eventVal As String = m_queryString(ApSConfigAHS.CB_EventVal)
    Dim arrSiteCodes() As String
    Dim oNetwork As HISNetwork
    Dim n As Integer
    oNetwork = Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
    Select Case controlType
      Case ApSConfigAHS.CB_Control_Type_HIS
        Select Case eventArg
          Case ApSConfigAHS.VARIABLE_MATCH_REQUEST
            response = getVariableMatchList(eventVal)
          Case ApSConfigAHS.CHECK_AVAILABILITY_REQUEST
            arrSiteCodes = ApSConfigAHS.GetSelectedSiteCodes(Me.Page)
            If ((arrSiteCodes Is Nothing) OrElse (arrSiteCodes.Length = 0)) Then
              '..intOIDs = ApSConfigAHS.GetOIDsInMapExtent(me.Page, 
              arrSiteCodes = GetSiteCodesByMapExtent(oNetwork.LayerName, oNetwork.SiteCodeField)
            End If
            If (Not arrSiteCodes Is Nothing) Then
              n = arrSiteCodes.Length
              If (n > ApSConfigAHS.MaxNumberOfSites) Then
                response = ApSConfigAHS.CB_CBShowMsg & ApSConfigAHS.K_KVSep & "Too many features are selected. " & ApSConfigAHS.KS_NL & "Max of " & ApSConfigAHS.MaxNumberOfSites & " selected features are allowed." & ApSConfigAHS.KS_NL & "You have selected " & n & " features." & ApSConfigAHS.KS_NL & ApSConfigAHS.KS_NL & "Network" & ApSConfigAHS.K_ConfirmSep & oNetwork.TagName & " [LayerName" & ApSConfigAHS.K_ConfirmSep & oNetwork.LayerName & "]"
              Else
                response = CheckVariableAvailability(eventVal, arrSiteCodes)
                response = "FUNCTIONRETURN" & ApSConfigAHS.K_KVSep & response
              End If
            End If
          Case ApSConfigAHS.ADDTOCART_MULTIPLE_REQUEST
            response = AddToCartDBMultiple(eventVal)
          Case "LoadVariablesM"
            response = LoadVariablesM()
          Case Else

        End Select
      Case Else

    End Select

    Return response
  End Function
  Private Function GetSiteCodesByMapExtent(ByVal LayerName As String, ByVal SiteCodeFieldName As String) As String()
    Dim arrSiteCodes() As String
    Dim sb As StringBuilder = New StringBuilder
    Dim pGISServerConnection As ESRI.ArcGIS.Server.IGISServerConnection
    Dim hostName As String
    Dim pServerObjectManager As ESRI.ArcGIS.Server.IServerObjectManager
    Dim pServerContext As ESRI.ArcGIS.Server.IServerContext = Nothing
    Dim pServerObject As ESRI.ArcGIS.Server.IServerObject
    Dim pMapServer As ESRI.ArcGIS.Carto.IMapServer
    Dim pMapServerObjects As ESRI.ArcGIS.Carto.IMapServerObjects
    Dim pMap As ESRI.ArcGIS.Carto.IMap
    Dim pMapPoly As ESRI.ArcGIS.ADF.Web.Geometry.Envelope
    Dim pSf As ESRI.ArcGIS.Geodatabase.SpatialFilter
    Dim pFCursor As IFeatureCursor
    Dim pFeature As IFeature = Nothing
    Dim s As String
    Dim FieldIndex As Integer
    Try
      pGISServerConnection = New ESRI.ArcGIS.Server.GISServerConnection
      hostName = Me.Page.Session(ApSConfigAHS.KS_HOSTNAME)
      pGISServerConnection.Connect(hostName)
      pServerObjectManager = pGISServerConnection.ServerObjectManager
      pServerContext = pServerObjectManager.CreateServerContext(ApSConfigAHS.MapServiceName, "MapServer")
      pServerObject = pServerContext.ServerObject
      pMapServer = pServerObject
      pMapServerObjects = pMapServer
      pMap = pMapServerObjects.Map(pMapServer.DefaultMapName)

      Dim pFLayer As IFeatureLayer = ApSConfigAHS.GetLayerByName(pMap, LayerName, False)  '   GetSelectedFeatureLayer(pMap, LayerName)
      Dim pFeatureClass As IFeatureClass = pFLayer.FeatureClass
      'Debug.WrtieLine(pFeatureClass.FeatureCount(Nothing))

      pMapPoly = CType(Me.Page.Session(ApSConfigAHS.CURRENT_MAP_EXTENT), ESRI.ArcGIS.ADF.Web.Geometry.Envelope)
            pSf = New ESRI.ArcGIS.Geodatabase.SpatialFilter

      pSf.Geometry = ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.Converter.ToIEnvelope(pMapPoly, pServerContext)
      pSf.GeometryField = pFeatureClass.ShapeFieldName
      pSf.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects
      FieldIndex = pFeatureClass.Fields.FindField(SiteCodeFieldName)
      If (FieldIndex < 0) Then
        If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
          ApSConfigAHS.Write2Log("GetSiteCodesByMapExtent:" & SiteCodeFieldName & " does not exist in " & LayerName, True, True, False)
        End If
      End If
      pFCursor = pFeatureClass.Search(pSf, True)
      pFeature = pFCursor.NextFeature
      Do Until pFeature Is Nothing
        s = "" & pFeature.Value(FieldIndex)
        If (sb.Length = 0) Then
          sb.Append(s)
        Else
          sb.Append(ApSConfigAHS.K_PP & s)
        End If
        pFeature = pFCursor.NextFeature
      Loop
      s = sb.ToString
      arrSiteCodes = s.Split(ApSConfigAHS.K_PP)

    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("GetSiteCodesByMapExtent:" & ex.Message & ", " & ex.StackTrace, True, True, False)
      End If
      arrSiteCodes = Nothing
    Finally
      If Not pServerContext Is Nothing Then
        pServerContext.ReleaseContext()
        pServerContext = Nothing
      End If
    End Try
    Return arrSiteCodes

  End Function
  Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
    _callbackArg = eventArgument
  End Sub
  ''' <summary>
  '''  Returns matching list of stations that measure selected input variable.
  ''' </summary>
  ''' <param name="variableCodeInfo"></param>
  ''' <returns>List of stations measuring input variable.</returns>
  ''' <remarks></remarks>
  Private Function CheckVariableAvailability(ByVal variableCodeInfo As String, ByVal SiteCodesListArray() As String) As String
    'Input Argument : variableCode:VariableName, 
    '  modified, zye.
    '..(1) @Param replaced by Variable replacement, @param did not work for multiple linked tables.
    '..(2) Create multiple Where statement so that the SQL will not be too long to execute.  Number of SiteCode allow
    Dim ds As Long = Date.Now.Ticks
    Dim resultSiteCodes As String = ""
    Dim myConn As SqlConnection = Nothing
    Dim myCmd As SqlCommand = Nothing
    Dim myReader As SqlDataReader = Nothing
    Dim SiteCodesList As String = ""
    Dim stationCount As Integer
    Dim isSiteCodesPresent As Boolean = False
    Dim i As Integer = 0
    Dim strResponse As String = ""

    ' get the list of selcted station site codes from Session
    Dim oNetwork As HISNetwork
    Dim activeLayer As String   'CType(Me.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK), String)
    Dim NetworkName As String = ""
    'Dim NetworkId As String = ""
    Dim variableCode As String
    Dim variableName As String
    Dim matchingSiteCount As Integer = 0
    Dim strSql As String = ""
    Dim arSiteCodes As ArrayList = New ArrayList()
    Dim s As String
    Dim sName As String
    Dim nStations As Integer = ApSConfigAHS.QueryInterval     '..nStations at a time to construct the SiteCodesList for SQL.
    Dim sb As StringBuilder = New StringBuilder
    Dim sbResponse As StringBuilder = New StringBuilder
    Dim SQLBase As String
    Dim dt1, dt1Curr, dt2, dt2Curr As DateTime
    Try
      If ((Not SiteCodesListArray Is Nothing) AndAlso (SiteCodesListArray.Length > 0)) Then
        oNetwork = Me.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
        NetworkName = oNetwork.Name
        'NetworkId = ApSConfigAHS.GetNetworkID(NetworkName)
        'varCodeInfoArray = variableCodeInfo.Split(":")
        variableCode = variableCodeInfo   'varCodeInfoArray(0)
        variableName = ApSConfigAHS.GetVariableName(oNetwork, variableCode)  '    varCodeInfoArray(1)
        myConn = New SqlConnection
        myConn.ConnectionString = oNetwork.DBConnection   'ConfigurationManager.ConnectionStrings(ApSConfigAHS.K_ODEConn).ConnectionString
        activeLayer = oNetwork.LayerName
        SQLBase = "SELECT SiteCode, SiteName, VariableID, BeginDateTime, EndDateTime, ValueCount "
        SQLBase &= " FROM SeriesCatalog WHERE (VariableID IN (SELECT  VariableID  FROM  Variables "
        SQLBase &= " WHERE (VariableCode=" & variableCode & "))) AND (SiteCode IN ("

        'SQLBase = "SELECT SiteCode, SiteName, VariableID, BeginDateTime, EndDateTime, ValueCount "
        'SQLBase &= " FROM SeriesCatalog WHERE (VariableID IN (SELECT  VariableID  FROM  Variables "
        'SQLBase &= " WHERE (networkId=" & NetworkId & ") AND (VariableCode=" & variableCode & "))) AND (SiteCode IN ("
        dt1Curr = DateTime.Parse("01/01/1900 12:00 PM")
        dt2Curr = DateTime.Now

        stationCount = SiteCodesListArray.Length
        SiteCodesList = ""
        For i = 0 To stationCount - 1
          If (sb.Length = 0) Then
            sb.Append("'" & SiteCodesListArray(i) & "'")
          Else
            sb.Append(",'" & SiteCodesListArray(i) & "'")
          End If
          If (((i Mod nStations) = 0) AndAlso (i <> 0)) Then
            Try
              SiteCodesList = sb.ToString
              SiteCodesList = SiteCodesList & "))"
              strSql = SQLBase & SiteCodesList
              myCmd = New SqlCommand
              '   System.Diagnostics.Debug.WriteLine("varcode: " + variableCode)
              myCmd.CommandText = strSql
              myCmd.CommandType = CommandType.Text
              myCmd.Connection = myConn
              myCmd.Connection.Open()
              myReader = myCmd.ExecuteReader()
              While myReader.Read()
                Try
                  s = myReader(ApSConfigAHS.FD_SiteCode).Trim()
                  If (s <> "") Then
                    If (Not arSiteCodes.Contains(s)) Then
                      arSiteCodes.Add(s)
                      sName = myReader(ApSConfigAHS.FD_SiteName).Trim()
                      If (sName <> "") Then
                        sName = ApSConfigAHS.MakeMsg4Web(sName)
                      End If
                      If sbResponse.Length = 0 Then
                        sbResponse.Append(myReader(ApSConfigAHS.FD_SiteCode).Trim() & ApSConfigAHS.K_AT & sName & ApSConfigAHS.K_AT & CStr(myReader(ApSConfigAHS.FD_ValueCount).ToString))
                      Else
                        sbResponse.Append(ApSConfigAHS.K_PP & myReader(ApSConfigAHS.FD_SiteCode).Trim() & ApSConfigAHS.K_AT & sName & ApSConfigAHS.K_AT & CStr(myReader(ApSConfigAHS.FD_ValueCount).ToString))
                      End If
                      'resultSiteCodes &= myReader(ApSConfigAHS.FD_SiteCode).Trim() & "@" & myReader(ApSConfigAHS.FD_SiteName).Trim() & "@" & CStr(myReader(ApSConfigAHS.FD_ValueCount).ToString) & ApSConfigAHS.K_PP
                      dt1 = myReader.GetSqlDateTime(3)
                      If DateTime.Compare(dt1Curr, dt1) > 0 Then
                        dt1Curr = dt1
                      End If
                      dt2 = myReader.GetSqlDateTime(4)
                      If DateTime.Compare(dt2Curr, dt2) < 0 Then
                        dt2Curr = dt2
                      End If
                      matchingSiteCount = matchingSiteCount + 1
                    End If
                  End If
                Catch ex As Exception
                End Try
              End While
            Catch ex As Exception
              If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
                ApSConfigAHS.Write2Log("CheckVariableAvailability:" & ex.Message & ", " & ex.StackTrace & vbCrLf & "SiteCode.length=" & SiteCodesList.Length & ", " & SiteCodesList, True, -1, False)
              End If
            Finally
              If (Not (myConn Is Nothing) AndAlso (myConn.State = ConnectionState.Open)) Then
                myConn.Close()
              End If
            End Try
            sb = New StringBuilder
          End If
        Next
        If (sb.Length > 0) Then
          Try
            SiteCodesList = sb.ToString
            SiteCodesList = SiteCodesList & "))"
            strSql = SQLBase & SiteCodesList
            myCmd = New SqlCommand
            '   System.Diagnostics.Debug.WriteLine("varcode: " + variableCode)
            myCmd.CommandText = strSql
            myCmd.CommandType = CommandType.Text
            myCmd.Connection = myConn
            myCmd.Connection.Open()
            myReader = myCmd.ExecuteReader()
            While myReader.Read()
              Try
                s = myReader(ApSConfigAHS.FD_SiteCode).Trim()
                If (s <> "") Then
                  If (Not arSiteCodes.Contains(s)) Then
                    arSiteCodes.Add(s)
                    sName = myReader(ApSConfigAHS.FD_SiteName).Trim()
                    If (sName <> "") Then
                      sName = ApSConfigAHS.MakeMsg4Web(sName)
                    End If
                    If sbResponse.Length = 0 Then
                      s = ApSConfigAHS.MakeMsg4Web(s)
                      sbResponse.Append(myReader(ApSConfigAHS.FD_SiteCode).Trim() & ApSConfigAHS.K_AT & sName & ApSConfigAHS.K_AT & CStr(myReader(ApSConfigAHS.FD_ValueCount).ToString))
                    Else
                      sbResponse.Append(ApSConfigAHS.K_PP & myReader(ApSConfigAHS.FD_SiteCode).Trim() & ApSConfigAHS.K_AT & sName & ApSConfigAHS.K_AT & CStr(myReader(ApSConfigAHS.FD_ValueCount).ToString))
                    End If
                    'resultSiteCodes += myReader(ApSConfigAHS.FD_SiteCode).Trim() & "@" & myReader(ApSConfigAHS.FD_SiteName).Trim() & "@" & CStr(myReader(ApSConfigAHS.FD_ValueCount).ToString) & "|"
                    ' resultSiteCodes += myReader.GetString(0).Trim() + "@" + myReader.GetString(1).Trim() + "@" + CStr(myReader.GetInt32(5)) + "|"
                    dt1 = myReader.GetSqlDateTime(3)
                    If DateTime.Compare(dt1Curr, dt1) > 0 Then
                      dt1Curr = dt1
                    End If
                    dt2 = myReader.GetSqlDateTime(4)
                    If DateTime.Compare(dt2Curr, dt2) < 0 Then
                      dt2Curr = dt2
                    End If
                    matchingSiteCount = matchingSiteCount + 1
                  End If
                End If
              Catch ex As Exception

              End Try
            End While
          Catch ex As Exception
            If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
              ApSConfigAHS.Write2Log("CheckVariableAvailability:" & ex.Message & ", " & ex.StackTrace & vbCrLf & "SiteCode.length=" & SiteCodesList.Length & ", " & SiteCodesList, True, -1, False)
            End If
          Finally
            If ((Not myConn Is Nothing) AndAlso (myConn.State = ConnectionState.Open)) Then
              myConn.Close()
            End If
          End Try
        End If
        resultSiteCodes = sbResponse.ToString
        'Me.Page.Session(ApSConfigAHS.SELECTED_STATION_LIST_SUBSET) = resultSiteCodes
        Dim strMatchingCount As String = CStr(matchingSiteCount)
        Dim strTotalSiteCount As String = CStr(stationCount)
        strResponse = strMatchingCount & "," & strTotalSiteCount & "???" + NetworkName.ToUpper & ApSConfigAHS.K_Sep2 & variableCode & ApSConfigAHS.K_Sep2 & variableName & ApSConfigAHS.K_Sep2 & CStr(dt1Curr) & ApSConfigAHS.K_Sep2 & CStr(dt2Curr) & ApSConfigAHS.K_Sep2 & resultSiteCodes
      End If

    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("CheckVariableAvailability:" & ex.Message & ", " & ex.StackTrace, True, True, False)
      End If
      strResponse = "<error>" + ex.Message + "</error>"

    Finally
      If Not myCmd Is Nothing Then
        myCmd.Dispose()
      End If
      If Not myConn Is Nothing Then
        If ((myConn.State = ConnectionState.Open) OrElse (myConn.State = ConnectionState.Connecting) OrElse (myConn.State = ConnectionState.Executing) OrElse (myConn.State = ConnectionState.Fetching)) Then
          myConn.Close()
          myConn.Dispose()
        End If
      End If
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogDSTime) = ApSConfigAHS.DebugType.LogDSTime) Then
        ApSConfigAHS.Write2Log("CheckVariableAvailability: ", True, ds, False)
      End If
    End Try

    ' matchingSiteCount,selectedSiteCount???network~varcode~varname~begDate~endDate~siteCode1@name1@count1|siteCode2@name2@count2|siteCode3@name3@count3|
    Return strResponse
  End Function
  Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete

  End Sub
  Private Function AddToCartDBMultiple(ByVal siteCodeInfo As String) As String
    'network~varcode~varname~begDate~endDate~siteCode1@name1@count1|siteCode2@name2@count2|siteCode3@name3@count3
    Dim retVal As String = Nothing
    Dim myConn As SqlConnection = Nothing
    Dim myCmd As SqlCommand = Nothing
    Dim _dTable As DataTable = Nothing
    Dim nRecs As Integer = 0
    Dim nAdded As Integer
    Try
      '..Need to be modified so that one record at a time is added so that the existence of a rec can be checked.
      '_dTable = CreateDataTableSiteCodeInfo(siteCodeInfo, nRecs)
      'SqlBulkUploadToCart(_dTable)
      'retVal = SqlBulkUploadToCart(_dTable)
      nAdded = SQLUploadToCart(siteCodeInfo, nRecs)
      If (nRecs = nAdded) Then
        retVal = ApSConfigAHS.CB_CBShowMsg & ApSConfigAHS.K_KVSep & CStr(nAdded) & " of " & nRecs & " item(s) added to the data cart."
      Else
        retVal = ApSConfigAHS.CB_CBShowMsg & ApSConfigAHS.K_KVSep & CStr(nAdded) & " item(s) added to the data cart." & ApSConfigAHS.KS_NL & (nRecs - nAdded) & " of " & nRecs & " item(s) already exist in the data cart."
      End If
    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("AddToCartDBMultiple:" & ex.Message & "," & ex.StackTrace, True, , False)
      End If
      retVal = "<error>" + ex.Message + "</error>"
    Finally

    End Try
    Return retVal
  End Function


  Private Function CreateDataTableSiteCodeInfo(ByVal siteCodeInfo_ As String, ByRef numOfSites As Integer) As DataTable
    '..Modified coding, zye.
    '(0) - NetworkName
    '(1) - VariableCode
    '(2) - VariableName
    '(3) - StartTime
    '(4) - EndTime
    '(5) - SiteCodes (Seperated by |)
    ' input structure:
    ' network~varcode~varname~begDate~endDate~siteCode1@name1@count1|siteCode2@name2@count2|siteCode3@name3@count3
    ' ~ used as first level deliminator, and | used as 2nd level deliminator.
    Dim ds As Long = DateTime.Now.Ticks
    Dim dTable As DataTable = Nothing
    Dim Row1 As DataRow
    Dim strDataArray() As String = Nothing
    Dim siteCodesRaw() As String = Nothing
    Dim siteCodesArray() As String = Nothing
    Dim i As Integer
    Dim _network As String
    Dim _varcode As String
    Dim _varname As String
    Dim _begindt As String
    Dim _enddt As String
    Try
      strDataArray = siteCodeInfo_.Split(ApSConfigAHS.K_Sep2)
      siteCodesRaw = strDataArray(5).Split(ApSConfigAHS.K_PP)
      numOfSites = siteCodesRaw.Length

      dTable = New DataTable(ApSConfigAHS.TB_Sites) '"SiteCodesInfo")

      Dim Network As DataColumn = New DataColumn(ApSConfigAHS.FD_NETWORK) '"Network")
      Network.DataType = System.Type.GetType("System.String")
      dTable.Columns.Add(Network)

      Dim VariableCode As DataColumn = New DataColumn(ApSConfigAHS.FD_VARIABLECODE) '"VariableCode")
      VariableCode.DataType = System.Type.GetType("System.String")
      dTable.Columns.Add(VariableCode)

      Dim SiteCode As DataColumn = New DataColumn(ApSConfigAHS.FD_SiteCode)  '"SiteCode")
      SiteCode.DataType = System.Type.GetType("System.String")
      dTable.Columns.Add(SiteCode)

      Dim VariableName As DataColumn = New DataColumn(ApSConfigAHS.FD_VARIABLENAME) '"VariableName")
      VariableName.DataType = System.Type.GetType("System.String")
      dTable.Columns.Add(VariableName)


      Dim ValueCount As DataColumn = New DataColumn(ApSConfigAHS.FD_ValueCount) '"ValueCount")
      ValueCount.DataType = System.Type.GetType("System.String")
      dTable.Columns.Add(ValueCount)

      Dim BeginDate As DataColumn = New DataColumn(ApSConfigAHS.FD_BEGINDATE) '"BeginDate")
      BeginDate.DataType = System.Type.GetType("System.String")
      dTable.Columns.Add(BeginDate)

      Dim EndDate As DataColumn = New DataColumn(ApSConfigAHS.FD_ENDDATE) '"EndDate")
      EndDate.DataType = System.Type.GetType("System.String")
      dTable.Columns.Add(EndDate)

      Dim SiteName As DataColumn = New DataColumn(ApSConfigAHS.FD_SiteName) ' "SiteName")
      SiteName.DataType = System.Type.GetType("System.String")
      dTable.Columns.Add(SiteName)

      Dim SessionId As DataColumn = New DataColumn(ApSConfigAHS.FD_USESSIONID) ' "USessionID")
      SessionId.DataType = System.Type.GetType("System.String")
      dTable.Columns.Add(SessionId)

      _network = strDataArray(0)
      _varcode = strDataArray(1)
      _varname = strDataArray(2)
      _begindt = strDataArray(3)
      _enddt = strDataArray(4)
      For i = 0 To numOfSites - 1
        Try
          Row1 = dTable.NewRow()
          Row1.Item(ApSConfigAHS.FD_USESSIONID) = Session.SessionID
          Row1.Item(ApSConfigAHS.FD_NETWORK) = _network
          Row1.Item(ApSConfigAHS.FD_VARIABLECODE) = _varcode
          Row1.Item(ApSConfigAHS.FD_VARIABLENAME) = _varname
          Row1.Item(ApSConfigAHS.FD_BEGINDATE) = _begindt
          Row1.Item(ApSConfigAHS.FD_ENDDATE) = _enddt
          ' sitecode@sitename@count
          siteCodesArray = siteCodesRaw(i).Split(ApSConfigAHS.K_AT)
          Row1.Item(ApSConfigAHS.FD_SiteCode) = siteCodesArray(0)
          Row1.Item(ApSConfigAHS.FD_SiteName) = siteCodesArray(1)
          Row1.Item(ApSConfigAHS.FD_ValueCount) = siteCodesArray(2)
          dTable.Rows.Add(Row1)
        Catch ex As Exception

        End Try
      Next
    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("CreateDataTableSiteCodeInfo:" & ex.Message & ", " & ex.StackTrace, True, -1, False)
      End If
    Finally
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogDSTime) = ApSConfigAHS.DebugType.LogDSTime) Then
        ApSConfigAHS.Write2Log("CreateDataTableSiteCodeInfo:", True, ds, False)
      End If
    End Try
    Return dTable
  End Function
  ''' <summary>
  '''   Load the data into the cart.
  ''' </summary>
  ''' <param name="siteCodeInfo_"></param>
  ''' <param name="numOfSites"></param>
  ''' <returns></returns>
  ''' <remarks></remarks>
  Private Function SQLUploadToCart(ByVal siteCodeInfo_ As String, ByRef numOfSites As Integer) As Integer
    Dim ds As Long = DateTime.Now.Ticks
    Dim myConn As SqlConnection = Nothing
    Dim myCmd As SqlCommand = Nothing
    Dim sqlBulkCopy As SqlBulkCopy = Nothing
    Dim s As String = ""
    Dim sCountBase As String
    Dim sDeleteBase As String
    Dim sInsertBase As String
    Dim sWhereBase As String
    Dim sSQLCount As String
    Dim sSQLInsert As String
    'Dim sSQLDelete As String
    Dim sWhereDate As String  '..with start/end date
    Dim sWhere As String
    Dim sSiteCode As String
    Dim sSiteName As String
    Dim sValueCount As String
    '..Modified coding, zye.
    '(0) - NetworkName
    '(1) - VariableCode
    '(2) - VariableName
    '(3) - StartTime
    '(4) - EndTime
    '(5) - SiteCodes (Seperated by |)
    ' input structure:
    ' network~varcode~varname~begDate~endDate~siteCode1@name1@count1|siteCode2@name2@count2|siteCode3@name3@count3
    ' ~ used as first level deliminator, and | used as 2nd level deliminator.
    Dim strDataArray() As String = Nothing
    Dim siteCodesRaw() As String = Nothing
    Dim siteCodesArray() As String = Nothing

    Dim i As Integer
    Dim _network As String
    Dim _varcode As String
    Dim _varname As String
    Dim _begindt As String
    Dim _enddt As String
    Dim n As Integer
    Dim nExists As Integer = 0
    Dim bCanAdd As Boolean
    Dim sUserName As String
    Try
      strDataArray = siteCodeInfo_.Split(ApSConfigAHS.K_Sep2)
      siteCodesRaw = strDataArray(5).Split(ApSConfigAHS.K_PP)
      numOfSites = siteCodesRaw.Length
      sUserName = Context.User.Identity.Name
      If (sUserName = "") Then
        sUserName = ApSConfigAHS.UnknowUser
      End If
      _network = strDataArray(0)
      _varcode = strDataArray(1)
      _varname = strDataArray(2)
      _begindt = strDataArray(3)
      _enddt = strDataArray(4)
      myConn = New SqlConnection
      'myConn.ConnectionString = ConfigurationManager.ConnectionStrings(ApSConfigAHS.K_ODEConn).ConnectionString
      myConn.ConnectionString = ConfigurationManager.ConnectionStrings(ApSConfigAHS.DB_AppDB).ConnectionString
      myCmd = New SqlCommand
      myCmd.Connection = myConn
      myConn.Open()
      sDeleteBase = "Delete FROM " & ApSConfigAHS.TB_MYSELECT
      sCountBase = "SELECT COUNT(*) FROM " & ApSConfigAHS.TB_MYSELECT
      sWhereBase = " WHERE " & ApSConfigAHS.FD_NETWORK & "='" & _network & "' AND " & _
        ApSConfigAHS.FD_VARIABLECODE & "='" & _varcode & "' AND " & _
        ApSConfigAHS.FD_USESSIONID & "='" & Session.SessionID & "'" & " AND " & ApSConfigAHS.FD_SiteCode & "='"
      sInsertBase = "INSERT INTO " & ApSConfigAHS.TB_MYSELECT & "(" & ApSConfigAHS.FD_USESSIONID & "," & _
        ApSConfigAHS.FD_NETWORK & "," & ApSConfigAHS.FD_VARIABLENAME & "," & ApSConfigAHS.FD_VARIABLECODE & "," & _
        ApSConfigAHS.FD_UserName & "," & ApSConfigAHS.FD_BEGINDATE & "," & ApSConfigAHS.FD_ENDDATE & "," & _
        ApSConfigAHS.FD_SiteName & ", " & ApSConfigAHS.FD_SiteCode & "," & ApSConfigAHS.FD_ValueCount & ") VALUES ('" & _
        Session.SessionID & "','" & _network & "','" & _varname & "','" & _varcode & "','" & sUserName & "','" & _begindt & "','" & _
       _enddt & "','"
      numOfSites = siteCodesRaw.Length
      For i = 0 To numOfSites - 1
        Try
          siteCodesArray = siteCodesRaw(i).Split(ApSConfigAHS.K_AT)
          sSiteCode = siteCodesArray(0)
          sSiteName = siteCodesArray(1)
          sValueCount = siteCodesArray(2)
          sWhere = sWhereBase & sSiteCode & "'"
          sSQLCount = sCountBase & sWhere
          myCmd.CommandType = CommandType.Text
          myCmd.CommandText = sCountBase & sWhere
          n = myCmd.ExecuteScalar()
          If (n > 0) Then
            bCanAdd = False
            sWhereDate = sWhere & " AND " & ApSConfigAHS.FD_BEGINDATE & "='" & _begindt & "' AND " & ApSConfigAHS.FD_ENDDATE & "='" & _enddt & "'"
            myCmd.CommandText = sCountBase & sWhereDate
            n = myCmd.ExecuteScalar()
            If (n > 0) Then
              bCanAdd = False
            Else
              myCmd.CommandText = sDeleteBase & sWhere
              n = myCmd.ExecuteNonQuery()
              bCanAdd = True
            End If
          Else
            bCanAdd = True
          End If
          If bCanAdd = True Then
            sSQLInsert = sSiteName & "','" & sSiteCode & "'," & sValueCount & ")"
            sSQLInsert = sInsertBase & sSQLInsert
            myCmd.CommandText = sSQLInsert
            myCmd.CommandTimeout = ApSConfigAHS.CMD_TimeOut
            n = myCmd.ExecuteNonQuery()
            nExists = nExists + 1
          End If
          'Row1.Item(ApSConfigAHS.FD_SiteCode) = siteCodesArray(0)
          'Row1.Item(ApSConfigAHS.FD_SiteName) = siteCodesArray(1)
          'Row1.Item(ApSConfigAHS.FD_ValueCount) = siteCodesArray(2)
        Catch ex As Exception
          If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
            ApSConfigAHS.Write2Log("SqlUploadToCart:" & ex.Message & ", " & ex.StackTrace, True, ds, False)
          End If
        End Try
      Next
    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("SqlUploadToCart:", True, ds, False)
      End If
    Finally
      If Not myCmd Is Nothing Then
        myCmd.Dispose()
      End If
      If Not myConn Is Nothing Then
        If ((myConn.State = ConnectionState.Open) OrElse (myConn.State = ConnectionState.Connecting) OrElse (myConn.State = ConnectionState.Broken)) Then
          myConn.Close()
        End If
        myConn.Dispose()
      End If
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogDSTime) = ApSConfigAHS.DebugType.LogDSTime) Then
        ApSConfigAHS.Write2Log("SqlBulkUploadToCart:", True, ds, False)
      End If
    End Try
    Return nExists

  End Function

  Private Function SqlBulkUploadToCart(ByVal inputDt As DataTable) As String
    Dim ds As Long = DateTime.Now.Ticks
    Dim myConn As SqlConnection = Nothing
    Dim mySqlTrans As SqlTransaction = Nothing
    Dim myCmd As SqlCommand = Nothing
    Dim sqlBulkCopy As SqlBulkCopy = Nothing
    Dim s As String = ""
    Try
      myConn = New SqlConnection
      '      myConn.ConnectionString = ConfigurationManager.ConnectionStrings(ApSConfigAHS.K_ODEConn).ConnectionString
      myConn.ConnectionString = ConfigurationManager.ConnectionStrings(ApSConfigAHS.DB_AppDB).ConnectionString
      sqlBulkCopy = New SqlBulkCopy(myConn.ConnectionString, SqlBulkCopyOptions.UseInternalTransaction)
      sqlBulkCopy.DestinationTableName = ApSConfigAHS.TB_MYSELECT

      sqlBulkCopy.ColumnMappings.Add(ApSConfigAHS.FD_USESSIONID, ApSConfigAHS.FD_USESSIONID)
      sqlBulkCopy.ColumnMappings.Add(ApSConfigAHS.FD_NETWORK, ApSConfigAHS.FD_NETWORK)
      sqlBulkCopy.ColumnMappings.Add(ApSConfigAHS.FD_SiteName, ApSConfigAHS.FD_SiteName)
      sqlBulkCopy.ColumnMappings.Add(ApSConfigAHS.FD_SiteCode, ApSConfigAHS.FD_SiteCode)
      sqlBulkCopy.ColumnMappings.Add(ApSConfigAHS.FD_VARIABLENAME, ApSConfigAHS.FD_VARIABLENAME)
      sqlBulkCopy.ColumnMappings.Add(ApSConfigAHS.FD_VARIABLECODE, ApSConfigAHS.FD_VARIABLECODE)
      sqlBulkCopy.ColumnMappings.Add(ApSConfigAHS.FD_ValueCount, ApSConfigAHS.FD_ValueCount)
      sqlBulkCopy.ColumnMappings.Add(ApSConfigAHS.FD_BEGINDATE, ApSConfigAHS.FD_BEGINDATE)
      sqlBulkCopy.ColumnMappings.Add(ApSConfigAHS.FD_ENDDATE, ApSConfigAHS.FD_ENDDATE)
      sqlBulkCopy.WriteToServer(inputDt)

    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("SqlBulkUploadToCart:", True, ds, False)
      End If
      s = ex.Message & ", " & ex.ToString
    Finally
      If Not myCmd Is Nothing Then
        myCmd.Dispose()
      End If
      If Not myConn Is Nothing Then
        If ((myConn.State = ConnectionState.Open) OrElse (myConn.State = ConnectionState.Connecting) OrElse (myConn.State = ConnectionState.Executing) OrElse (myConn.State = ConnectionState.Fetching)) Then
          myConn.Close()
          myConn.Dispose()
        End If
      End If
      If Not sqlBulkCopy Is Nothing Then
        sqlBulkCopy.Close()
        sqlBulkCopy = Nothing
      End If
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogDSTime) = ApSConfigAHS.DebugType.LogDSTime) Then
        ApSConfigAHS.Write2Log("SqlBulkUploadToCart:", True, ds, False)
      End If
    End Try
    Return s
  End Function

  Private Function GetSelectedFeatureLayer(ByVal pMap_ As IMap) As IFeatureLayer
    Dim pFlayer As IFeatureLayer = Nothing
    Dim iLayer As ILayer = Nothing
    Try
      Dim oNetwork As HISNetwork
      oNetwork = Me.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
      Dim selectedLayerName As String = oNetwork.LayerName
      Dim pLayerEnum As IEnumLayer = pMap_.Layers
      iLayer = pLayerEnum.Next
      While Not iLayer Is Nothing
        If (iLayer.Name.Contains(selectedLayerName)) Then
          pFlayer = iLayer
          Exit While
        End If
        iLayer = pLayerEnum.Next
      End While
    Catch ex As Exception

    End Try
    Return pFlayer
  End Function

  Public Function GetSiteIndexFromCursor(ByVal pFCur As IFeatureCursor, ByVal sFieldName As String) As Integer
    Dim i As Integer
    Dim icnt As Integer
    Dim sName As String
    Dim iIndex As Integer = -1
    Try
      sName = sFieldName.ToLower.Trim
      icnt = pFCur.Fields.FieldCount
      For i = 0 To icnt - 1
        If (pFCur.Fields.Field(i).Name.ToLower = sName) Then
          iIndex = i
          Exit For
        End If

      Next

    Catch ex As Exception

    End Try

    Return iIndex

  End Function

  Private Function getVariableMatchList(ByVal _varName As String) As String
    Dim varMatchList As String = ""
    Dim myConn As SqlConnection = Nothing
    Dim myCmd As SqlCommand = Nothing
    Dim myReader As SqlDataReader = Nothing
    Dim isSiteCodesAvailable As Boolean = False
    Dim varName, varCode As String
    Dim count As Integer = 0
    Dim sqlStr2 As String = ""
    Dim networkId As String = "2" ' default 2, NWIS
    Dim oNetwork As HISNetwork
    Dim sConnString As String

    Try
      oNetwork = Me.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
      Dim network As String = oNetwork.Name
      sConnString = oNetwork.DBConnection   'ConfigurationManager.ConnectionStrings(ApSConfigAHS.K_ODEConn).ConnectionString
      ''SiteCodesList = "'14815', '198621'"
      myConn = New SqlConnection
      myConn.ConnectionString = sConnString
      myCmd = New SqlCommand

      Try
        networkId = Convert.ToInt32(ApSConfigAHS.GetFieldValue(sConnString, ApSConfigAHS.TB_Network, ApSConfigAHS.FD_NetworkName, "'" & network & "'", ApSConfigAHS.FD_NetworkID, True, ","))
      Catch ex As Exception
        networkId = 2
      End Try
      sqlStr2 = "SELECT  distinct VariableCode, VariableName FROM " & ApSConfigAHS.TB_Variables & " WHERE VariableCode IS NOT NULL AND VariableName IS NOT NULL AND networkId =" + networkId
      System.Diagnostics.Debug.WriteLine("Sql Str : " + sqlStr2)

      myCmd.CommandText = sqlStr2
      myCmd.CommandType = CommandType.Text
      myCmd.Connection = myConn
      myCmd.Connection.Open()
      myReader = myCmd.ExecuteReader()

      While myReader.Read()
        varCode = myReader.GetString(0).Trim
        varName = myReader.GetString(1).Trim()
        If varName.ToLower.StartsWith(_varName.ToLower) Then
          varMatchList += CStr(count) + ApSConfigAHS.K_Sep2 + CStr(varCode) + ApSConfigAHS.K_Sep2 + varName + ApSConfigAHS.K_PP
          count += 1
        End If
      End While

      myReader.Close()
      myReader = Nothing
      myCmd = Nothing
      myConn.Close()

    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("GetVariableMatchList:" & ex.Message & "," & ex.StackTrace, True, , False)
      End If
      varMatchList = "<error>" + ex.Message + "</error>"
    Finally
      If Not myConn Is Nothing Then
        myConn = Nothing
      End If
    End Try

    Return varMatchList
  End Function

End Class
