Imports System.Collections.Generic
Imports ESRI.ArcGIS.ADF.Web
Imports ESRI.ArcGIS.ADF.Web.UI.WebControls
Imports ESRI.ArcGIS.ADF.Web.DataSources
Imports ESRI.ArcGIS.ADF.Connection.AGS
Imports ESRI.ArcGIS.Server
Imports ESRI.ArcGIS.ADF.ArcGISServer
Imports ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer

Imports System.IO
Imports System.IO.File
Imports System
Imports System.Drawing
Imports System.Data.SqlClient
Imports System.Xml
Imports System.Xml.XPath
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports ESRI.ArcGIS.Carto
Imports ESRI.ArcGIS.Geodatabase
Imports ESRI.ArcGIS.Geometry



Partial Class WebMapApplication
  Inherits System.Web.UI.Page
  Implements ICallbackEventHandler

  Private identify As MapIdentify
  Private m_HISIdentify As HISIdentify
  Public m_newLoad As String = "false"
  Public m_closeOutCallback As String = ""
  Public m_copyrightCallback As String = ""
  Public oActiveNetwork As HISNetwork

  Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
    Try
      If (Page.Session.IsNewSession) Then
        If (MapResourceManager1.Initialized = False) Then
          MapResourceManager1.Initialize()
        End If
        Dim mrItem As MapResourceItem
        Dim def As GISResourceItemDefinition
        Dim MapServiceHost As String = ""   'ConfigurationManager.AppSettings("MapServiceHost")
        Dim MapServiceName As String = ""   'ConfigurationManager.AppSettings("MapServiceName")
        Dim MapServiceType As String = ""   'ConfigurationManager.AppSettings("MapServiceType")
        Try
          MapServiceHost = ConfigurationManager.AppSettings("MapServiceHost")
          MapServiceName = ConfigurationManager.AppSettings("MapServiceName")
          MapServiceType = ConfigurationManager.AppSettings("MapServiceType")
        Catch ex As Exception

        End Try

        Dim sNames() As String
        Dim bViaConfig As Boolean = False
        Dim sServiceName As String
        Dim sDef As String

        If (((Not (MapServiceHost Is Nothing)) AndAlso (MapServiceHost <> "")) And (Not (MapServiceName Is Nothing)) AndAlso (MapServiceName <> "")) And (Not (MapServiceType Is Nothing) AndAlso (MapServiceType <> "")) Then
          sNames = MapServiceName.Split("@".ToCharArray())
          If (sNames.Length = 2) Then
            sServiceName = sNames(1)
          Else
            sServiceName = MapServiceName
          End If

          MapResourceManager1.ResourceItems.Clear()
          mrItem = New MapResourceItem()
          mrItem.Name = sServiceName
          '<Definition DataSourceDefinition="localhost" DataSourceType="ArcGIS Server Local" Identity="" ResourceDefinition="Layers@NYPS92" DataSourceShared="True" />
          sDef = "<Definition DataSourceDefinition=""" & MapServiceHost & """ DataSourceType=""" & MapServiceType & """ Identity=""""  ResourceDefinition=""" & MapServiceName & """ DataSourceShared=""True"" />"
          def = New GISResourceItemDefinition(sDef)
          mrItem.Parent = MapResourceManager1
          mrItem.Definition = def
          'mrItem.Transparency = "50%";
          'mrItem.DisplaySettings.Transparency = 50;
          mrItem.DisplaySettings.ImageDescriptor.TransparentBackground = True
          mrItem.DisplaySettings.ImageDescriptor.TransparentColor = System.Drawing.Color.White

          mrItem.DisplaySettings.ImageDescriptor.TransparentBackground = True
          mrItem.DisplaySettings.ImageDescriptor.TransparentColor = System.Drawing.Color.White
          '//Add resource info to map resource manager and create resources
          MapResourceManager1.ResourceItems.Add(mrItem)
          MapResourceManager1.CreateResource(mrItem)
          Map1.PrimaryMapResource = mrItem.Name
          Map1.InitializeFunctionality(mrItem)
          Toc1.InitializeFunctionality(mrItem)
          OverviewMap1.OverviewMapResource = mrItem.Name
          Magnifier1.MagnifierMapResource = mrItem.Name
        End If

        Dim mri As MapResourceItem
        Dim mapResource As MapResourceLocal = Nothing
        Dim localDataSource As GISDataSourceLocal = Nothing
        For Each mri In MapResourceManager1.ResourceItems
          If Not mri Is Nothing Then
            If TypeOf (mri.Resource) Is MapResourceLocal Then
              mapResource = CType(mri.Resource, MapResourceLocal)
              localDataSource = mapResource.DataSource
              ApSConfigAHS.MapServiceName = mapResource.Name  ' mapResource.Service
              'ApSConfigAHS.MapServiceName = mapResource.Name
              ApSConfigAHS.HostName = mri.DataSourceName
              Me.Page.Session(ApSConfigAHS.K_MAPSERVICE_NAME) = ApSConfigAHS.MapServiceName
              Me.Page.Session(ApSConfigAHS.KS_HOSTNAME) = mri.DataSourceName
              Exit For
            End If
          End If
        Next mri
        'try to add the basemap if there is one configured.
        Try
          Dim sMapHost As String = ConfigurationManager.AppSettings("BaseMapHost")
          Dim sMapType As String = ConfigurationManager.AppSettings("BaseMapType")
          Dim sMapService As String = ConfigurationManager.AppSettings("BaseMapService")
          Dim sName As String
          Dim mrItem2 As MapResourceItem
          sMapHost = sMapHost.Trim()
          sMapType = sMapType.Trim()
          sMapService = sMapService.Trim()
          If ((sMapHost <> "") AndAlso (sMapType <> "") AndAlso (sMapService <> "")) Then
            sNames = sMapService.Split("@".ToCharArray())
            If (sNames.Length = 2) Then
              sName = sNames(1)
            Else
              sName = sMapService
            End If
            mrItem2 = New MapResourceItem()
            mrItem2.Name = sName
            sDef = "<Definition DataSourceDefinition=""" & sMapHost & """ DataSourceType=""" & sMapType & """ Identity=""""  ResourceDefinition=""" & sMapService & """ DataSourceShared=""True"" />"
            def = New GISResourceItemDefinition(sDef)
            'def = new GISResourceItemDefinition("<Definition DataSourceDefinition=\"" + sMapHost + "\" DataSourceType=\"" + sMapType + "\" Identity=\"\" ResourceDefinition=\"" + sMapService + "\" DataSourceShared=\"True\" />");
            mrItem2.Definition = def
            MapResourceManager1.ResourceItems.Add(mrItem2)
            MapResourceManager1.CreateResource(mrItem2)
            Map1.InitializeFunctionality(mrItem2)
            Toc1.InitializeFunctionality(mrItem2)
            OverviewMap1.OverviewMapResource = mrItem2.Name
            'Magnifier1.MagnifierMapResource = mrItem.Name
          End If
        Catch ex As Exception
        End Try
        Map1.Refresh()
        Toc1.Refresh()
      End If
    Catch ex As Exception
    End Try
  End Sub
  Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load, Me.Load
    Dim n As Integer
    Dim ds As Long = Date.Now.Ticks
    If Not Page.IsCallback And Not Page.IsPostBack Then
      If Map1.MapResourceManager Is Nothing Or Map1.MapResourceManager.Length = 0 Then
        callErrorPage("No MapResourceManager defined for the map.", Nothing)
      End If
      If MapResourceManager1.ResourceItems.Count = 0 Then
        callErrorPage("The MapResourceManager does not have a valid ResouceItem Definition.", Nothing)
      ElseIf MapResourceManager1.ResourceItems(0) Is Nothing Then
        callErrorPage("The MapResourceManager does not have a valid ResouceItem Definition.", Nothing)
      End If
      m_newLoad = "true"

      Dim cbReference As String = Page.ClientScript.GetCallbackEventReference(Page, "message", ApSConfigAHS.CB_CBGeneralServerProc, "context", "postBackError", True)
      Dim cbScript As String = "function " & ApSConfigAHS.CB_CB2Server & "(message, context){" & cbReference & ";}"
      Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), ApSConfigAHS.CB_CB2Server, cbScript, True)
      ddlActiveLayer.Attributes.Add("onChange", "ActiveLayerUpdate(this.value, 'ActiveLayerUpdate')")

      Dim sPath As String = ""
      Dim cHISNetworks As HISNetworks
      Dim sKey As String = ""
      Dim sPageName As String = ""
      Dim oNetwork As HISNetwork
      Try
        sPath = ConfigurationManager.AppSettings("DBForDownload")
      Catch ex As Exception
        sPath = "App_Data\HISDownloadSchema.mdb"
      End Try
      ApSConfigAHS.DBForDownLoad = sPath
      Try
        n = CType(ConfigurationManager.AppSettings("DebugLevel"), Integer)
      Catch ex As Exception
        n = 0
      End Try
      ApSConfigAHS.WebDebug = n
      Try
        n = CType(ConfigurationManager.AppSettings("MaxNumberOfSites"), Integer)
      Catch ex As Exception
        n = 200
      End Try
      ApSConfigAHS.MaxNumberOfSites = n

      Try
        n = CType(ConfigurationManager.AppSettings("QueryInterval"), Integer)
      Catch ex As Exception
        n = 50
      End Try
      ApSConfigAHS.QueryInterval = n

      'ReadAppConfig(10000)
      sKey = ApSConfigAHS.GetWebSiteName(Me.Page, sPath, sPageName)
      ApSConfigAHS.AppName = sKey
      If (ApSConfigAHS.Logger Is Nothing) Then
        sKey = ApSConfigAHS.getDateTimeAsString(Date.Now)
        sKey = sKey & ".log"
        ApSConfigAHS.Logger = New ErrorLogger("LogFiles", sKey)
        ApSConfigAHS.Write2Log("DefaultPage_Load Started:", True)
      End If
      sPath = Me.Page.MapPath("bin") & "\HISNetworks.xml"
      cHISNetworks = New HISNetworks
      cHISNetworks.LoadXMLFile(sPath)
      Me.ddlActiveLayer.Items.Clear()
      Dim oItem As ListItem
      ApSConfigAHS.HisNetworks = cHISNetworks
      For Each sKey In cHISNetworks.Keys
        oNetwork = cHISNetworks.Item(sKey)
        oItem = New ListItem(sKey, oNetwork.Name)
        Me.ddlActiveLayer.Items.Add(oNetwork.TagName)
      Next
      Me.ddlActiveLayer.SelectedIndex = 1
      oActiveNetwork = ApSConfigAHS.HashtableGetValue(cHISNetworks, Me.ddlActiveLayer.SelectedValue)
      Dim m_resourceManger As MapResourceManager = Me.Page.FindControl(Map1.MapResourceManager)
      If (Session.IsNewSession = True) Then
        'End If
        m_closeOutCallback = Page.ClientScript.GetCallbackEventReference(Page, "argument", "CloseOutResponse", "context", True)
        m_copyrightCallback = Page.ClientScript.GetCallbackEventReference(Page, "argument", "processCallbackResult", "context", True)
        ' initiate identify class and set link to TaskResults1 for response

        Dim ovPanel As FloatingPanel = Page.FindControl("OverviewMap_Panel") '
        If Not (ovPanel Is Nothing) Then
          AddHandler ovPanel.PanelCollapsed, AddressOf OverviewMap_Panel_PanelCollapsed
          AddHandler ovPanel.PanelExpanded, AddressOf OverviewMap_Panel_PanelExpanded
        End If

        'Dim sss As String = m_resourceManger.GetResource(ApSConfigAHS.ResourceIdx).ResourceDefinition
        'Dim i As Integer = sss.IndexOf("@")
        'sss = sss.Substring((i + 1), sss.Length - (i + 1))
        'Me.Page.Session(ApSConfigAHS.K_MAPSERVICE_NAME) = sss
        '' get the current map extent
        'Me.Page.Session(ApSConfigAHS.KS_HOSTNAME) = m_resourceManger.GetResource(0).DataSource.Name
        'ApSConfigAHS.HostName = m_resourceManger.GetResource(0).DataSource.Name   'Server.MachineName
        Me.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK) = oActiveNetwork
        If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogDSTime) = ApSConfigAHS.DebugType.LogDSTime) Then
          ApSConfigAHS.Write2Log(Page.Session.SessionID & " Started.", True, ds, False)
        End If
        'Dim mri As MapResourceItem
        'Dim mapResource As MapResourceLocal = Nothing
        'Dim localDataSource As GISDataSourceLocal = Nothing
        'For Each mri In MapResourceManager1.ResourceItems
        '  If Not mri Is Nothing Then
        '    If TypeOf (mri.Resource) Is MapResourceLocal Then
        '      mapResource = CType(mri.Resource, MapResourceLocal)
        '      localDataSource = mapResource.DataSource
        '      ApSConfigAHS.MapServiceName = mapResource.Service
        '      ApSConfigAHS.MapServiceName = mapResource.Name
        '      Exit For
        '    End If
        '  End If
        'Next mri
      End If
    End If

    identify = New MapIdentify(Map1)
    identify.ResultsDisplay = TaskResults1
    identify.NumberDecimals = 4

    m_HISIdentify = New HISIdentify(Map1)
    m_HISIdentify.ResultsDisplay = Me.TaskResults2
    m_HISIdentify.NumberDecimals = 3
    Me.Page.Session(ApSConfigAHS.CURRENT_MAP_EXTENT) = Map1.Extent

  End Sub 'Page_Load

  '/ <summary>
  '/ Default method for catching errors that have no programmed catch point
  '/ </summary>
  Private Sub Page_Error(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Error
    Dim exception As Exception = Server.GetLastError()
    Server.ClearError()
    callErrorPage("Page_Error", exception)
  End Sub
  Protected Sub Page_PreRenderComplete(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.PreRenderComplete
    ' If no tasks have been defined, hide the tasks panel
    If TaskMenu.Items.Count = 0 Then Tasks_Menu_Panel.Visible = False
    ' check to see if any of the resource items are non-pooled
    If Not Page.IsCallback Or Not Page.IsPostBack Then
      CloseHyperLink.Visible = HasNonPooledResources()
      Dim ov As OverviewMap = Page.FindControl("OverviewMap1")
      If Not ov Is Nothing Then
        If Not OverviewMapResourceIsValid(ov) Then
          ov.OverviewMapResource = Map1.PrimaryMapResource
        End If
      End If
    End If
    CopyrightTextHolder.Visible = HasCopyrightText()
  End Sub 'Page_PreRenderComplete


  Protected Sub TitleMenu_DataBound(ByVal sender As Object, ByVal e As EventArgs)
    Dim menu As Menu = CType(sender, Menu)
    If Not (menu Is Nothing) Then
      Dim i As Integer
      For i = 0 To menu.Items.Count - 2
        menu.Items(i).SeparatorImageUrl = "~/images/separator.gif"
      Next i
    End If

  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>
  '/  Checks to see if any resources used by the app are local non-pooled
  '/ </summary>
  '/ <returns>True if any resources are local non-pooled</returns>
  Private Function HasNonPooledResources() As Boolean
    ' define a boolean and set it to false by default... no non-pooled resourceitems
    Dim hasNonPooledResource As Boolean = False
    ' Now go through all resources and find any non-pooled local resources
    Dim mapResource As MapResourceLocal = Nothing
    Dim localDataSource As GISDataSourceLocal = Nothing
    ' First, check the map resourceitems
    Dim mri As MapResourceItem
    For Each mri In MapResourceManager1.ResourceItems
      If Not mri Is Nothing Then
        If TypeOf (mri.Resource) Is MapResourceLocal Then
          mapResource = CType(mri.Resource, MapResourceLocal)
          localDataSource = mapResource.DataSource
          If Not localDataSource.Connection.IsServerObjectPooled(mapResource.ServerContextInfo.ServerObjectName, "MapServer") Then
            hasNonPooledResource = True
          End If
        End If
      End If
    Next mri
    ' If there any geocoding resourceitems, check these
    If GeocodeResourceManager1.ResourceItems.Count > 0 Then
      If Not GeocodeResourceManager1.Initialized Then GeocodeResourceManager1.Initialize()
      Dim geocodeResource As GeocodeResourceLocal = Nothing
      Dim gri As GeocodeResourceItem
      For Each gri In GeocodeResourceManager1.ResourceItems
        If Not gri Is Nothing Then
          If TypeOf (gri.Resource) Is GeocodeResourceLocal Then
            geocodeResource = CType(gri.Resource, GeocodeResourceLocal)
            localDataSource = geocodeResource.DataSource
            If Not localDataSource.Connection.IsServerObjectPooled(geocodeResource.ServerContextInfo.ServerObjectName, "GeocodeServer") Then
              hasNonPooledResource = True
            End If
          End If
        End If
      Next gri
    End If

    ' If there any geoprocessing resourceitems, check these
    If GeoprocessingResourceManager1.ResourceItems.Count > 0 Then
      If Not GeoprocessingResourceManager1.Initialized Then GeoprocessingResourceManager1.Initialize()
      Dim geoprocessResource As GeoprocessingResourceLocal = Nothing
      Dim gpri As GeoprocessingResourceItem
      For Each gpri In GeoprocessingResourceManager1.ResourceItems
        If Not gpri Is Nothing Then
          If TypeOf (gpri.Resource) Is GeoprocessingResourceLocal Then
            geoprocessResource = CType(gpri.Resource, GeoprocessingResourceLocal)
            localDataSource = geoprocessResource.DataSource
            If Not localDataSource.Connection.IsServerObjectPooled(geoprocessResource.ServerContextInfo.ServerObjectName, "GPServer") Then
              hasNonPooledResource = True
            End If
          End If
        End If
      Next gpri
    End If
    ' if any resourceitems were non-pooled, hasNonPooledResource will be true
    Return hasNonPooledResource
  End Function 'HasNonPooledResources

  Protected Sub ResourceManager_ResourcesInit(ByVal sender As Object, ByVal e As EventArgs) Handles MapResourceManager1.ResourcesInit, GeocodeResourceManager1.ResourcesInit, GeoprocessingResourceManager1.ResourcesInit
    If DesignMode Then
      Return
    End If
    Dim manager As ResourceManager = sender '
    If Not manager.FailureOnInitialize Then
      Return
    End If
    If TypeOf manager Is MapResourceManager Then
      Dim mapManager As MapResourceManager = manager '
      Dim i As Integer
      For i = 0 To mapManager.ResourceItems.Count - 1
        Dim item As MapResourceItem = mapManager.ResourceItems(i)
        If Not (item Is Nothing) Then
          If item.FailedToInitialize Then
            mapManager.ResourceItems(i) = Nothing
          End If
        End If
      Next i
    Else
      If TypeOf manager Is GeocodeResourceManager Then
        Dim gcManager As GeocodeResourceManager = manager '
        Dim i As Integer
        For i = 0 To gcManager.ResourceItems.Count - 1
          Dim item As GeocodeResourceItem = gcManager.ResourceItems(i)
          If Not (item Is Nothing) Then
            If item.FailedToInitialize Then
              gcManager.ResourceItems(i) = Nothing
            End If
          End If
        Next i
      Else
        If TypeOf manager Is GeoprocessingResourceManager Then
          Dim gpManager As GeoprocessingResourceManager = manager '
          Dim i As Integer
          For i = 0 To gpManager.ResourceItems.Count - 1
            Dim item As GeoprocessingResourceItem = gpManager.ResourceItems(i)
            If Not (item Is Nothing) Then
              If item.FailedToInitialize Then
                gpManager.ResourceItems(i) = Nothing
              End If
            End If
          Next i
        End If
      End If
    End If
  End Sub 'ResourceManager_ResourcesInit 

  Private Function OverviewMapResourceIsValid(ByVal ov As OverviewMap) As Boolean
    Dim isValidResource As Boolean = False
    Dim resource As MapResourceItem
    For Each resource In MapResourceManager1.ResourceItems
      If Not resource Is Nothing Then
        If resource.Name = ov.OverviewMapResource Then
          isValidResource = True
        End If
      End If
    Next resource
    Return isValidResource
  End Function 'OverviewMapResourceIsValid

  Private Function HasCopyrightText() As Boolean
    Return (GetCopyrightText().Length > 0)
  End Function 'HasCopyrightText

  Private Function GetCopyrightText() As String
    Dim sb As New System.Text.StringBuilder()
    Dim mapFunc As IMapFunctionality
    Dim s As String = ""
    Dim key As String = ""
    Dim value As String = ""
    Dim dataframeValue As String = ""
    Dim layerId As Int32
    For Each mapFunc In Map1.GetFunctionalities()
      If (Not (mapFunc Is Nothing)) AndAlso (mapFunc.Supports("GetCopyrightText")) Then
        Dim crDictionary As Dictionary(Of String, String) = mapFunc.GetCopyrightText()
        Dim sb2 As New System.Text.StringBuilder()
        Dim layerIds() As String = Nothing
        Dim layerNames() As String = Nothing
        mapFunc.GetLayers(layerIds, layerNames)
        For Each kvPair As KeyValuePair(Of String, String) In crDictionary
          key = kvPair.Key
          value = kvPair.Value
          If Not value Is Nothing Then
            If value.Length > 0 Then
              If Not key Is Nothing Then
                If key.Length > 0 Then
                  layerId = Convert.ToInt32(key)
                  sb2.Append(layerNames(layerId) & ": ")
                  sb2.Append(value & "<br/>")
                Else
                  dataframeValue = value
                End If

              End If
            End If
          End If
        Next
        If sb2.Length > 0 Then sb.AppendFormat("<div style='font-weight: bold'>{0}:</div><div style='padding: 0px 5px 5px 5px;font-weight: normal;'>{2}<br/>{1}</div>", mapFunc.Resource.Name, sb2.ToString(), dataframeValue)
        sb2.Length = 0
        dataframeValue = ""
      End If
    Next mapFunc
    Return sb.ToString()
  End Function 'GetCopyrightText
  Private _callbackArg As String
  Public Overridable Function RaiseCallbackEvent2(ByVal responseString As String) As String '
    ' break out the responseString into a querystring  
    '..Single place that handles all the callbacks.  zye.
    Dim ds As Long = Date.Now.Ticks
    Dim keyValuePairs As Array
    Dim m_queryString As New NameValueCollection()
    Dim keyValue() As String
    Dim response As String = ""
    Dim BufferExtRatio As Double = 0.01
    Dim sMsg As String = ""
    Dim s As String = ""
    Dim pMf As MapFunctionality
    Dim bOk As Boolean = True
    Dim i As Integer
    Dim sValues() As String
    Dim cbParams(1) As Object
    Dim cbr As CallbackResult
    Try
      keyValuePairs = responseString.Split("&".ToCharArray())
      If keyValuePairs.Length > 0 Then
        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("ControlType")
      Dim eventArg As String = m_queryString("EventArg")
      Dim eventVal As String = m_queryString("EventVal")
      If controlType Is Nothing Then
        controlType = "Map"
      End If
      Select Case controlType
        Case "Map"
          ' request is for the map control
          If eventArg = "MapIdentify" Then
            ' Identify
            If Not (identify Is Nothing) Then
              identify.Map = Map1 ' make sure it is current
              response = identify.Identify(m_queryString)
            End If
          ElseIf eventArg = "CloseOutApplication" Then
            ' Close out session and quit application
            Dim context As IServerContext
            For i = 0 To Session.Count - 1
              If TypeOf (Session(i)) Is IServerContext Then
                context = Session(i)
                context.RemoveAll()
                context.ReleaseContext()
              End If
            Next i
            response = "SessionClosed"
            Session.RemoveAll()
            response = ConfigurationManager.AppSettings("CloseOutUrl")
            If response Is Nothing Then
              response = "ApplicationClosed.aspx"
            ElseIf response.Length = 0 Then
              response = "ApplicationClosed.aspx"
            End If
          Else
            If eventArg = "GetCopyrightText" Then '
              Dim sb As New System.Text.StringBuilder()
              sb.AppendFormat("///:::{0}:::innercontent:::", "CopyrightTextContents")
              Dim sbLength As Integer = sb.Length
              sb.Append(GetCopyrightText())
              If sb.Length = sbLength Then
                sb.Append("No Copyright information available.")
              End If
              response = sb.ToString()
            End If
          End If
        Case ApSConfigAHS.CB_Control_Type_HIS
          Select Case eventArg
            Case ApSConfigAHS.SITEINFO_REQUEST
              ' Dim sss As String
              ' sss = "AGPS---" & SiteSelect_Panel.CallbackResults.ToString()
              response = GetSiteInfoWP(eventVal)   '"???" & sss
            Case ApSConfigAHS.CSV_REQUEST
              Dim tsInputInfo As String = CType(m_queryString(ApSConfigAHS.CB_EventVal), String)
              's = TestConnection()
              'response = DoGetCSV(tsInputInfo)
              response = GetCSVInfo(tsInputInfo)
            Case ApSConfigAHS.CHART_REQUEST
              Dim chartInputInfo As String = CType(m_queryString(ApSConfigAHS.CB_EventVal), String)
              response = GetChartInfo(chartInputInfo)
            Case ApSConfigAHS.ADDTOCART_REQUEST
              Dim addToCartInputInfo As String = CType(m_queryString(ApSConfigAHS.CB_EventVal), String)
              response = GetAddToCartDB(addToCartInputInfo)
            Case ApSConfigAHS.ACTIVELAYER_UPDATE_REQUEST
              response = m_queryString(ApSConfigAHS.CB_EventVal)
              Dim sLayerName As String = CType(m_queryString(ApSConfigAHS.CB_EventVal), String)
              oActiveNetwork = ApSConfigAHS.HashtableGetValue(ApSConfigAHS.HisNetworks, sLayerName)
              Me.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK) = oActiveNetwork
              Dim iLayerIndex As Integer = GetLayerIndex(Me.Page, "Map1", sLayerName)
              'Me.Page.Session(ApSConfigAHS.SELECTED_STATION_LIST) = Nothing
            Case ApSConfigAHS.HISID_REQUEST
              If (Not m_HISIdentify Is Nothing) Then
                Try
                  BufferExtRatio = System.Configuration.ConfigurationManager.AppSettings.Item("BufferExtRatio")
                Catch ex As Exception
                  BufferExtRatio = 0.01
                End Try
                response = m_HISIdentify.Identify(m_queryString, BufferExtRatio)
              End If
            Case "ClearSelection"
              i = ApSConfigAHS.ClearSelectedFeatures(Map1, False)
              cbParams(0) = "SetStatusMsg('" & CStr(i) & " selected feature(s) cleared');"
              cbr = New CallbackResult(Nothing, Nothing, "javascript", cbParams)
              Map1.CallbackResults.Add(cbr)
              Map1.Refresh()
              response = ApSConfigAHS.CB_CallAGSP & ApSConfigAHS.K_KVSep & Map1.CallbackResults.ToString()
            Case "ToggleSelection"
              Dim SelectedIds() As Integer
              oActiveNetwork = Me.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
              SelectedIds = ApSConfigAHS.ToggleSelected(Me.Page, Map1, ApSConfigAHS.MapServiceName, oActiveNetwork.LayerName)
              pMf = Map1.GetFunctionality(ApSConfigAHS.MapServiceName)
              sMsg = ApSConfigAHS.SaveSelectedSiteCodes(Me.Page, oActiveNetwork.LayerName, pMf, SelectedIds, sMsg, oActiveNetwork.SiteCodeField)
              Try
                If Not SelectedIds Is Nothing Then
                  Dim n As Integer
                  n = SelectedIds.Length()
                  cbParams(0) = "SetStatusMsg('" & CStr(n) & " features selected from layer " & oActiveNetwork.LayerName & "');"
                  cbr = New CallbackResult(Nothing, Nothing, "javascript", cbParams)
                  Map1.CallbackResults.Add(cbr)
                End If
              Catch ex As Exception

              End Try
              Map1.Refresh()
              response = ApSConfigAHS.CB_CallAGSP & ApSConfigAHS.K_KVSep & Map1.CallbackResults.ToString()
            Case "ShowStationsWithVariable"
              If (eventVal <> "") Then
                i = ShowStationsWithVariable(Map1, eventVal)
                If (i > 0) Then
                  Map1.Refresh()
                  response = ApSConfigAHS.CB_CallAGSP & ApSConfigAHS.K_KVSep & Map1.CallbackResults.ToString()
                End If
              End If
            Case "ShowMultipleSelect"
              s = CanShowMultipleSelect()
              sValues = s.Split(",")
              If (sValues(0) <> "OK") Then
                response = ApSConfigAHS.CB_CBShowMsg & ApSConfigAHS.K_KVSep & s
              Else
                response = ApSConfigAHS.CB_CBDoEval & ApSConfigAHS.K_KVSep & "ShowMultipleSelectForm('" & sValues(1) & "');"
              End If

            Case ApSConfigAHS.CB_LastExt
              If (Not Page.Session(ApSConfigAHS.K_LastExt) Is Nothing) Then
                Dim pMapRect As ESRI.ArcGIS.ADF.Web.Geometry.Envelope
                pMapRect = CType(Page.Session(ApSConfigAHS.K_LastExt), ESRI.ArcGIS.ADF.Web.Geometry.Envelope)
                Map1.Extent = pMapRect
                Map1.Refresh()
                response = ApSConfigAHS.CB_CallAGSP & ApSConfigAHS.K_KVSep & Map1.CallbackResults.ToString()
              End If
          End Select
        Case Else
      End Select '
    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("RaiseCallbackEvent2:" & ex.Message & "," & ex.StackTrace & "," & responseString, True, ds, False)
      End If
    Finally
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogDSTime) = ApSConfigAHS.DebugType.LogDSTime) Then
        ApSConfigAHS.Write2Log("RaiseCallbackEvent2:", True, ds, False)
      End If
    End Try
    Return response
  End Function 'RaiseCallbackEvent
  Public Function CanShowMultipleSelect() As String
    '..check to see if the number of selected sites or selected by extent is > nMax.
    '..returns "OK, number of stations (either selected or in the map extent).
    Dim n As Integer
    Dim intIDs() As Integer = Nothing
    Dim pMF As MapFunctionality
    Dim oNetWork As HISNetwork
    Dim sMsg As String = ""
    Dim bSelected As Boolean = True
    Try
      oNetWork = Me.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
      pMF = CType(Map1.GetFunctionality(ApSConfigAHS.MapServiceName), MapFunctionality)
      n = ApSConfigAHS.GetSelectedFeatureIDs(pMF, oNetWork.LayerName, ApSConfigAHS.MapServiceName, intIDs)
      If (n = 0) Then
        intIDs = ApSConfigAHS.GetOIDsInMapExtent(Me.Page, pMF, oNetWork.LayerName)
        n = intIDs.Length
        If (n > ApSConfigAHS.MaxNumberOfSites) Then
          sMsg = "The map extent contains too many stations. Please zoom in further." & ApSConfigAHS.KS_NL & "Max stations allowed" & ApSConfigAHS.K_ConfirmSep & ApSConfigAHS.MaxNumberOfSites & ApSConfigAHS.KS_NL & n & " stations contained in the current extent."
        Else
          If n = 1 Then
            sMsg = " Station In Current Map Extent."
          Else
            sMsg = " Stations In Current Map Extent."
          End If
          sMsg = "OK," & n & sMsg
        End If
      Else
        bSelected = True
        If (n > ApSConfigAHS.MaxNumberOfSites) Then
          sMsg = "Too many stations are selected for the analysis." & ApSConfigAHS.KS_NL & "Max stations allowed" & ApSConfigAHS.K_ConfirmSep & ApSConfigAHS.MaxNumberOfSites & ApSConfigAHS.KS_NL & n & " stations are selected."
        Else
          If (n = 1) Then
            sMsg = " Selected Station."
          Else
            sMsg = " Selected Stations."
          End If
          sMsg = "OK," & n & sMsg
        End If
      End If
    Catch ex As Exception
      sMsg = ex.Message & ", " & ex.ToString
    End Try

    Return sMsg
  End Function
  Public Function ShowStationsWithVariable(ByVal pMapCtrl As ESRI.ArcGIS.ADF.Web.UI.WebControls.Map, ByVal EventVal As String) As Integer
    Dim htMatrix As Hashtable
    Dim ds As Long = DateTime.Now.Ticks
    Dim nCnt As Integer = 0
    Dim oNetwork As HISNetwork
    Dim pMf As MapFunctionality
    Dim oPage As System.Web.UI.Page
    Dim pQF As ESRI.ArcGIS.ADF.ArcGISServer.QueryFilter
    Dim SelectedOIDs() As Integer
    Dim sWhere As String = ""
    Dim SiteCodes As String
    Dim LastSiteCodes As String
    Dim sb As StringBuilder = New StringBuilder
    'Dim SiteCodes(nCnt - 1) As String
    Dim Fields() As String
    Dim i As Integer
    Dim sMsg As String = ""

    Try
      oPage = pMapCtrl.Page
      '..htMatrix keyed in index, value = string(), value.legth=3.
      htMatrix = ApSConfigAHS.ParseString2D(EventVal)
      nCnt = htMatrix.Count
      For i = 0 To nCnt - 1
        Fields = htMatrix.Item(i)
        'SiteCodes(i) = Fields(0)
        If (sb.Length = 0) Then
          sb.Append("'" & Fields(0) & "'")
        Else
          sb.Append(",'" & Fields(0) & "'")
        End If
      Next
      SiteCodes = sb.ToString
      LastSiteCodes = oPage.Session(ApSConfigAHS.KS_LastSiteCodes)
      If (SiteCodes <> LastSiteCodes) Then
        oNetwork = oPage.Session(ApSConfigAHS.KS_ACTIVENETWORK)
        sWhere = oNetwork.SiteCodeField & " IN (" & SiteCodes & ")"
        pQF = New ESRI.ArcGIS.ADF.ArcGISServer.QueryFilter()
        pQF.WhereClause = sWhere
        pMf = pMapCtrl.GetFunctionality(ApSConfigAHS.MapServiceName)
        '..Try to save last selected info.
        SelectedOIDs = ApSConfigAHS.SaveSelectedOIDs(oPage, pMf, oNetwork.LayerName, True)
        Dim pSelColor As RgbColor
        pSelColor = ApSConfigAHS.GetSelectionColor()
        SelectedOIDs = ApSConfigAHS.ApplySelection(pMf, oNetwork.LayerName, pQF, pSelColor, ApSConfigAHS.SelectActions.NewSet)
        ApSConfigAHS.SaveSelectedSiteCodes(oPage, oNetwork.LayerName, pMf, SelectedOIDs, sMsg, oNetwork.SiteCodeField)
        nCnt = SelectedOIDs.Length
      End If
    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("ShowStationsWithVariable:" & ex.Message & "," & ex.StackTrace, True, ds, False)
      End If
      nCnt = -1
    Finally
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogDSTime) = ApSConfigAHS.DebugType.LogDSTime) Then
        ApSConfigAHS.Write2Log("ShowStationsVithVariable:", True, ds, False)
      End If

    End Try
    Return nCnt
  End Function
  Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
    Return RaiseCallbackEvent2(_callbackArg)
  End Function
  ''' <summary>
  ''' testing ReadAppConfig's speed.
  ''' </summary>
  ''' <param name="nTimes"></param>
  ''' <returns></returns>
  ''' <remarks></remarks>
  Private Function ReadAppConfig(ByVal nTimes As Integer) As Boolean

    Dim ds As Long = Date.Now.Ticks
    Dim i As Integer
    Dim n As Integer

    Try
      For i = 0 To nTimes
        n = CType(ConfigurationManager.AppSettings("DebugLevel"), Integer)
      Next
    Catch ex As Exception
    Finally
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogDSTime) = ApSConfigAHS.DebugType.LogDSTime) Then
        ApSConfigAHS.Write2Log("ReadAppConfig: " & nTimes & " times:", True, ds, False)
      End If

    End Try

  End Function
  Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
    _callbackArg = eventArgument
  End Sub

  'Private Function SwitchMapTipsVisibility(ByVal sLayer As String) As String

  '  'Dim layerCBResult As String = Nothing
  '  'If sLayer.Contains(ApSConfigAHS.NETWORK_NAME_NWIS) Then
  '  '  MapTips1.Visible = True
  '  '  MapTips2.Visible = False
  '  'ElseIf sLayer.Contains(ApSConfigAHS.NETWORK_NAME_EPA) Then
  '  '  MapTips2.Visible = True
  '  '  MapTips1.Visible = False
  '  'End If

  '  'MapTips1.Refresh()
  '  'MapTips2.Refresh()
  '  'Map1.Refresh()
  '  'Return Map1.CallbackResults.ToString & "???" & MapTips1.CallbackResults.ToString & "???" & MapTips2.CallbackResults.ToString
  'End Function

  Protected Sub OverviewMap_Panel_PanelExpanded(ByVal sender As Object, ByVal args As System.EventArgs)
    Dim ovPanel As FloatingPanel = Page.FindControl("OverviewMap_Panel")
    If Not ovPanel Is Nothing Then
      Dim ov As OverviewMap = ovPanel.FindControl("OverviewMap1")
      If Not ov Is Nothing Then
        ov.Enabled = True
        ov.Refresh()
        ovPanel.CallbackResults.CopyFrom(ov.CallbackResults)
      End If
    End If
  End Sub

  Protected Sub OverviewMap_Panel_PanelCollapsed(ByVal sender As Object, ByVal args As System.EventArgs)
    Dim ovPanel As FloatingPanel = Page.FindControl("OverviewMap_Panel")

    If Not ovPanel Is Nothing Then
      Dim ov As OverviewMap = ovPanel.FindControl("OverviewMap1")
      If Not ov Is Nothing Then
        ov.Enabled = False
      End If
    End If

  End Sub

  Protected Sub Page_PreInit(ByVal sender As Object, ByVal args As System.EventArgs) Handles MyBase.PreInit
    ' Make the overview enabled property match floatingpanel expanded property
    Dim ovPanel As FloatingPanel = Page.FindControl("OverviewMap_Panel")
    If Not ovPanel Is Nothing Then
      Dim ov As OverviewMap = ovPanel.FindControl("OverviewMap1")
      If Not ov Is Nothing Then
        ov.Enabled = ovPanel.Expanded
      End If
    End If

  End Sub

  ''' <summary>
  '''   Returns site info. from web services
  ''' </summary>
  ''' <param name="stationInfo"></param>
  ''' <returns></returns>
  ''' <remarks></remarks>
  ''' 
  Private Function GetSiteInfoWP(ByVal stationInfo As String) As String
    '..Wrapper to get StationSiteInfo, try local first, 
    '  if none returned, try the really WebService.  zye
    Dim ds As Long = DateTime.Now.Ticks
    Dim _siteInfo As String = ""
    Dim sesSiteInfo As String = Nothing
    Dim dbSiteInfo As String = ""
    Dim stationIdArray() As String
    Try
      stationIdArray = stationInfo.Split(",")
      ' sesSiteInfo = Session(ApSConfigAHS.KS_SITEINFO)   ' NWIS:111203040
      dbSiteInfo = getSiteInfoLocal(stationIdArray)
      If dbSiteInfo Is Nothing Then
        ' get the info from WS
        Dim wsSiteInfo As String
        Try
          wsSiteInfo = GetSiteInfo(stationIdArray)
        Catch ex As Exception
          wsSiteInfo = ""
        End Try
        '..parse the wsSiteInfo xml returned by the web service. 
        If (wsSiteInfo <> "") Then
          _siteInfo = GetSiteInfoFromXml(wsSiteInfo)
        Else
          _siteInfo = "<error>Error accessing site informarion. Blank wsSiteInfo. Try again later.</error>"  ' wsSiteInfo
        End If
      Else
        _siteInfo = dbSiteInfo
      End If

    Catch ex As Exception
      _siteInfo = "<error>Error accessing site informarion. Try again later.</error>"
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("GetSiteInfoWP:" & ex.Message & "," & ex.StackTrace, True, -1, False)
      End If
    Finally
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogDSTime) = ApSConfigAHS.DebugType.LogDSTime) Then
        ApSConfigAHS.Write2Log("GetSiteInforWP:", True, ds, False)
      End If

    End Try
    Return _siteInfo
  End Function

  Private Function getSiteInfoLocal(ByVal inputSiteInfo() As String) As String
    ' query  the local database for site Info
    Dim ds As Long = DateTime.Now.Ticks
    Dim dbSiteRes As String = Nothing
    Dim siteInfoRes As String = Nothing
    Dim network As String = Nothing
    'Dim networkId As String = ApSConfigAHS.NETWORK_NAME_NWIS ' default network id nwis
    Dim siteCode As String = Nothing
    Dim count As Integer = 0
    Dim dt1Str As String = ""
    Dim dt2Str As String = ""
    'Dim dt1Arr() As String
    'Dim dt2Arr() As String
    Dim dt1Final As String
    Dim dt2Final As String
    Dim dt1 As Date
    Dim dt2 As Date
    Dim oNetwork As HISNetwork

    Dim myConn As SqlConnection = Nothing
    Dim myCmd As SqlCommand = Nothing
    Dim sqlReader As SqlDataReader = Nothing
    Dim strData As String = ""

    Try
      network = inputSiteInfo(1)
      siteCode = inputSiteInfo(0)
      oNetwork = Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
      If (network = "") Then
        network = oNetwork.Name
      End If
      'NetworkID = ApSConfigAHS.GetNetworkID(network)

      Dim sqlStr As String
      'sqlStr = "SELECT SeriesCatalog.SiteCode, SeriesCatalog.SiteName, Variables.VariableCode, Variables.VariableName, SeriesCatalog.ValueCount, "
      'sqlStr &= " SeriesCatalog.BeginDateTime, SeriesCatalog.EndDateTime  FROM  Variables INNER JOIN  SeriesCatalog INNER JOIN "
      'sqlStr &= "  Sites ON SeriesCatalog.SiteID = Sites.SiteID ON Variables.VariableID = SeriesCatalog.VariableID   "
      'sqlStr &= "  WHERE  (SeriesCatalog.SiteCode = '" & siteCode & "') AND (Sites.NetworkID = " & NetworkID & " ) ORDER BY Variables.VariableName"
      sqlStr = "SELECT SeriesCatalog.SiteCode, SeriesCatalog.SiteName, Variables.VariableCode, Variables.VariableName, SeriesCatalog.ValueCount, "
      sqlStr &= " SeriesCatalog.BeginDateTime, SeriesCatalog.EndDateTime  FROM  Variables INNER JOIN  SeriesCatalog INNER JOIN "
      sqlStr &= "  Sites ON SeriesCatalog.SiteID = Sites.SiteID ON Variables.VariableID = SeriesCatalog.VariableID   "
      sqlStr &= "  WHERE  (SeriesCatalog.SiteCode = '" & siteCode & "') ORDER BY Variables.VariableName"

      myConn = New SqlConnection
      myConn.ConnectionString = oNetwork.DBConnection   ' ConfigurationManager.ConnectionStrings(ApSConfigAHS.K_ODEConn).ConnectionString

      myCmd = New SqlCommand
      myCmd.CommandText = sqlStr
      myCmd.CommandType = CommandType.Text
      myCmd.CommandTimeout = ApSConfigAHS.CMD_TimeOut
      myCmd.Connection = myConn
      myCmd.Connection.Open()
      ' sqlReader = myCmd.ExecuteReader
      Dim ireader As IDataReader = myCmd.ExecuteReader

      While ireader.Read
        dt1 = DateTime.Parse(ireader(ApSConfigAHS.FD_BeginDateTime).ToString)
        dt1Str = Format(dt1, "yyyy-MM-dd")   'Format(dt1, "yyyy-MM-dd HH:mm:ss")
        dt1Final = dt1Str
        'dt1Arr = dt1Str.Split(" ")
        'dt1Final = dt1Arr(0) & "T" & dt1Arr(1)
        dt2 = DateTime.Parse(ireader(ApSConfigAHS.FD_EndDateTime).ToString)   'DB_SITEINFO_ENDDATETIME
        If (dt1 = dt2) Then
          '..Try to add 2 years, zye
          Try
            Dim dt3 As DateTime
            dt3 = dt2.AddYears(2)
            If (dt3 < Date.Now) Then
              dt2 = dt3
            Else
              dt2 = Date.Now
            End If
          Catch ex As Exception
            dt2 = dt1
          End Try
        End If
        dt2Str = Format(dt2, "yyyy-MM-dd")     ' Format(dt2, "yyyy-MM-dd HH:mm:ss")
        dt2Final = dt2Str
        'dt2Arr = dt2Str.Split(" ")
        'dt2Final = dt2Arr(0) & "T" & dt2Arr(1)
        If count = 0 Then
          strData &= ireader(ApSConfigAHS.FD_SiteName).ToString.Trim & "$" & network & "$" & ireader(ApSConfigAHS.FD_SiteCode).ToString().Trim & "#" & ireader(ApSConfigAHS.FD_VARIABLECODE).ToString.Trim & ApSConfigAHS.K_Sep2 & ireader(ApSConfigAHS.FD_VARIABLENAME).ToString().Trim & ApSConfigAHS.K_Sep2 & CStr(Integer.Parse(ireader(ApSConfigAHS.FD_ValueCount).ToString)) & ApSConfigAHS.K_Sep2 & dt1Final & ApSConfigAHS.K_Sep2 & dt2Final & "|"
        Else
          strData &= ireader(ApSConfigAHS.FD_VARIABLECODE).ToString.Trim & ApSConfigAHS.K_Sep2 & ireader(ApSConfigAHS.FD_VARIABLENAME).ToString().Trim & ApSConfigAHS.K_Sep2 & CStr(Integer.Parse(ireader(ApSConfigAHS.FD_ValueCount).ToString)) & ApSConfigAHS.K_Sep2 & dt1Final & ApSConfigAHS.K_Sep2 & dt2Final & "|"
        End If
        count += 1
      End While

      If strData.Length > 0 Then dbSiteRes = strData
    Catch ex As Exception
      ApSConfigAHS.Write2Log("GetSiteInfoLocal: " & ex.Message & ", " & ex.StackTrace, True, -1, False)
      dbSiteRes = Nothing
    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("GetSiteInfoLocal:", True, ds, False)
      End If
    End Try
    Return dbSiteRes
  End Function

  Private Function GetSiteInfo(ByVal inputArray() As String) As String
    Dim ds As Long = DateTime.Now.Ticks
    Dim siteInfoRes As String = Nothing
    Dim network As String = Nothing
    Dim siteCode As String = Nothing
    Dim wsProxy As edu.sdsc.water.NWISDailyValues = New edu.sdsc.water.NWISDailyValues
    Dim oNetWork As HISNetwork
    Try
      'Dim epaProxy As edu.sdsc.water.STORET = New edu.sdsc.water.STORET
      oNetWork = Me.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
      network = inputArray(1)
      siteCode = inputArray(0)
      wsProxy.Url = oNetWork.WebServiceURL
      siteInfoRes = wsProxy.GetSiteInfo(network & ":" & siteCode, "")
    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("GetSiteInfo:" & ex.Message & "," & ex.StackTrace & ", " & network & ":" & siteCode, True, -1, False)
      End If

    Finally
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogDSTime) = ApSConfigAHS.DebugType.LogDSTime) Then
        ApSConfigAHS.Write2Log("GetSiteInfo:", True, ds, False)
      End If
    End Try

    Return siteInfoRes
  End Function
  'Private Function GetSiteInfoFromXml(ByVal wsResponse As String, Optional ByVal sNetWork As String = "") As String
  '  Dim oReader As System.IO.StringReader
  '  Dim sReturn As String = ""
  '  Dim sName As String
  '  Dim SiteName As String = ""
  '  Dim Network As String = sNetWork
  '  Dim SiteCode As String = ""
  '  Dim sSiteInfo As String = ""
  '  Dim sbVarInfo As StringBuilder = New StringBuilder
  '  Dim sVCode As String = ""
  '  Dim sVName As String = ""
  '  Dim sCnt As String = ""
  '  Dim sStartDate As String = ""
  '  Dim sEndDate As String = ""
  '  Try
  '    oReader = New System.IO.StringReader(wsResponse)
  '    Using pReader As XmlTextReader = New XmlTextReader(oReader)
  '      While pReader.Read()
  '        If pReader.NodeType = XmlNodeType.Element Then
  '          sName = pReader.Name
  '          Select Case sName.ToUpper   '..SiteInfo, SeriesCatalog.
  '            Case "SITEINFO"
  '              Do Until (pReader.Name.ToUpper = "SITEINFO" And pReader.NodeType = XmlNodeType.EndElement)
  '                pReader.Read()
  '                If (pReader.Name.ToUpper = "SITENAME" And pReader.NodeType = XmlNodeType.Element) Then
  '                  pReader.Read()
  '                  SiteName = pReader.Value
  '                Else
  '                  If (pReader.Name.ToUpper = "SITECODE" And pReader.NodeType = XmlNodeType.Element) Then
  '                    pReader.Read()
  '                    SiteCode = pReader.Value
  '                    Network = pReader.GetAttribute("network")
  '                    If (Network = "") Then
  '                      Network = sNetWork
  '                    End If
  '                  End If
  '                End If
  '              Loop
  '              sSiteInfo = SiteName & "$" & Network & "$" & SiteCode
  '            Case "SERIESCATALOG"
  '              Do Until (pReader.Name.ToUpper = "SERIESCATALOG" And pReader.NodeType = XmlNodeType.EndElement)
  '                pReader.Read()
  '                If pReader.Name.ToUpper = "SERIES" And pReader.NodeType = XmlNodeType.Element Then
  '                  Do Until (pReader.Name.ToUpper = "SERIES" And pReader.NodeType = XmlNodeType.EndElement)
  '                    pReader.Read()
  '                    If (pReader.Name.ToUpper = "VALUECOUNT" And pReader.NodeType = XmlNodeType.Element) Then
  '                      pReader.Read()
  '                      sCnt = pReader.Value
  '                    Else
  '                      If pReader.Name.ToUpper = "VARIABLETIMEINTERVAL" And pReader.NodeType = XmlNodeType.Element Then
  '                        Do Until pReader.Name.ToUpper = "VARIABLETIMEINTERVAL" And pReader.NodeType = XmlNodeType.Element
  '                          pReader.Read()
  '                          If pReader.Name.ToUpper = "BEGINDATETIME" And pReader.NodeType = XmlNodeType.Element Then
  '                            pReader.Read()
  '                            sStartDate = pReader.Value
  '                          Else
  '                            If pReader.Name.ToUpper = "ENDDATETIME" And pReader.NodeType = XmlNodeType.Element Then
  '                              pReader.Read()
  '                              sEndDate = pReader.Value
  '                            End If
  '                          End If
  '                        Loop
  '                      Else
  '                        If pReader.Name.ToUpper = "VARIABLE" And pReader.NodeType = XmlNodeType.Element Then
  '                          Do Until pReader.Name.ToUpper = "VARIABLE" And pReader.NodeType = XmlNodeType.EndElement
  '                            pReader.Read()
  '                            If pReader.Name.ToUpper = "VARIABLECODE" And pReader.NodeType = XmlNodeType.Element Then
  '                              pReader.Read()
  '                              sVCode = pReader.Value
  '                            Else
  '                              If pReader.Name.ToUpper = "VARIABLENAME" And pReader.NodeType = XmlNodeType.Element Then
  '                                pReader.Read()
  '                                sVName = pReader.Value
  '                              End If
  '                            End If
  '                          Loop
  '                        End If
  '                      End If
  '                    End If
  '                  Loop
  '                  sbVarInfo.Append(sVCode & "~" & sVName & "~" & sCnt & "~" & sStartDate & "~" & sEndDate & "|")
  '                End If
  '              Loop
  '          End Select  '..'..SiteInfo, SeriesCatalog.
  '        End If    '..If pReader.NodeType = XmlNodeType.Element Then
  '      End While   '..While pReader.Read()
  '    End Using
  '  Catch ex As Exception

  '  End Try
  '  sReturn = sSiteInfo & "#" & sbVarInfo.ToString
  '  Return sReturn
  'End Function
  'Private Function GetSiteInfoFromXml(ByVal wsResponse As String) As String
  '  Dim pDom As System.Xml.XmlDocument
  '  Dim pNode As System.Xml.XmlNode
  '  Dim pSeriesNode As System.Xml.XmlNode
  '  Dim pVariableNode As System.Xml.XmlNode
  '  Dim pChildNode As System.Xml.XmlNode
  '  Dim pCountNode As System.Xml.XmlNode
  '  Dim pVCodeNode As System.Xml.XmlNode
  '  Dim pVNameNode As System.Xml.XmlNode
  '  Dim pIntervalNode As System.Xml.XmlNode
  '  Dim pBdate As System.Xml.XmlNode
  '  Dim pEDate As System.Xml.XmlNode
  '  Dim sb As StringBuilder = New StringBuilder
  '  Try
  '    pDom = New System.Xml.XmlDocument
  '    pDom.LoadXml(wsResponse)
  '    '..GetSiteRelatedInfo:
  '    pNode = pDom.SelectSingleNode("sitesResponse/site/siteInfo/siteName")

  '    sb.Append(pNode.InnerText)
  '    sb.Append("$")
  '    pNode = pDom.SelectSingleNode("/sitesResponse/site/siteInfo/siteCode")
  '    sb.Append(pNode.Attributes("network").Value)
  '    sb.Append("$")
  '    sb.Append(pNode.InnerText)
  '    sb.Append("#")
  '    pNode = pDom.SelectSingleNode("/sitesResponse/site/seriesCatalog")
  '    If (pNode.HasChildNodes) Then
  '      For Each pSeriesNode In pNode.ChildNodes
  '        pVariableNode = pSeriesNode.SelectSingleNode("variable")
  '        pCountNode = pSeriesNode.SelectSingleNode("valueCount")
  '        pVCodeNode = pVariableNode.SelectSingleNode("variableCode")
  '        pVNameNode = pVariableNode.SelectSingleNode("variableName")
  '        pIntervalNode = pSeriesNode.SelectSingleNode("variableInterval")
  '        pBdate = pIntervalNode.SelectSingleNode("beginDateTime")
  '        pEDate = pIntervalNode.SelectSingleNode("endDateTime")
  '        sb.Append(pVCodeNode.InnerText & "~" & pVNameNode.InnerText & "~" & pCountNode.InnerText & "~" & pBdate.InnerText & "~" & pEDate.InnerText & "|")
  '      Next
  '    End If
  '  Catch ex As Exception

  '  End Try
  '  Return sb.ToString
  'End Function

  Private Function GetSiteInfoFromXml(ByVal wsResponse As String) As String
    Dim groupName As String = Nothing
    Dim groupNameValue As String = Nothing
    Dim isNote As String = Nothing
    Dim isNetwork As Boolean = False
    Dim isSiteCode As Boolean = False
    Dim isSiteName As Boolean = False
    Dim isVarCodeElement As Boolean = False
    Dim isVarNameElement As Boolean = False
    Dim isStartDtElement As Boolean = False
    Dim isEndDtElement As Boolean = False
    Dim isTimeSingleElement As Boolean = False
    Dim isRealTimeDtElement As Boolean = False
    Dim isCountElement As Boolean = False
    Dim isErrorElement As Boolean = False
    Dim isGroupName As Boolean = False
    Dim isIIDGroup As Boolean = False
    Dim isDVGroup As Boolean = False
    Dim isUVGroup As Boolean = False
    Dim isLat As Boolean = False
    Dim isLong As Boolean = False
    Dim strNetwork As String = Nothing
    Dim varName As String = Nothing
    Dim strVarName As String = Nothing
    Dim strVarCode As String = Nothing
    Dim strBeginDt As String = Nothing
    Dim strEndDt As String = Nothing
    Dim strCount As String = Nothing
    Dim strSiteCode As String = Nothing

    Dim strbData As StringBuilder = New StringBuilder
    Dim siteInfo As New SiteInfo
    Try
      ' dump the siteInfo WS response into an xml file.
      Dim oReader As System.IO.StringReader = New System.IO.StringReader(wsResponse)
      'System.IO.File.WriteAllText(Server.MapPath("tmp\" & Session.SessionID & "siteInfo.xml"), wsResponse)
      ' iterate response XML for sitename, varcode, start, end dates and count (# of observations)
      'Using reader As XmlTextReader = New XmlTextReader(Server.MapPath("tmp\" & Session.SessionID & "siteInfo.xml"))
      Using reader As XmlTextReader = New XmlTextReader(oReader)
        While reader.Read()
          If Not reader.Name Is Nothing And reader.NodeType = XmlNodeType.Element Then
            If reader.Name.Equals("ErrorDescription") Then
              isErrorElement = True
            Else
              isErrorElement = False
            End If

            If reader.Name.Equals("siteCode") Then
              isSiteCode = True
            Else
              isSiteCode = False
            End If

            If reader.Name.Equals("siteName") Then
              isSiteName = True
            Else
              isSiteName = False
            End If

            If reader.Name.Equals("variableCode") Then
              isVarCodeElement = True
            Else
              isVarCodeElement = False
            End If

            If reader.Name.Equals("variableName") Then
              isVarNameElement = True
            Else
              isVarNameElement = False
            End If

            If reader.Name.Equals("beginDateTime") Then
              isStartDtElement = True
            Else
              isStartDtElement = False
            End If

            If reader.Name.Equals("timeSingle") Then
              isTimeSingleElement = True
            Else
              isTimeSingleElement = False
            End If

            If reader.Name.Equals("realTimeDataPeriod") Then
              isRealTimeDtElement = True
            Else
              isRealTimeDtElement = False
            End If


            If reader.Name.Equals("endDateTime") Then
              isEndDtElement = True
            Else
              isEndDtElement = False
            End If

            If reader.Name.Equals("valueCount") Then
              isCountElement = True
            Else
              isCountElement = False
            End If


            If reader.Name.Equals("latitude") Then
              isLat = True
            Else
              isLat = False
            End If

            If reader.Name.Equals("longitude") Then
              isLong = True
            Else
              isLong = False
            End If


          End If

          groupName = reader.GetAttribute("menuGroupName")
          If Not groupName Is Nothing Then

            System.Diagnostics.Debug.WriteLine("Group Name :" & groupName)
            '    strbData.Append("@" & groupName & "#")
            If groupName.Contains("Daily") Then
              isDVGroup = True
              groupNameValue = groupName
            ElseIf groupName.Contains("Instantaneous") Then
              isIIDGroup = True
              groupNameValue = groupName
            ElseIf groupName.Contains("Unit") Then
              isUVGroup = True
              groupNameValue = groupName
            ElseIf groupName.Contains("Variables") Then
              isUVGroup = True
              groupNameValue = groupName
            End If
          End If

          strNetwork = reader.GetAttribute("network")
          If Not strNetwork Is Nothing Then
            siteInfo.network = strNetwork
            strbData.Append(strNetwork & "$")
          End If


          If reader.NodeType = XmlNodeType.Text Then
            If isErrorElement Then
              'Return "<error>" & reader.Value & "</error>"
              If Not reader.Value Is Nothing And reader.Value.Length > 0 Then
                System.Diagnostics.Debug.WriteLine("Error :" & reader.Value)
                Return "<error>" & reader.Value & "</error>"
                Exit Function
              End If
            End If

            If isSiteCode Then
              siteInfo.siteCode = reader.Value().Trim()
              strSiteCode = reader.Value().Trim()
              strbData.Append(reader.Value().Trim() & "#")
            End If

            If isLong Then
              siteInfo.longitude = reader.Value().Trim()
            End If

            If isLat Then
              siteInfo.latitude = reader.Value().Trim()
            End If

            If isSiteName Then
              'System.Diagnostics.Debug.WriteLine("SiteName :" & reader.Value)
              siteInfo.siteName = reader.Value()
              strbData.Append(reader.Value() & "$")
            End If

            If isVarCodeElement Then
              'System.Diagnostics.Debug.WriteLine("VarCode :" & reader.Value)
              strVarCode = reader.Value
              strbData.Append(strVarCode & ApSConfigAHS.K_Sep2)
            End If

            If isVarNameElement Then
              'System.Diagnostics.Debug.WriteLine("VarName :" & reader.Value)
              strVarName = reader.Value()
              If Not groupNameValue Is Nothing Then
                varName = strVarName.Trim() & " (" & groupNameValue & ")" & ApSConfigAHS.K_Sep2
                strbData.Append(varName)
              Else
                varName = strVarName.Trim() & ApSConfigAHS.K_Sep2
                strbData.Append(varName)
              End If

            End If

            If isCountElement Then
              ' System.Diagnostics.Debug.WriteLine("Count :" & reader.Value)
              strCount = reader.Value
              strbData.Append(strCount & ApSConfigAHS.K_Sep2)
            End If

            If isStartDtElement Then
              'System.Diagnostics.Debug.WriteLine("StartDt :" & reader.Value)
              If reader.Value().Length = 0 Then
                strbData.Append("None,")
              Else
                strBeginDt = reader.Value()
                strbData.Append(strBeginDt & ApSConfigAHS.K_Sep2)
              End If
            End If

            If isTimeSingleElement Then
              strBeginDt = reader.Value()
              strbData.Append(strBeginDt & ApSConfigAHS.K_Sep2)

              ' timesingle element is single date, no end date
              strEndDt = reader.Value()
              strbData.Append(strBeginDt & "|")
            End If

            If isRealTimeDtElement Then
              strBeginDt = reader.Value()
              strbData.Append(strBeginDt & ApSConfigAHS.K_Sep2)
              ' real time date element is single date, no end date
              strEndDt = reader.Value()
              strbData.Append(strBeginDt & "|")
            End If

            If isEndDtElement Then
              ' System.Diagnostics.Debug.WriteLine("EndDt :" & reader.Value)
              If reader.Value().Length = 0 Then
                strbData.Append("None,")
              Else
                strEndDt = reader.Value()
                strbData.Append(strEndDt & ApSConfigAHS.K_Sep2)
                siteInfo.addVariableInfo(varName, strVarCode, strBeginDt, strEndDt, strCount)
              End If
              strbData.Append(reader.Value() & "|")
            End If
          End If
        End While
      End Using

      'dumpSiteInfo2DB(siteInfo)
    Catch ex As Exception
      Return "<error>" & ex.Message & " </error>"
    End Try


    Return strbData.ToString

  End Function

  Private Function GetCSVInfo(ByVal tsInputInfo As String) As String
    Dim ds As Long = Date.Now.Ticks
    'Dim wsProxyIID As New edu.sdsc.water.NWISInstantaneousIrregularData
    'Dim wsProxyDV As New edu.sdsc.water.NWISDailyValues
    'Dim epaProxy As New edu.sdsc.water.STORET
    'Dim wsProxy As New edu.sdsc.water.NWISDailyValues
    Dim oNetwork As HISNetwork = Nothing
    Dim wsResponseDV As String = Nothing
    Dim downloadData As String = Nothing
    Dim _startDate As String = Nothing
    Dim _endDate As String = Nothing

    Dim tsInputArray() As String = tsInputInfo.Split(ApSConfigAHS.K_Sep2)

    Dim _network As String = tsInputArray(0)
    Dim siteID As String = tsInputArray(1)
    Dim varCode As String = tsInputArray(2)
    Dim stDate As String = tsInputArray(3)
    Dim enDate As String = tsInputArray(4)
    Dim valueCount As String = Nothing
        Dim bOk As Boolean = True
    Dim sNoData As String = ""
    If Not stDate Is Nothing Then
      Dim stDateArr() As String = stDate.Split("T")
      _startDate = stDateArr(0)
    End If

    If Not enDate Is Nothing Then
      Dim enDateArr() As String = enDate.Split("T")
      _endDate = enDateArr(0)
    End If

    Try

            oNetwork = Me.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
            '
            ' Added 11/08/2007 tw
            '
            ' caching values response on server 
            '
            Dim hashname As String = oNetwork.Name & siteID & varCode & _startDate.ToString & _endDate.ToString

            If Not Session(hashname) Is Nothing Then
                wsResponseDV = Session(hashname).ToString()

            Else

                Try

                    wsResponseDV = ApSConfigAHS.GetTSFromWS(oNetwork, _network & ":" & siteID, _network & ":" & varCode, _startDate, _endDate, "")
                    bOk = Not wsResponseDV.Contains(ApSConfigAHS.K_TagError)
                    If bOk Then Session.Add(hashname, wsResponseDV)
                    'wsProxy.Url = oNetwork.WebServiceURL 
                    'wsResponseDV = wsProxy.GetValues(_network & ":" & siteID, _network & ":" & varCode, _startDate, _endDate, "")

                Catch ex As Exception
                    bOk = False
                    Throw New Exception(ex.Message)
                End Try
            End If

            If bOk = True Then
                'valueCount = toCSV2(wsResponseDV, sNoData)
                valueCount = writeCSV(hashname)
                ApSConfigAHS.AddToZip(Server.MapPath("csv\"), Session.SessionID & "MyData.txt")
            Else
                valueCount = -1
            End If
            'addToZip("csv\" & Session.SessionID & "MyData.txt")
        Catch ex As Exception
            Return ApSConfigAHS.K_TagError & "Error accessing values" & ApSConfigAHS.K_TagErrorEnd
            'Try
            '  wsResponseDV = wsProxyIID.GetValues(oNetwork.Name & ":" & siteID, _network & ":" & varCode, _startDate, _endDate, "")
            '  valueCount = toCSV2(wsResponseDV)
            '  ApSConfigAHS.AddToZip(Server.MapPath("csv\"), Session.SessionID & "MyData.txt")
            'Catch ex1 As Exception
            '  ApSConfigAHS.Write2Log("GetCSVInfo: " & ex1.Message & ", " & ex1.StackTrace, True, -1, False)
            '  Return "<error>Error Accessing Values</error>"
            'End Try
        Finally
            If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogDSTime) = ApSConfigAHS.DebugType.LogDSTime) Then
                ApSConfigAHS.Write2Log("GetCSVInfo:", True, ds, False)
            End If
        End Try
    Return valueCount
  End Function
    '
    ' Added function to write CSV file with metadata contained in GetValuesResponse object
    '

    Private Function writeCSV(ByVal hashname As String) As String

        Dim ds As Long = Date.Now.Ticks
        Dim sb As StringBuilder = New StringBuilder
        Dim xml As String
        Dim gvr As CUAHSI.GetValuesResponse
        Dim i As Integer
        Dim vc As Integer = 0
        If Not Session(hashname) Is Nothing Then
            xml = Session(hashname)
            gvr = New CUAHSI.GetValuesResponse(xml)
            'METADATA
            'write query metadata information
            sb.Append("# Query Parameters:     ").Append(vbCrLf)
            sb.Append("#     QueryDate:        ").Append(gvr.QueryInfo.creationtime.ToString).Append(vbCrLf)
            sb.Append("#     Location:         ").Append(gvr.QueryInfo.locationparam).Append(vbCrLf)
            sb.Append("#     Variable:         ").Append(gvr.QueryInfo.variableparam).Append(vbCrLf)
            sb.Append("#     DateRange:        ").Append(gvr.QueryInfo.begindatetime.ToString).Append(" - ").Append(gvr.QueryInfo.enddatetime.ToString).Append(vbCrLf)
            If Not gvr.QueryInfo.queryurl Is Nothing Then sb.Append("#     QueryURL:         ").Append(gvr.QueryInfo.queryurl).Append(vbCrLf)
            For i = 0 To gvr.QueryInfo.notes.Count - 1
                sb.Append("#                          ").Append(gvr.QueryInfo.notes(i).ToString).Append(vbCrLf)
            Next

            ' Source Info: (if available)

            For Each src As CUAHSI.GetValuesResponse.TSeries.ValueData.Source In gvr.TimeSeries.Values.sources
                sb.Append("#").Append(vbCrLf)
                sb.Append("# Source Information:").Append(vbCrLf)
                If src.organization <> "" Then sb.Append("#     Organization: ").Append(src.organization).Append(vbCrLf)
                If src.sourceid <> "" Then sb.Append("#     SourceID:     ").Append(src.sourceid).Append(vbCrLf)
                If src.srcdesc <> "" Then sb.Append("#     Source Desc:  ").Append(src.srcdesc).Append(vbCrLf)
                If src.srclink <> "" Then sb.Append("#     Website:      ").Append(src.srclink).Append(vbCrLf)
                Dim enu As System.Collections.IEnumerator = src.contactinfo.Keys.GetEnumerator()
                enu.Reset()
                While enu.MoveNext()
                    sb.Append("#       ").Append(enu.Current).Append(":   ").Append(src.contactinfo(enu.Current)).Append(vbCrLf)
                    'enu.MoveNext()
                End While
            Next

            ' write site info:
            sb.Append("#").Append(vbCrLf)
            sb.Append("# Site Information:").Append(vbCrLf)
            sb.Append("#     Name:             ").Append(gvr.TimeSeries.SourceInfo.sitename).Append(vbCrLf)
            sb.Append("#     Code:             ").Append(gvr.TimeSeries.SourceInfo.sitecode).Append(vbCrLf)
            sb.Append("#     Location:         ")
            If Not (gvr.TimeSeries.SourceInfo.latitude = 0 And gvr.TimeSeries.SourceInfo.longitude = 0) Then
                If Not (gvr.TimeSeries.SourceInfo.geographic_srs = Nothing) Then sb.Append("SRS ").Append(gvr.TimeSeries.SourceInfo.geographic_srs)
                sb.Append(" : ").Append(gvr.TimeSeries.SourceInfo.latitude).Append(",").Append(gvr.TimeSeries.SourceInfo.longitude).Append(vbCrLf)
            End If
            If Not (gvr.TimeSeries.SourceInfo.localx = 0 And gvr.TimeSeries.SourceInfo.localy = 0) Then
                sb.Append("#                   ")
                If Not gvr.TimeSeries.SourceInfo.local_srs Is Nothing Then sb.Append(gvr.TimeSeries.SourceInfo.local_srs)
                sb.Append(": ").Append(gvr.TimeSeries.SourceInfo.localx).Append(",").Append(gvr.TimeSeries.SourceInfo.localy).Append(vbCrLf)
            End If

            ' variable details
            sb.Append("#").Append(vbCrLf)
            sb.Append("# Variable Information:").Append(vbCrLf)
            sb.Append("#     Name:             ").Append(gvr.TimeSeries.Variable.variableName).Append(vbCrLf)
            sb.Append("#     Code:             ").Append(gvr.TimeSeries.Variable.variablecode).Append(vbCrLf)
            If Not gvr.TimeSeries.Variable.vocabulary Is Nothing Then sb.Append("#     Vocabulary:       ").Append(gvr.TimeSeries.Variable.vocabulary).Append(vbCrLf)
            If gvr.TimeSeries.Variable.valuetype <> "" Then sb.Append("#     Valuetype:        ").Append(gvr.TimeSeries.Variable.valuetype).Append(vbCrLf)
            If gvr.TimeSeries.Variable.datatype <> "" Then sb.Append("#     Datatype:         ").Append(gvr.TimeSeries.Variable.datatype).Append(vbCrLf)
            If gvr.TimeSeries.Variable.generalcategory <> "" Then sb.Append("#     GeneralCategory:    ").Append(gvr.TimeSeries.Variable.generalcategory).Append(vbCrLf)
            sb.Append("#     NoDataValue:      ").Append(gvr.TimeSeries.Variable.nodataval).Append(vbCrLf)
            If Not gvr.TimeSeries.Variable.units Is Nothing Then
                sb.Append("#      Units:          ").Append(gvr.TimeSeries.Variable.datatype)
                If Not gvr.TimeSeries.Variable.unitsabbr Is Nothing Then sb.Append(" ").Append(gvr.TimeSeries.Variable.unitsabbr)
                If Not gvr.TimeSeries.Variable.unitscode Is Nothing Then sb.Append(", code:").Append(gvr.TimeSeries.Variable.unitscode)
                sb.Append(vbCrLf)
            End If


            ' write out Data
            sb.Append("#").Append(vbCrLf)
            sb.Append("# Data Value Count:").Append(gvr.TimeSeries.Values.ValueCount).Append(vbCrLf)
            sb.Append("#").Append(vbCrLf)
            sb.Append("DATETIME,VALUE").Append(vbCrLf)
            For Each val As CUAHSI.GetValuesResponse.TSeries.ValueData.Value In gvr.TimeSeries.Values.values
                sb.Append(val.date_time.ToString).Append(",").Append(val.value).Append(vbCrLf)
            Next
            Dim outputCSVPath As String = Server.MapPath("csv\" & Session.SessionID & "MyData.txt")
            System.IO.File.WriteAllText(outputCSVPath, sb.ToString)

            vc = gvr.TimeSeries.Values.ValueCount

        End If

        Return vc
    End Function


    Private Function toCSV2(ByVal wsResponse As String, ByRef sNoData As String) As String

        Dim ds As Long = Date.Now.Ticks
        Dim strbData As StringBuilder = New StringBuilder
        Dim settings As New XmlReaderSettings
        settings.IgnoreWhitespace = True
        settings.IgnoreComments = True
        Dim isDTElement As Boolean = False
        Dim isValueElement As Boolean = False
        Dim isErrorElement As Boolean = False
        Dim isDTAttrib As Boolean = False
        Dim dtValue As String = Nothing
        Dim valueCount As String = Nothing
        Dim valueCountStr As String = Nothing
        Try
            If Not wsResponse Is Nothing Then
                ' dump the GetValues WS response into an xml file.
                'Dim xmlDoc As XmlDocument = New XmlDocument()
                'xmlDoc.Load("E:\Projects\HISWEB\NoData.xml")
                'wsResponse = xmlDoc.OuterXml
                Dim oReader As System.IO.StringReader = New System.IO.StringReader(wsResponse)
                Using reader As XmlTextReader = New XmlTextReader(oReader)   '     outPath)
                    While reader.Read
                        If (reader.Name = ApSConfigAHS.K_NoDataValue) Then
                            reader.Read()
                            sNoData = reader.Value
                            reader.Read()
                        End If

                        If Not reader.Name Is Nothing And reader.NodeType = XmlNodeType.Element Then
                            If reader.Name.Equals("ErrorDescription") Then
                                isErrorElement = True
                            Else
                                isErrorElement = False
                            End If
                            If reader.Name.Equals("value") Then
                                isValueElement = True
                            Else
                                isValueElement = False
                            End If
                        End If
                        dtValue = reader.GetAttribute("dateTime")
                        If Not dtValue Is Nothing Then
                            'System.Diagnostics.Debug.WriteLine("DateTime :" & dtValue)
                            strbData.Append(dtValue & ",")
                        End If

                        valueCount = reader.GetAttribute("count")
                        If Not valueCount Is Nothing Then
                            'System.Diagnostics.Debug.WriteLine("DateTime :" & dtValue)
                            strbData.Append("Date,Value")
                            strbData.Append(vbCrLf)
                            valueCountStr = valueCount
                        End If

                        If reader.NodeType = XmlNodeType.Text Then
                            If isErrorElement Then
                                Return "error"
                                Exit Function
                            End If
                            If isValueElement Then
                                strbData.Append(reader.Value())
                                strbData.Append(vbCrLf)
                            End If
                        End If
                    End While
                End Using

                Dim outputCSVPath As String = Server.MapPath("csv\" & Session.SessionID & "MyData.txt")
                System.IO.File.WriteAllText(outputCSVPath, strbData.ToString)
            Else
                Return ApSConfigAHS.K_TagError & "toCSV2, Error Accessing Data" & ApSConfigAHS.K_TagErrorEnd
            End If
        Catch ex As Exception
            If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
                ApSConfigAHS.Write2Log("ToCSV2: " & ex.Message & ", " & ex.StackTrace, True, -1, False)
            End If

            Return ApSConfigAHS.K_TagError & "toCSV2," & ex.Message & ApSConfigAHS.K_TagErrorEnd
        Finally
            If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogDSTime) = ApSConfigAHS.DebugType.LogDSTime) Then
                ApSConfigAHS.Write2Log("ToCSV2:", True, ds, False)
            End If
        End Try
        Return valueCountStr
    End Function

    Private Function GetChartInfo(ByVal chartInput As String) As String
        Dim ds As Long = Date.Now.Ticks
        Dim chartResult As String = Nothing
        '..Commented out, all the service will be using the same WS function definition and dynamically assign the URL at runtime.
        'Dim wsProxyIID As New edu.sdsc.water.NWISInstantaneousIrregularData
        'Dim epaProxy As New edu.sdsc.water.STORET
        'Dim wsProxy As New edu.sdsc.water.NWISDailyValues
        Dim wsResponseDV As String = Nothing
        Dim downloadData As String = Nothing
        Dim _startDate As String = Nothing
        Dim _endDate As String = Nothing
        Dim _network As String = Nothing
        Dim siteID As String = Nothing
        Dim varCode As String = Nothing
        Dim stDate As String = Nothing
        Dim enDate As String = Nothing
        Dim oNetwork As HISNetwork
        Dim sReturn As String
        Dim sNoData As String = ""
        Try
            Dim tsInputArray() As String = chartInput.Split(ApSConfigAHS.K_Sep2)
            _network = tsInputArray(0)
            siteID = tsInputArray(1)
            varCode = tsInputArray(2)
            stDate = tsInputArray(3)
            enDate = tsInputArray(4)

            If Not stDate Is Nothing Then
                Dim stDateArr() As String = stDate.Split("T")
                _startDate = stDateArr(0)
            End If
            If Not enDate Is Nothing Then
                Dim enDateArr() As String = enDate.Split("T")
                _endDate = enDateArr(0)
            End If

            oNetwork = Me.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
            Dim hashname As String = oNetwork.Name & siteID & varCode & _startDate.ToString & _endDate.ToString

            If Not Session(hashname) Is Nothing Then
                wsResponseDV = Session(hashname).ToString()
            Else

                wsResponseDV = ApSConfigAHS.GetTSFromWS(oNetwork, _network & ":" & siteID, _network & ":" & varCode, _startDate, _endDate, "")
                Session.Add(hashname, wsResponseDV)
                'wsProxy.Url = oNetwork.WebServiceURL
                'wsResponseDV = wsProxy.GetValues(_network & ":" & siteID, _network & ":" & varCode, _startDate, _endDate, "")
            End If
            chartResult = toCSV2(wsResponseDV, sNoData)
            sReturn = chartResult & "&ChartInput=" & chartInput & "&" & ApSConfigAHS.K_NoDataValue & "=" & sNoData & "&hashname=" & hashname
        Catch ex As Exception
            sReturn = ApSConfigAHS.K_TagError & ex.Message & ApSConfigAHS.K_TagErrorEnd
            '..Once the instantaneous/daily flow network are seperated, no need for the following code.
            'Try
            '  wsResponseDV = wsProxyIID.GetValues(_network & ":" & siteID, _network & ":" & varCode, _startDate, _endDate, "")
            '  chartResult = toCSV2(wsResponseDV)
            'Catch ex1 As Exception
            '  ApSConfigAHS.Write2Log("GetChartInfo: " & ex1.Message & ", " & ex1.StackTrace, True, -1, False)
            '  chartResult = "<info>No data to plot.</info>"
            '  'chartResult = "<error>" & ex.Message & "</error>"
            'End Try
            If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
                ApSConfigAHS.Write2Log("GetChartInfo:" & ex.Message & ", " & ex.StackTrace, True, ds, False)
            End If

        End Try
        Return sReturn  'chartResult & "&ChartInput=" & chartInput
    End Function

    Private Function GetAddToCartDB(ByVal addToInfo As String) As String
        Dim ds As Long = DateTime.Now.Ticks
        Dim returnVal As String = Nothing
        Dim myConn As SqlConnection = Nothing
        Dim myCmd As SqlCommand = Nothing
        Dim objCntValue As Object
        Dim sInfo As String
        Try

            Dim strCartItem() As String = addToInfo.Split(ApSConfigAHS.K_Sep2)
            ' error handling ?
            'cbAddToCart("ControlType=CUAHSI&EventArg=addToCart&EventVal=currentStationId&"~"&_siteName&"~"&_varName&"~"&_varCode &"~"& _varStartDt &"~"& _varEndDt &"~"& _network & "~" & _valueCount,"AddToCart");   
            Dim siteId As String = strCartItem(0)
            Dim siteName As String = strCartItem(1)
            Dim varName As String = strCartItem(2)
            Dim varCode As String = strCartItem(3)
            Dim beginDt As String = strCartItem(4)
            Dim endDt As String = strCartItem(5)
            Dim network As String = strCartItem(6)
            Dim valueCount As String = strCartItem(7)
            Dim sUserName As String
            sUserName = Page.User.Identity.Name
            If (sUserName = "") Then
                sUserName = ApSConfigAHS.UnknowUser
            End If
            sInfo = ApSConfigAHS.KS_NL & "NETWORK" & ApSConfigAHS.K_ConfirmSep & network
            sInfo = sInfo & ApSConfigAHS.KS_NL & "SITENAME (SiteCode)" & ApSConfigAHS.K_ConfirmSep & siteName & " (" & siteId & ")"
            sInfo = sInfo & ApSConfigAHS.KS_NL & "VARIABLENAME (VariatbleCode)" & ApSConfigAHS.K_ConfirmSep & varName & " (" & varCode & ")"
            myConn = New SqlConnection
            myConn.ConnectionString = ConfigurationManager.ConnectionStrings(ApSConfigAHS.DB_AppDB).ConnectionString
            'myConn.ConnectionString = ConfigurationManager.ConnectionStrings(ApSConfigAHS.K_ODEConn).ConnectionString
            ' check if station and variable code is already added to cart
            myCmd = New SqlCommand
            myCmd.CommandText = ApSConfigAHS.MySelect_IS_DUPLICATE_RECORD
            myCmd.CommandType = CommandType.Text
            myCmd.CommandTimeout = ApSConfigAHS.CMD_TimeOut
            Dim sessionIdParam As SqlParameter = New SqlParameter
            sessionIdParam.ParameterName = "@" & ApSConfigAHS.FD_USESSIONID ' .MySelect_COLUMN_SESSIONID
            sessionIdParam.SqlDbType = SqlDbType.Char
            sessionIdParam.Size = Session.SessionID.Length
            sessionIdParam.Direction = ParameterDirection.Input
            sessionIdParam.Value = Session.SessionID

            Dim siteIdParam As SqlParameter = New SqlParameter
            siteIdParam.ParameterName = "@" & ApSConfigAHS.FD_SiteID   'siteId"        '& ApSConfigAHS.FD_SiteCode       'MySelect_COLUMN_SITECODE
            siteIdParam.SqlDbType = SqlDbType.Char
            siteIdParam.Size = 50
            siteIdParam.Direction = ParameterDirection.Input
            siteIdParam.Value = siteId


            Dim variableCodeParam As SqlParameter = New SqlParameter
            variableCodeParam.ParameterName = "@" & ApSConfigAHS.FD_VARIABLECODE   '.MySelect_COLUMN_VARIABLECODE
            variableCodeParam.SqlDbType = SqlDbType.VarChar
            variableCodeParam.Size = varCode.Length
            variableCodeParam.Direction = ParameterDirection.Input
            variableCodeParam.Value = varCode

            myCmd.Parameters.Add(sessionIdParam)
            myCmd.Parameters.Add(siteIdParam)
            myCmd.Parameters.Add(variableCodeParam)

            myCmd.Connection = myConn
            myCmd.Connection.Open()
            objCntValue = myCmd.ExecuteScalar()

            Dim recCount As Integer = Integer.Parse(objCntValue.ToString())
            If recCount > 0 Then
                returnVal = "The item aready exists in your data cart." & ApSConfigAHS.KS_NL & sInfo
            Else
                myCmd.Parameters.Clear()
                ' myCmd = New SqlCommand
                myCmd.CommandText = ApSConfigAHS.MySelect_INSERT_QUERY
                myCmd.CommandType = CommandType.Text
                myCmd.CommandTimeout = ApSConfigAHS.CMD_TimeOut
                Dim siteNameParam As SqlParameter = New SqlParameter
                siteNameParam.ParameterName = "@" & ApSConfigAHS.FD_SiteName          '.MySelect_COLUMN_SITENAME
                siteNameParam.SqlDbType = SqlDbType.Char
                siteNameParam.Size = 50
                siteNameParam.Direction = ParameterDirection.Input
                siteNameParam.Value = siteName

                Dim networkParam As SqlParameter = New SqlParameter
                networkParam.ParameterName = "@" & ApSConfigAHS.FD_NETWORK            'MySelect_COLUMN_NETWORK
                networkParam.SqlDbType = SqlDbType.Char
                networkParam.Size = 15
                networkParam.Direction = ParameterDirection.Input
                networkParam.Value = network

                Dim variableNameParam As SqlParameter = New SqlParameter
                variableNameParam.ParameterName = "@" & ApSConfigAHS.FD_VARIABLENAME  ' .MySelect_COLUMN_VARIABLENAME
                variableNameParam.SqlDbType = SqlDbType.Text
                variableNameParam.Size = varName.Length
                variableNameParam.Direction = ParameterDirection.Input
                variableNameParam.Value = varName


                Dim beginDtParam As SqlParameter = New SqlParameter
                beginDtParam.ParameterName = "@" & ApSConfigAHS.FD_BEGINDATE       ' .MySelect_COLUMN_BEGINDATE
                beginDtParam.SqlDbType = SqlDbType.Char
                beginDtParam.Size = beginDt.Length
                beginDtParam.Direction = ParameterDirection.Input
                beginDtParam.Value = beginDt

                Dim endDtParam As SqlParameter = New SqlParameter
                endDtParam.ParameterName = "@" & ApSConfigAHS.FD_ENDDATE         'MySelect_COLUMN_ENDDATE
                endDtParam.SqlDbType = SqlDbType.Char
                endDtParam.Size = endDt.Length
                endDtParam.Direction = ParameterDirection.Input
                endDtParam.Value = endDt

                Dim valueCountParam As SqlParameter = New SqlParameter
                valueCountParam.ParameterName = "@" & ApSConfigAHS.FD_ValueCount  'MySelect_COLUMN_VALUECOUNT
                valueCountParam.SqlDbType = SqlDbType.Int
                valueCountParam.Size = 25
                valueCountParam.Direction = ParameterDirection.Input
                valueCountParam.Value = valueCount

                Dim pUserParam As SqlParameter = New SqlParameter
                pUserParam.ParameterName = "@" & ApSConfigAHS.FD_UserName
                pUserParam.SqlDbType = SqlDbType.Char
                pUserParam.Size = 50
                pUserParam.Direction = ParameterDirection.Input
                pUserParam.Value = sUserName

                myCmd.Parameters.Add(sessionIdParam)
                myCmd.Parameters.Add(siteIdParam)
                myCmd.Parameters.Add(siteNameParam)
                myCmd.Parameters.Add(networkParam)
                myCmd.Parameters.Add(variableNameParam)
                myCmd.Parameters.Add(variableCodeParam)
                myCmd.Parameters.Add(beginDtParam)
                myCmd.Parameters.Add(endDtParam)
                myCmd.Parameters.Add(valueCountParam)
                myCmd.Parameters.Add(pUserParam)

                myCmd.Connection = myConn
                ' myCmd.Connection.Open()
                myCmd.ExecuteNonQuery()
                returnVal = "Data item is added to the data cart." & ApSConfigAHS.KS_NL & sInfo
            End If

        Catch ex As Exception
            ApSConfigAHS.Write2Log("GetAddToCartDB: " & ex.Message & ", " & ex.StackTrace, True, -1, False)
            returnVal = "<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("GetAddToCartDB:", True, ds, False)
            End If
        End Try

        Return returnVal

    End Function

    'Private Function GetVariableList(ByVal selectedStns As String) As String
    '    Dim varList As String = ""
    '    Dim myConn As SqlConnection = Nothing
    '    Dim myCmd As SqlCommand = Nothing
    '    Dim myReader As SqlDataReader = Nothing

    '    Try


    '        myConn = New SqlConnection
    '        myConn.ConnectionString = ConfigurationManager.ConnectionStrings("ODEAccess").ConnectionString

    '        myCmd = New SqlCommand
    '        Dim sqlStr As String = "SELECT     VariableID, VariableCode, VariableName   FROM (Variables) WHERE (VariableID IN"
    '        sqlStr &= " (SELECT     VariableID  FROM(SeriesCatalog) WHERE      (SiteCode IN  ('199506')))) "
    '        myCmd.CommandText = sqlStr
    '        myCmd.CommandType = CommandType.Text
    '        myCmd.Connection = myConn
    '        myCmd.Connection.Open()
    '        myReader = myCmd.ExecuteReader()


    '    Catch ex As Exception
    '        varList = "<error>" & ex.Message & "</error>"
    '    End Try

    '    Return varList

    'End Function

    Protected Function GetControlByName(ByVal oPage As System.Web.UI.Page, ByVal sName As String) As Control
        Dim o As Control = Nothing
        Try
            o = oPage.FindControl(sName)

        Catch ex As Exception
            o = Nothing
        End Try
        Return o
    End Function

    Protected Function GetLayerIndex(ByVal oPage As System.Web.UI.Page, ByVal sMapControlName As String, ByVal sLayerName As String) As Integer
        Dim iReturn As Integer = -1
        Try
            If Not oPage.Session(ApSConfigAHS.KS_ACTIVELAYER) Is Nothing Then
                iReturn = CType(oPage.Session(ApSConfigAHS.KS_ACTIVELAYER), Integer)
            Else
                Dim pMapCtrl As ESRI.ArcGIS.ADF.Web.UI.WebControls.Map
                If sMapControlName = "" Then sMapControlName = "Map1"
                pMapCtrl = CType(GetControlByName(oPage, sMapControlName), ESRI.ArcGIS.ADF.Web.UI.WebControls.Map)
                Dim mf As MapFunctionality = pMapCtrl.GetFunctionality(ApSConfigAHS.MapServiceName)      'ApSConfigAHS.mResourceIndex)
                Dim pGisRecs As ESRI.ArcGIS.ADF.Web.DataSources.IGISResource = mf.Resource
                Dim pGisRecsLocal As ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapResourceLocal = CType(pGisRecs, ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapResourceLocal)
                Dim mapDesc As ESRI.ArcGIS.ADF.ArcGISServer.MapDescription = mf.MapDescription
                Dim layerDesc() As ESRI.ArcGIS.ADF.ArcGISServer.LayerDescription = mapDesc.LayerDescriptions
                Dim pMapLayerInfos() As ESRI.ArcGIS.ADF.ArcGISServer.MapLayerInfo = pGisRecsLocal.MapServerInfo.MapLayerInfos
                iReturn = GetLayerIndex(pMapLayerInfos, sLayerName)
            End If

        Catch ex As Exception
            iReturn = -1
        End Try
        Return iReturn
    End Function

    Protected Function GetLayerIndex(ByVal cMapLayerInfos() As ESRI.ArcGIS.ADF.ArcGISServer.MapLayerInfo, ByVal sName As String) As Integer

        Dim iL As Integer = -1
        Dim i As Integer
        Dim mlInfo As ESRI.ArcGIS.ADF.ArcGISServer.MapLayerInfo
        Dim s As String = ""
        Try
            s = sName.ToLower()

            For i = 0 To cMapLayerInfos.Length - 1
                mlInfo = cMapLayerInfos(i)
                If mlInfo.Name.ToLower() = s Then
                    iL = i
                    Exit For
                End If
            Next
        Catch ex As Exception
            iL = -1
        End Try

        Return iL

    End Function

    Sub drawPrevSelectedExtent()
        Dim resource_index As Integer = 0

        Dim mapctrl As ESRI.ArcGIS.ADF.Web.UI.WebControls.Map = CType(Me.Page.FindControl("Map1"), ESRI.ArcGIS.ADF.Web.UI.WebControls.Map)
        oActiveNetwork = mapctrl.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
        Dim sourcelayername As String = oActiveNetwork.LayerName   'CStr(mapctrl.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK))

        Dim mf As ESRI.ArcGIS.ADF.Web.DataSources.IMapFunctionality = CType(mapctrl.GetFunctionality(ApSConfigAHS.MapServiceName), ESRI.ArcGIS.ADF.Web.DataSources.IMapFunctionality)
        'Dim mf As ESRI.ArcGIS.ADF.Web.DataSources.IMapFunctionality = CType(mapctrl.GetFunctionality(resource_index), ESRI.ArcGIS.ADF.Web.DataSources.IMapFunctionality)
        Dim gisresource As ESRI.ArcGIS.ADF.Web.DataSources.IGISResource = mf.Resource


        Dim mappoly As ESRI.ArcGIS.ADF.Web.Geometry.Envelope = CType(Me.Page.Session(ApSConfigAHS.KS_SELECTED_CURRENTEXT_SAVED), ESRI.ArcGIS.ADF.Web.Geometry.Envelope)
        If Not mappoly Is Nothing Then
            Me.Page.Session(ApSConfigAHS.KS_SELECTED_CURRENTEXT) = mappoly
            Me.Page.Session(ApSConfigAHS.KS_SELECTED_CURRENTEXT_SAVED) = Nothing
        Else
            ' if not saved extent, draw current extent
            mappoly = CType(Me.Page.Session(ApSConfigAHS.KS_SELECTED_CURRENTEXT), ESRI.ArcGIS.ADF.Web.Geometry.Envelope)
        End If

        Dim supported As Boolean = gisresource.SupportsFunctionality(GetType(ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality))
        If supported And Not mappoly Is Nothing Then
            Dim qfunc As ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality = CType(gisresource.CreateFunctionality(GetType(ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality), Nothing), ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality)

            Dim lids As String() = Nothing
            Dim lnames As String() = Nothing
            qfunc.GetQueryableLayers(Nothing, lids, lnames)

            Dim layer_index As Integer = 1
            Dim i As Integer = 0
            Do While i < lnames.Length
                If lnames(i) = sourcelayername Then
                    If TypeOf lids(i) Is String Then
                        If (Not Integer.TryParse(CStr(lids(i)), layer_index)) Then
                            layer_index = i
                        End If
                    Else
                        layer_index = i
                    End If
                    Exit Do
                Else
                    layer_index = 0  ' default selected layer
                End If
                i += 1
            Loop

            ' If TypeOf qfunc.Resource Is ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapResourceLocal Then
            Dim ags_mf As ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapFunctionality = CType(mf, ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapFunctionality)
            Dim ags_mr As ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapResourceBase = CType(qfunc.Resource, ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapResourceBase)
            Dim mapdescription As ESRI.ArcGIS.ADF.ArcGISServer.MapDescription
            mapdescription = ags_mf.MapDescription

            Dim layerdescs As ESRI.ArcGIS.ADF.ArcGISServer.LayerDescription() = mapdescription.LayerDescriptions

            Dim mli As ESRI.ArcGIS.ADF.ArcGISServer.MapLayerInfo() = ags_mr.MapServerInfo.MapLayerInfos

            Dim featureLayer As ESRI.ArcGIS.ADF.ArcGISServer.LayerDescription = layerdescs(layer_index)

            If featureLayer Is Nothing Then
                ' throw exception because feature layer is not valid
                Throw New Exception("featurelayer null")
            Else

                Dim envelopen As EnvelopeN = ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.Converter.FromAdfEnvelope(mappoly)

                Dim sf As ESRI.ArcGIS.ADF.ArcGISServer.SpatialFilter = New ESRI.ArcGIS.ADF.ArcGISServer.SpatialFilter()
                sf.FilterGeometry = envelopen
                sf.GeometryFieldName = "SHAPE"
                sf.SpatialRel = ESRI.ArcGIS.ADF.ArcGISServer.esriSpatialRelEnum.esriSpatialRelIntersects

                Dim msdp As MapServerProxy = ags_mr.MapServerProxy
                Dim irgbc As RgbColor = New RgbColor()
                irgbc.Red = 255
                irgbc.Green = 255
                irgbc.Blue = 0
                irgbc.AlphaValue = 255

                featureLayer.SelectionColor = irgbc
                Dim ifid As ESRI.ArcGIS.ADF.ArcGISServer.FIDSet = msdp.QueryFeatureIDs(mapdescription.Name, featureLayer.LayerID, sf)
                featureLayer.SelectionFeatures = ifid.FIDArray

                Dim siteCodes As String = ""

                Dim recSet As ESRI.ArcGIS.ADF.ArcGISServer.RecordSet = msdp.QueryFeatureData(mapdescription.Name, featureLayer.LayerID, sf)
                Dim j As Integer
                Dim recd As ESRI.ArcGIS.ADF.ArcGISServer.Record
                Dim strSelectedStationList As String = ""
                Dim selSiteCount As Integer = 0

                For j = 0 To recSet.Records.Length - 1
                    recd = recSet.Records(j)
                    siteCodes &= CStr(recd.Values(7)) & ApSConfigAHS.K_PP   '"|"
                    'selSiteCount += 1
                Next

                'Session(ApSConfigAHS.SELECTED_STATION_LIST) = siteCodes
                mapctrl.Refresh()


            End If
        End If
        '  End If

    End Sub

    'Sub ClearSelectedFeatures()
    '  Dim resource_index As Integer = 0

    '  Dim pMapCtrl As ESRI.ArcGIS.ADF.Web.UI.WebControls.Map = CType(Me.Page.FindControl("Map1"), ESRI.ArcGIS.ADF.Web.UI.WebControls.Map)
    '  Dim mf As MapFunctionality = CType(pMapCtrl.GetFunctionality(resource_index), MapFunctionality)
    '  Dim pGisRecs As ESRI.ArcGIS.ADF.Web.DataSources.IGISResource = mf.Resource
    '  Dim pGisRecsLocal As ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapResourceLocal = CType(pGisRecs, ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapResourceLocal)
    '  Dim pMapDesc As ESRI.ArcGIS.ADF.ArcGISServer.MapDescription = mf.MapDescription
    '  Dim pLayerDescs() As ESRI.ArcGIS.ADF.ArcGISServer.LayerDescription = pMapDesc.LayerDescriptions
    '  Dim pLayerDesc As ESRI.ArcGIS.ADF.ArcGISServer.LayerDescription

    '  Dim mappoly As ESRI.ArcGIS.ADF.Web.Geometry.Envelope = CType(Me.Page.Session(ApSConfigAHS.KS_SELECTED_CURRENTEXT), ESRI.ArcGIS.ADF.Web.Geometry.Envelope)
    '  If Not mappoly Is Nothing Then
    '    Me.Page.Session(ApSConfigAHS.KS_SELECTED_CURRENTEXT_SAVED) = mappoly
    '    Me.Page.Session(ApSConfigAHS.KS_SELECTED_CURRENTEXT) = Nothing
    '  End If


    '  For Each pLayerDesc In pLayerDescs
    '    pLayerDesc.SelectionFeatures = Nothing
    '  Next
    '  Session(ApSConfigAHS.SELECTED_STATION_LIST) = Nothing
    '  pMapCtrl.Refresh()
    'End Sub

    Protected Sub Toolbar1_CommandClick(ByVal sender As Object, ByVal args As ESRI.ArcGIS.ADF.Web.UI.WebControls.ToolbarCommandClickEventArgs) Handles Toolbar1.CommandClick
        Dim sCmd As String = args.CommandName

        Select Case (sCmd)
            Case ApSConfigAHS.TOOL_SELECTED_CLEARSELECTED
                ApSConfigAHS.ClearSelectedFeatures(Map1, True)

                'Case ApSConfigAHS.TOOL_SELECTED_PREVIOUSSELECTED
                '  drawPrevSelectedExtent()
                'Case "cmdTest"
                '  Dim pCon As HISWEB2AO.IWEB2AOConnector
                '  Dim gisresource As ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapResourceLocal = MapResourceManager1.GetResource(0)
                '  Dim mapContext As IServerContext = gisresource.ServerContextInfo.ServerContext
                '  pCon = mapContext.CreateObject("HISWEB2AO.WEB2AOConn")
                '  sCmd = pCon.DoTest("E:\Inetpub\wwwroot\HISWEB\dboutput\TestMyDB.mdb")

            Case Else

        End Select

    End Sub

    Delegate Function GetCSValues(ByVal tsInputInfo As String) As String

    Public Function DoGetCSV(ByVal tsInputInfo As String) As String
        Dim pDelegate As GetCSValues = New GetCSValues(AddressOf GetCSVInfo)
        Dim pAR As IAsyncResult = pDelegate.BeginInvoke(tsInputInfo, Nothing, Nothing)
        Dim s As String
        pAR.AsyncWaitHandle.WaitOne()

        'Do Until pAR.IsCompleted
        '  System.Diagnostics.Debug.WriteLine("Waiting " & CStr(i))
        '  System.Threading.Thread.Sleep(4000)
        '  i = i + 1
        'Loop

        s = pDelegate.EndInvoke(pAR)
        Return s
    End Function
    Private Function TestConnection() As String
        Dim myConn As SqlConnection = Nothing
        Dim myCmd As SqlCommand = Nothing
        Dim sCon As String = ""
        Dim s As String = ""
        Dim oNetwork As HISNetwork
        Dim sSQL As String = "Select Count(SITEID) as [CNT] From SeriesCatalog"
        Dim ds As Long = Date.Now.Ticks
        Try
            oNetwork = Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
            sCon = oNetwork.DBConnection   '"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\92Data\UCSD_Download\EPA_STORET_sites.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
            myConn = New SqlConnection
            myConn.ConnectionString = sCon

            ' check if station and variable code is already added to cart
            myCmd = New SqlCommand
            myCmd.CommandText = sSQL
            myCmd.CommandType = CommandType.Text
            myCmd.Connection = myConn
            myCmd.CommandTimeout = ApSConfigAHS.CMD_TimeOut
            myConn.Open()
            s = myCmd.ExecuteScalar
        Catch ex As Exception
            If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
                ApSConfigAHS.Write2Log("TestCon:" & ex.Message & ", " & ex.StackTrace, True, -1, 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.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("Conn:" & s & " " & sCon & "," & sSQL, False, ds, False)
            End If

        End Try
        Return s
    End Function


    Protected Overrides Sub Finalize()
        MyBase.Finalize()
    End Sub

    Protected Sub Map1_ExtentChanged(ByVal sender As Object, ByVal args As ESRI.ArcGIS.ADF.Web.UI.WebControls.ExtentEventArgs) Handles Map1.ExtentChanged
        Try
            Page.Session(ApSConfigAHS.K_CurrentExt) = args.NewExtent
            Page.Session(ApSConfigAHS.K_LastExt) = args.OldExtent
        Catch ex As Exception

        End Try
    End Sub
End Class
