Imports System.Data.SqlClient
Imports System.IO
Imports System.IO.File
Imports System.Xml
Imports System.Xml.XPath
Imports System
Imports System.Data
Imports ICSharpCode.SharpZipLib.Zip
Imports ESRI.ArcGIS.Carto
Imports ESRI.ArcGIS.ADF.ArcGISServer
Imports ESRI.ArcGIS.Geodatabase

Imports ESRI.ArcGIS.ADF.Web
Imports ESRI.ArcGIS.ADF.Web.UI.WebControls
Imports ESRI.ArcGIS.ADF.Web.UI.WebControls.Tools
Imports ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer
Imports ESRI.ArcGIS.ADF.Web.DataSources
Imports ESRI.ArcGIS.Server

Imports ESRI.ArcGIS.esriSystem
Imports ESRI.ArcGIS.Geometry

Partial Class Cart
  Inherits System.Web.UI.Page
  Private Const K_CartMsg As String = "CARTMSG"
  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
      bindGrid(Me.CheckAll.Checked)
    ElseIf Not IsPostBack And Not IsCallback Then
      bindGrid(Me.CheckAll.Checked)
    End If
    Label1.Text = ""
  End Sub

  Private Sub bindGrid(ByVal bShowAll)
    Dim sUser As String = ""
    Dim sSelectCmd As String
    Dim sSelectBase As String = "SELECT ID, SiteCode, SiteName, Network, VariableName, VariableCode, ValueCount, BeginDate, EndDate FROM MySelect"
    Try
      sUser = Page.User.Identity.Name
      If (sUser.Length = 0) Then
        sUser = ApSConfigAHS.UnknowUser
      End If
      SqlDataSource1.ConnectionString = ConfigurationManager.ConnectionStrings(ApSConfigAHS.DB_AppDB).ConnectionString
      If bShowAll = False Then
        sSelectCmd = sSelectBase & " WHERE USessionID='" & Session.SessionID & "' AND " & ApSConfigAHS.FD_UserName & "='" & sUser & "'"
      Else
        If (sUser.ToLower = "admin") Then
          sSelectCmd = "SELECT ID, UserName, SiteCode, SiteName, Network, VariableName, VariableCode, ValueCount, BeginDate, EndDate FROM MySelect ORDER BY USERNAME"
        Else
          sSelectCmd = sSelectBase & " WHERE " & ApSConfigAHS.FD_UserName & "='" & sUser & "'"
        End If
      End If
      SqlDataSource1.SelectCommand = sSelectCmd
      'SqlDataSource1.ConnectionString = ConfigurationManager.ConnectionStrings(ApSConfigAHS.K_ODEConn).ConnectionString
      'SqlDataSource1.SelectCommand = ApSConfigAHS.CART_BINDGRID_SQL
      GridView1.DataSource = SqlDataSource1
      GridView1.DataBind()
      Me.TitleLabel.Text = "Your data cart contains " & GridView1.Rows.Count & " item(s). User=" & sUser
    Catch ex As Exception

    End Try
  End Sub

  Protected Sub DeleteSelected_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles DeleteSelected.Click
    Dim checkbox As CheckBox = Nothing
    Dim strData As String = Nothing
    Dim i, j As Integer
    If GridView1.Rows.Count > 0 Then
      j = ApSConfigAHS.GetCellIndex(Me.Page, "GridView1", ApSConfigAHS.FD_ID)
      strData = ""
      For i = 0 To GridView1.Rows.Count - 1
        checkbox = GridView1.Rows(i).FindControl("CheckBox1")
        If Not checkbox Is Nothing And checkbox.Checked Then
          If strData = "" Then
            strData = GridView1.Rows(i).Cells(j).Text.Trim
          Else
            strData = strData & "," & GridView1.Rows(i).Cells(j).Text.Trim
          End If

        End If
      Next
      If strData.Length > 0 Then
        DeleteSelectedRecs(strData)
        bindGrid(Me.CheckAll.Checked)
      Else
        Session(K_CartMsg) = "No items are selected to delete."
        'Label1.Text = "No records are selected."
      End If
    Else
      Session(K_CartMsg) = "No items are selected to delete."  'No itmes in the data cart."
    End If
  End Sub

  Private Sub DeleteSelectedRecs(ByVal recId As String)
    'System.Diagnostics.Debug.WriteLine(recId)
    Dim delIDs As String = Nothing
    Dim myConn As SqlConnection = Nothing
    Dim myCmd As SqlCommand = Nothing
    Dim myReader As SqlDataReader = Nothing
    delIDs = recId
    Try
      myConn = New SqlConnection
      myConn.ConnectionString = ConfigurationManager.ConnectionStrings(ApSConfigAHS.DB_AppDB).ConnectionString   'ConfigurationManager.ConnectionStrings(ApSConfigAHS.K_ODEConn).ConnectionString
      'Dim strSql As String = "DELETE FROM MySelect  WHERE ID IN (" & delIDs & " )  AND  USessionID ='" & "nm3pf1455nmpmyv4ikam4fb5" & "'"
      Dim strSql As String = "DELETE FROM MySelect  WHERE ID IN (" & delIDs & " )" '  AND  USessionID ='" & Session.SessionID & "'"

      myCmd = New SqlCommand
      myCmd.CommandText = strSql
      myCmd.CommandType = CommandType.Text

      myCmd.Connection = myConn
      myCmd.Connection.Open()
      myCmd.ExecuteNonQuery()

    Catch ex As Exception

    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
    End Try
  End Sub

  Protected Sub SelectAll_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SelectAll.Click
    ApSConfigAHS.CheckboxSelectAll(Me.Page, "GridView1", "CheckBox1", True)
  End Sub

  Protected Sub ClearAll_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ClearAll.Click
    HyperLink1.Visible = False
    ApSConfigAHS.CheckboxSelectAll(Me.Page, "GridView1", "CheckBox1", False)
  End Sub
  Protected Sub dwnCart_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles dwnCart.Click
    HyperLink1.Visible = False
    Dim err_msgArr() As String = Nothing
    Dim sName As String = "d" & getDateTimeAsString(Date.Now, True)
    Dim sFileName As String = sName & "MyDB.mdb"
    Dim sZipFileName As String
    sZipFileName = System.IO.Path.ChangeExtension(sFileName, "zip")

    Dim s As String = downloadCart2(sFileName)
    Dim outFileName As String = ""
    If Not s Is Nothing Then
      If s.StartsWith("dboutput") Then
        ' outFileName = s.Substring(s.LastIndexOf("/") & 1)
        Page.Response.Redirect(s)
        'Page.Response.WriteFile(Server.MapPath("dboutput\" & sZipFileName))
        'Page.Response.WriteFile(s)
        'Label1.Text = ""
        'Label1.Visible = False
      Else
        Session(K_CartMsg) = s
      End If
    End If
  End Sub

  Private Function downloadCart2(ByVal sFileName) As String
    Dim ddCartResult As String = "ok"
    Dim zipFilePath As String = Nothing
    Dim outPath As String = Server.MapPath("dboutput\")
    Dim FullFileName As String = outPath & sFileName
    Dim sName As String
    Try
      Dim _dTable As DataTable = gridView2DataTable2()
      System.IO.File.Copy(Server.MapPath(ApSConfigAHS.DBForDownLoad), FullFileName, True)
      BatchUpdateMySelect(_dTable, 100, FullFileName)
      sName = ApSConfigAHS.AddToZip(Server.MapPath("dboutput\"), sFileName, True)
      ddCartResult = "dboutput/" & sName '& "MyCart.zip"
      'ddCartResult = "http://" & Server.MachineName & "/" & ApSConfigAHS.AppName & "/dboutput/" & sName '& "MyCart.zip"
    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("DownloadCart2:" & ex.Message & ", " & ex.StackTrace, True, -1, False)
      End If
      ddCartResult = ex.Message
    End Try
    Return ddCartResult
  End Function

  Public Sub BatchUpdateMySelect( _
ByVal dataTable As DataTable, ByVal batchSize As Int32, ByVal outPath As String)
    ' Assumes GetConnectionString() returns a valid connection string.
    Dim myConn As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection
    myConn.ConnectionString = ApSConfigAHS.MyDBConBase & outPath  '"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
    Dim connectionString As String = myConn.ConnectionString
    ' Connect to the AdventureWorks database.
    Using connection As New OleDb.OleDbConnection(connectionString)
      ' Create a SqlDataAdapter.
      Dim adapter As New OleDb.OleDbDataAdapter

      'Set the INSERT command and parameter.
      '   adapter.InsertCommand = New OleDb.OleDbCommand( _
      '  "INSERT INTO VariableValues (Value_,DateTime_, SiteID, VariableID) VALUES (@ValueInfo,@DataTimeValue,@SiteCode,@VariableCode);", _
      ' connection)

      adapter.InsertCommand = New OleDb.OleDbCommand("INSERT INTO MySelect(SiteCode,SiteName,Network,VariableName,VariableCode,ObservationCount,BeginDate,EndDate) VALUES (@SiteCode,@SiteName,@Network,@VariableName,@VariableCode,@ValueCount,@BeginDate,@EndDate);", connection)
      '"INSERT INTO VariableValues (Value_) VALUES (@ValueInfo);", _
      '"INSERT INTO VariableValues (DateTime_) VALUES (@DataTimeValue);", _
      '"INSERT INTO VariableValues (Value_,DateTime_) VALUES (@ValueInfo,@DataTimeValue);", _

      adapter.InsertCommand.Parameters.Add("@SiteCode", _
       OleDb.OleDbType.VarChar, 50, "SiteCode")

      adapter.InsertCommand.Parameters.Add("@SiteName", _
         OleDb.OleDbType.VarChar, 50, "SiteName")

      adapter.InsertCommand.Parameters.Add("@Network", _
               OleDb.OleDbType.VarChar, 50, "Network")

      adapter.InsertCommand.Parameters.Add("@VariableName", _
              OleDb.OleDbType.VarChar, 50, "VariableName")

      adapter.InsertCommand.Parameters.Add("@VariableCode", _
               OleDb.OleDbType.VarChar, 50, "VariableCode")

      adapter.InsertCommand.Parameters.Add("@ValueCount", _
               OleDb.OleDbType.Integer, 50, "ValueCount")

      adapter.InsertCommand.Parameters.Add("@BeginDate", _
               OleDb.OleDbType.VarChar, 50, "BeginDate")

      adapter.InsertCommand.Parameters.Add("@EndDate", _
               OleDb.OleDbType.VarChar, 50, "EndDate")

      adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.None
      ' Set the batch size.
      'adapter..UpdateBatchSize = batchSize

      ' Execute the update.
      adapter.Update(dataTable)
    End Using
  End Sub

  Public Sub BatchUpdate(ByVal dataTable As DataTable, ByVal batchSize As Int32, ByVal outPath As String)
    ' Assumes GetConnectionString() returns a valid connection string.
    Dim myConn As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection
    myConn.ConnectionString = ApSConfigAHS.MyDBConBase & outPath    '"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
    Dim connectionString As String = myConn.ConnectionString
    ' Connect to the AdventureWorks database.
    Using connection As New OleDb.OleDbConnection(connectionString)
      ' Create a SqlDataAdapter.
      Dim adapter As New OleDb.OleDbDataAdapter

      'Set the INSERT command and parameter.
      adapter.InsertCommand = New OleDb.OleDbCommand( _
      "INSERT INTO VariableValues (TSVALUE,TSDateTime, SiteID, VariableID, FeatureID, TSTypeID) VALUES (@ValueInfo,@DataTimeValue,@SiteCode,@VariableCode,@FeatureID,@TSTypeID);", _
      connection)

      '"INSERT INTO VariableValues (Value_) VALUES (@ValueInfo);", _
      '"INSERT INTO VariableValues (DateTime_) VALUES (@DataTimeValue);", _
      '"INSERT INTO VariableValues (Value_,DateTime_) VALUES (@ValueInfo,@DataTimeValue);", _

      adapter.InsertCommand.Parameters.Add("@ValueInfo", _
       OleDb.OleDbType.Double, 50, "ValueInfo")

      adapter.InsertCommand.Parameters.Add("@DataTimeValue", _
         OleDb.OleDbType.DBTimeStamp, 50, "DateTimeValue")

      adapter.InsertCommand.Parameters.Add("@SiteCode", _
               OleDb.OleDbType.VarChar, 50, "SiteCode")

      adapter.InsertCommand.Parameters.Add("@VariableCode", _
               OleDb.OleDbType.VarChar, 50, "VariableCode")

      adapter.InsertCommand.Parameters.Add("@FeatureID", _
               OleDb.OleDbType.Integer, 10, "FeatureID")

      adapter.InsertCommand.Parameters.Add("@TSTypeID", _
               OleDb.OleDbType.Integer, 10, "TSTypeID")

      adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.None
      ' Set the batch size.
      'adapter..UpdateBatchSize = batchSize

      ' Execute the update.
      adapter.Update(dataTable)
    End Using
  End Sub

  Public Shared Function getDateTimeAsString(ByVal d As Date, Optional ByVal bPad0 As Boolean = False, Optional ByRef yr As Integer = 0, Optional ByRef mon As Integer = 0, Optional ByRef day As Integer = 0, _
Optional ByRef hr As Integer = 0, Optional ByRef min As Integer = 0, Optional ByRef s As Integer = 0, Optional ByRef ms As Integer = 0) As String
    '*****************************************************************
    ' Copyright, 2004 ESRI, All Rights Reserved.
    '*****************************************************************
    'Description: return the date/time
    'History: zye 12-16-2004 @ 12:38:52

    '*****************************************************************
    yr = d.Year
    mon = d.Month
    day = d.Day
    hr = d.Hour
    min = d.Minute
    s = d.Second
    ms = d.Millisecond
    Dim sb As System.Text.StringBuilder
    sb = New System.Text.StringBuilder(CStr(yr))
    If bPad0 = True Then
      sb.Append(IIf((mon < 10), "0" & CStr(mon), CStr(mon)))
      sb.Append(IIf((day < 10), "0" & CStr(day), CStr(day)))
      sb.Append(IIf((hr < 10), "0" & CStr(hr), CStr(hr)))
      sb.Append(IIf((min < 10), "0" & CStr(min), CStr(min)))
      sb.Append(CStr(s))
    Else
      sb.Append(CStr(mon))
      sb.Append(CStr(day))
      sb.Append(CStr(hr))
      sb.Append(CStr(min))
      sb.Append(CStr(s))
    End If
    Return sb.ToString

  End Function

  Public Function gridView2DataTable2() As DataTable
    Dim dTable As DataTable = Nothing
    Dim Row1 As DataRow
    Dim strData As String = Nothing
    Dim strDataArray() As String = Nothing

    Dim checkbox As CheckBox
    Dim i, j As Integer
    Dim numRecs As Integer = 0

    Try
      If GridView1.Rows.Count > 0 Then
        dTable = New DataTable(ApSConfigAHS.TB_MYSELECT)
        Dim SiteCode As DataColumn = New DataColumn(ApSConfigAHS.FD_SiteCode)  ' "SiteCode")
        SiteCode.DataType = System.Type.GetType("System.String")
        dTable.Columns.Add(SiteCode)


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

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


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

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

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

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

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

        For i = 0 To GridView1.Rows.Count - 1
          checkbox = GridView1.Rows(i).FindControl("CheckBox1")
          If Not checkbox Is Nothing And checkbox.Checked Then
            Try
              strData = ""
              Row1 = dTable.NewRow()
              For j = 1 To GridView1.Rows(i).Cells.Count - 1
                System.Diagnostics.Debug.WriteLine(GridView1.Rows(i).Cells(j).Text)
                strData &= GridView1.Rows(i).Cells(j).Text.Trim & ApSConfigAHS.K_Sep2
              Next

              strDataArray = strData.Split(ApSConfigAHS.K_Sep2)
              Row1.Item(ApSConfigAHS.FD_SiteCode) = strDataArray(1)   ' "SiteCode"
              Row1.Item(ApSConfigAHS.FD_SiteName) = strDataArray(2)   ' "SiteName")
              Row1.Item(ApSConfigAHS.FD_NETWORK) = strDataArray(3)    '"Network")
              Row1.Item(ApSConfigAHS.FD_VARIABLENAME) = strDataArray(4)  '"VariableName"
              Row1.Item(ApSConfigAHS.FD_VARIABLECODE) = strDataArray(5)  '"VariableCode")
              If strDataArray(6).Equals("&nbsp;") Then
                Row1.Item(ApSConfigAHS.FD_ValueCount) = "0"              '"ValueCount"
              Else
                Row1.Item(ApSConfigAHS.FD_ValueCount) = strDataArray(6)  '"ValueCount"
              End If
              Row1.Item(ApSConfigAHS.FD_BEGINDATE) = strDataArray(7)     '"BeginDate"
              Row1.Item(ApSConfigAHS.FD_ENDDATE) = strDataArray(8)       '"EndDate"
              dTable.Rows.Add(Row1)
              numRecs += 1
            Catch ex As Exception

            End Try
          End If
        Next
      End If
    Catch ex As Exception
      Throw New Exception(ex.Message)
      dTable = Nothing
      Return dTable
    End Try
    If numRecs = 0 Then Throw New Exception("No items are selected")
    Return dTable

  End Function

  Private Function WriteURL2HTML(ByVal sURL As String) As String
    '*****************************************************************
    'Copyright © 2006 ESRI. All Rights Reserved.
    '*****************************************************************
    'Description: write efid to the page
    'History: z.ye @1/27/2006 1:31:39 PM
    '*****************************************************************
    Dim ds As Long = Date.Now.Ticks
    Dim sb As New System.Text.StringBuilder
    sb.Append((ControlChars.Lf & "<script language=""javascript"">" & ControlChars.Lf))
    sb.Append("var sURL='" & sURL & "';" & ControlChars.Lf)
    sb.Append(("</script>" & ControlChars.Lf))
    Return sb.ToString
  End Function

  '/ <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

  Protected Sub dwnData_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles dwnData.Click
    Dim err_msgArr() As String = Nothing
    Dim sName As String = "d" & getDateTimeAsString(Date.Now, True)
    Dim sFileName As String = sName & "MyDB.mdb"
    Dim sZipFileName As String
    Dim sUser As String
    sZipFileName = System.IO.Path.ChangeExtension(sFileName, "zip")
    Dim s As String
    s = export2DB(sFileName)
    If Not s Is Nothing Then
      sUser = Context.User.Identity.Name
      If (sUser <> "") Then
        Dim ss As String
        ss = "http://" & Server.MachineName & "/" & ApSConfigAHS.AppName & "/" & s
        Dim sMsg As String = sUser & ":" & vbCrLf & vbCrLf & "The requested data are ready for retrieval at: " & vbCrLf & ss & vbCrLf & vbCrLf & "Hydrologic Information System [HISWEB]."
        Dim sSubject As String = "The spatial/time series data are ready for retrieval. " & Date.Now
        ApSConfigAHS.SendEmail(sUser, sMsg, sSubject)
      End If
      If s.StartsWith("dboutput") Then
        Page.Response.Redirect(s)
        'Page.Response.WriteFile(Server.MapPath("dboutput\" & sZipFileName))
        'Page.Response.WriteFile(Server.MapPath("dboutput\" & Session.SessionID & "MyDB.zip"))
        Label1.Text = ""
      Else
        Session(K_CartMsg) = s
        'err_msgArr = s.Split("::")
        'Label1.Text = err_msgArr(2)

      End If
    End If
  End Sub
  ''' <summary>
  '''  Export FeatureClasses (Selected features)
  '''  Export TSTypeINFO
  '''  GetTimeSeries, Export TS.
  ''' </summary>
  ''' <param name="sFileName"></param>
  ''' <returns></returns>
  ''' <remarks></remarks>
  Private Function export2DB(ByVal sFileName As String) As String
    Dim checkbox As CheckBox = Nothing
    Dim strData As String = Nothing
    Dim i As Integer
    Dim numOfSelRec As Integer = 0
    Dim sName As String = ""
    Dim outPath As String = Server.MapPath("dboutput\")
    Dim FullFileName As String = outPath & sFileName
    Dim oCartItem As CartItem
    Dim cCartItems As CartItems = New CartItems
    Dim cNetworks As HISNetworks = New HISNetworks
    Dim oNetwork As HISNetwork
    Dim htSiteCode2HydroID As Hashtable
    Dim htSiteCodes As Hashtable
    Dim bOk As Boolean
    Try
      System.IO.File.Copy(Server.MapPath(ApSConfigAHS.DBForDownLoad), FullFileName, True)  '"App_Data\HISDownloadSchema.mdb"
      For i = 0 To GridView1.Rows.Count - 1
        Try
          checkbox = GridView1.Rows(i).FindControl("CheckBox1")
          If (Not checkbox Is Nothing) AndAlso (checkbox.Checked = True) Then
            oCartItem = New CartItem
            With oCartItem
              .Selected = True
              .ID = (GridView1.Rows(i).Cells(1).Text).Trim
              .SiteCode = (GridView1.Rows(i).Cells(2).Text).Trim
              .SiteName = (GridView1.Rows(i).Cells(3).Text).Trim
              .Network = (GridView1.Rows(i).Cells(4).Text).Trim
              .VariableName = (GridView1.Rows(i).Cells(5).Text).Trim
              .VariableCode = (GridView1.Rows(i).Cells(6).Text).Trim
              .ValueCount = (GridView1.Rows(i).Cells(7).Text).Trim
              .BeginDate = ApSConfigAHS.ToRegularDate((GridView1.Rows(i).Cells(8).Text).Trim)
              .EndDate = ApSConfigAHS.ToRegularDate((GridView1.Rows(i).Cells(9).Text).Trim)
            End With
            ApSConfigAHS.HashtableAddValue(cCartItems, oCartItem.ID, oCartItem)
            If (Not cNetworks.ContainsKey(oCartItem.Network)) Then
              oNetwork = ApSConfigAHS.HisNetworks.GetNetworkByName(oCartItem.Network)
              If Not oNetwork Is Nothing Then
                cNetworks.Add(oNetwork.Name, oNetwork)
              End If
            End If
          End If
        Catch ex As Exception

        End Try
      Next
      '..htSiteCodes '..Keyed on oNetwork.name, value = htSiteCodes2HydroID.
      htSiteCodes = ExportFeatureClasses(cNetworks, cCartItems, FullFileName)   'outPath & sFileName)
      '..WriteTSTypeInfo
      Dim htTSTypeInfos As Hashtable '..Keyed on VariableID, Value on TSTypeID.
      htTSTypeInfos = ExportTSTypeInfo(cCartItems, FullFileName, ApSConfigAHS.TB_TSTypeInfo)  'outPath & sFileName
      Dim FeatureID As Integer = 1
      Dim TSTypeID As Integer = 1
      For Each oCartItem In cCartItems.Values
        If (oCartItem.Selected = True) Then
          Try
            htSiteCode2HydroID = ApSConfigAHS.HashtableGetValue(htSiteCodes, oCartItem.Network)
          Catch ex As Exception
            htSiteCode2HydroID = Nothing
          End Try
          Try
            FeatureID = ApSConfigAHS.HashtableGetInteger(htSiteCode2HydroID, oCartItem.SiteCode)
          Catch ex As Exception
            FeatureID = 1
          End Try
          Try
            TSTypeID = ApSConfigAHS.HashtableGetInteger(htTSTypeInfos, oCartItem.VariableCode)
          Catch ex As Exception
            TSTypeID = 1
          End Try
          bOk = dump2DatabaseBulk(oCartItem, FullFileName, FeatureID, TSTypeID)
          numOfSelRec = numOfSelRec + 1
          If bOk = True Then
            dump2PrimaryTables(oCartItem, FullFileName)    'strData
          End If
        End If
      Next

      If numOfSelRec > 0 Then
        outPath = IIf(outPath.EndsWith("\"), outPath, outPath & "\")
        sName = ApSConfigAHS.AddToZip(outPath, sFileName)
        Try
          System.IO.File.Delete(outPath & sFileName)
        Catch ex As Exception
          If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
            ApSConfigAHS.Write2Log("Export2DB.system.IO.File.Delete " & outPath & sFileName & ": " & ex.Message & ", " & ex.StackTrace, True, -1, False)
          End If
        End Try
        'outPath = "http://" & Server.MachineName & "/" & ApSConfigAHS.AppName & "/dboutput/" & sName 'Session.SessionID & "MyDB.zip"
        outPath = "dboutput/" & sName 'Session.SessionID & "MyDB.zip"
      Else
        outPath = "No items are selected."
      End If

    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("Export2DB:" & ex.Message & ", " & ex.StackTrace, True, -1, False)
      End If
      outPath = "Error::" & ex.Message
    Finally

    End Try

    Return outPath
  End Function
  ''' <summary>
  '''  Write TypeInfo into a target table. returns htVariableID2TSTypeID
  ''' </summary>
  ''' <param name="cCartItems"></param>
  ''' <param name="sTargetPath"></param>
  ''' <param name="TsTypeInfoTable"></param>
  ''' <returns></returns>
  ''' <remarks></remarks>
  Private Function ExportTSTypeInfo(ByVal cCartItems As CartItems, ByVal sTargetPath As String, ByVal TsTypeInfoTable As String) As Hashtable
    Dim myConn As System.Data.OleDb.OleDbConnection = Nothing
    Dim myCmd As System.Data.OleDb.OleDbCommand = Nothing
    Dim htVariableID2TSTYPEID As Hashtable = New Hashtable
    Dim nID As Integer = 0
    Dim sCountBase As String
    Dim sGetMaxValue As String
    Dim sInsertBase As String
    Dim sInsert As String
    Dim sWhereBase As String
    Dim oItem As CartItem
    Dim sWhere As String
    Dim sCount As String
    Dim sGetValue As String
    Dim n As Integer
    Dim ds As Long = Date.Now.Ticks
    Try
      myConn = New System.Data.OleDb.OleDbConnection
      myConn.ConnectionString = ApSConfigAHS.MyDBConBase & sTargetPath  '"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
      myCmd = New System.Data.OleDb.OleDbCommand
      myCmd.Connection = myConn
      myConn.Open()
      myCmd.CommandType = CommandType.Text

      sCountBase = "SELECT COUNT(*) FROM " & TsTypeInfoTable
      sGetMaxValue = "SELECT MAX(" & ApSConfigAHS.FD_TSTYPEID & ") FROM " & TsTypeInfoTable
      sWhereBase = " WHERE " & ApSConfigAHS.FD_TSVARIABLEID & " IN ('"
      sInsertBase = "INSERT INTO " & ApSConfigAHS.TB_TSTypeInfo & " (" & ApSConfigAHS.FD_TSTYPEID & "," & ApSConfigAHS.FD_TSVARIABLEID & ") VALUES ("
      For Each oItem In cCartItems.Values
        Try
          sWhere = sWhereBase & oItem.VariableName & "')"
          sCount = sCountBase & sWhere
          Try
            myCmd.CommandText = sCount
            nID = myCmd.ExecuteScalar
          Catch ex As Exception
            nID = -1
          End Try
          If nID <= 0 Then
            sGetValue = sGetMaxValue
            myCmd.CommandText = sGetValue
            Try
              nID = myCmd.ExecuteScalar
            Catch ex As Exception
              nID = 0
            End Try
            nID = nID + 1
            sInsert = sInsertBase & nID & ",'" & oItem.VariableName & "')"
            myCmd.CommandText = sInsert
            n = myCmd.ExecuteNonQuery()
            ApSConfigAHS.HashtableAddValue(htVariableID2TSTYPEID, oItem.VariableCode, nID)
          Else
            If (htVariableID2TSTYPEID.ContainsKey(oItem.VariableCode) = False) Then
              sGetValue = "SELECT " & ApSConfigAHS.FD_TSTYPEID & " FROM " & ApSConfigAHS.TB_TSTypeInfo & sWhere
              myCmd.CommandText = sGetValue
              nID = myCmd.ExecuteScalar
              ApSConfigAHS.HashtableAddValue(htVariableID2TSTYPEID, oItem.VariableCode, nID)
            End If
          End If
        Catch ex As Exception
          nID = 1
        End Try
      Next
    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("ExportTSTypeInfo:" & 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("ExportTSTypeInfo:", True, ds, False)
      End If

    End Try
    Return htVariableID2TSTYPEID

  End Function
  ''' <summary>
  '''  download data specified by the cCartItems.
  ''' </summary>
  ''' <param name="cNetworks">List of Network involved</param>
  ''' <param name="cCartItems">list of data items</param>
  ''' <param name="TargetMDB">FullPath Name of the TargetMDB </param>
  ''' <returns>htSiteCodes (keyed on layername, value=htSiteCode2HydroID</returns>
  ''' <remarks></remarks>
  Private Function ExportFeatureClasses(ByVal cNetworks As HISNetworks, ByVal cCartItems As CartItems, ByVal TargetMDB As String) As Hashtable
    Dim pFC As IFeatureClass
    Dim oNetwork As HISNetwork
    Dim pWK As IWorkspace
    Dim pWF As ESRI.ArcGIS.DataSourcesGDB.AccessWorkspaceFactory  'IWorkspaceFactory
    Dim sName As String
    Dim pDataset As IDataset
    Dim sDatasetName As String
    Dim pFCSource As IFeatureClass

    Dim pSC As IServerContext = Nothing
    Dim pGISConn As IGISServerConnection
    Dim pSOM As IServerObjectManager
    Dim pFCursor As IFeatureCursor
    Dim nHydroID As Integer = 1
    Dim pFields As IFields
    Dim pFieldsEdit As IFieldsEdit
    Dim pClone As IClone
    Dim iFldSiteCode As Integer
    Dim arItems As ArrayList
    Dim oItem As CartItem
    Dim pQF As ESRI.ArcGIS.Geodatabase.QueryFilter = New ESRI.ArcGIS.Geodatabase.QueryFilter
    Dim sWhere As String
    Dim pField As IField
    Dim sQT As String = ""
    Dim htSiteCodes As Hashtable = New Hashtable
    Dim htSiteCode2HydroID As Hashtable
    Dim pWorkspaceEdit As IWorkspaceEdit = Nothing
    Dim pConn As HISWEB2AO.IWEB2AOConnector = Nothing
    Dim htParams As Hashtable
    Dim htReturn As Hashtable
    Dim s As String
    Try
      pGISConn = New GISServerConnectionClass()
      pGISConn.Connect(ApSConfigAHS.HostName)
      pSOM = pGISConn.ServerObjectManager
      pSC = pSOM.CreateServerContext("", "")
      pWF = pSC.CreateObject("esriDataSourcesGDB.AccessWorkspaceFactory")
      pWK = pWF.OpenFromFile(TargetMDB, 0)
      For Each oNetwork In cNetworks.Values
        htParams = New Hashtable
        sName = oNetwork.LayerName
        htSiteCode2HydroID = New Hashtable
        pFCSource = ApSConfigAHS.GetFeatureClassOnServer(ApSConfigAHS.HostName, ApSConfigAHS.MapServiceName, oNetwork.LayerName)
        iFldSiteCode = pFCSource.Fields.FindField(oNetwork.SiteCodeField)
        If iFldSiteCode >= 0 Then
          pField = pFCSource.Fields.Field(iFldSiteCode)
          If ((pField.Type = ESRI.ArcGIS.Geodatabase.esriFieldType.esriFieldTypeInteger) OrElse (pField.Type = ESRI.ArcGIS.Geodatabase.esriFieldType.esriFieldTypeOID) _
            OrElse (pField.Type = ESRI.ArcGIS.Geodatabase.esriFieldType.esriFieldTypeDouble) OrElse (pField.Type = ESRI.ArcGIS.Geodatabase.esriFieldType.esriFieldTypeSmallInteger) _
            OrElse (pField.Type = ESRI.ArcGIS.Geodatabase.esriFieldType.esriFieldTypeSingle)) Then
            sQT = ""
          Else
            sQT = "'"
          End If
        End If
        pFC = ApSConfigAHS.Try2OpenFeatureClass(pWK, sName)
        If pFC Is Nothing Then
          pDataset = pFCSource.FeatureDataset
          If Not pDataset Is Nothing Then
            sDatasetName = pDataset.Name
          Else
            sDatasetName = ""
          End If
          pFields = pFCSource.Fields
          pClone = pFields
          pFields = pClone.Clone
          pFieldsEdit = pFields
          pFieldsEdit.AddField(ApSConfigAHS.CreateField(ApSConfigAHS.FD_HYDROID, ESRI.ArcGIS.Geodatabase.esriFieldType.esriFieldTypeInteger, ApSConfigAHS.FD_HYDROID))
          pFC = ApSConfigAHS.CopyFeatureClass(pFCSource, sDatasetName, pWK, pFields)
        End If
        If Not pFC Is Nothing Then
          'pWorkspaceEdit = pWK
          'pWorkspaceEdit.StartEditing(False)
          'pWorkspaceEdit.StartEditOperation()
          '..Get all the selected features under the current network.
          arItems = cCartItems.GetItemsByNetwork(oNetwork.Name)
          sWhere = ""
          Dim o As Object
          For Each o In arItems
            oItem = CType(o, CartItem)
            If (sWhere = "") Then
              sWhere = sQT & oItem.SiteCode & sQT
            Else
              s = "," & sQT & oItem.SiteCode & sQT
              If (Not sWhere.Contains(s)) Then
                sWhere = sWhere & s   '"," & sQT & oItem.SiteCode & sQT
              End If
            End If
          Next
          sWhere = oNetwork.SiteCodeField & " IN (" & sWhere & ")"
          pQF.WhereClause = sWhere
          pFCursor = pFCSource.Search(pQF, False)
          ApSConfigAHS.HashtableAddValue(htParams, "TARGETWORKSPACE", TargetMDB)
          ApSConfigAHS.HashtableAddValue(htParams, "LAYERNAME", pFC.AliasName, True)
          ApSConfigAHS.HashtableAddValue(htParams, "NEXTHYDROID", nHydroID, True)
          ApSConfigAHS.HashtableAddValue(htParams, "SITECODE", oNetwork.SiteCodeField, True)
          pConn = pSC.CreateObject("HISWEB2AO.WEB2AOConn")
          htReturn = pConn.CopyFeatures(pFCursor, htParams)
          s = ApSConfigAHS.HashtableGetString(htReturn, "MSG", "")
          If s <> "" Then
            If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
              ApSConfigAHS.Write2Log("HISWEB2AO.WEB2AOConn.CopyFeatures: " & s, True, -1, False)
            End If
          End If
          Try
            nHydroID = ApSConfigAHS.HashtableGetInteger(htReturn, "NEXTHYDROID")
          Catch ex As Exception
            nHydroID = 0
          End Try
          Try
            htSiteCode2HydroID = ApSConfigAHS.HashtableGetValue(htReturn, "HTSITECODE2HYDROID")
          Catch ex As Exception

          End Try
          'iFldHydroID = ApSConfigAHS.HashtableGetInteger(htReturn, "NEXTHYDROID", 0)
          'pFeature = pFCursor.NextFeature
          'iFldHydroID = pFC.Fields.FindField(ApSConfigAHS.FD_HYDROID)
          'Do Until pFeature Is Nothing
          '  sSiteCode = pFeature.Value(iFldSiteCode)
          '  pFeatureA = pFC.CreateFeature
          '  bOk = ApSConfigAHS.CopyFeature(pFeature, pFeatureA)
          '  If (bOk = True) And (iFldHydroID >= 0) Then
          '    pFeatureA.Value(iFldHydroID) = nHydroID
          '    ApSConfigAHS.HashtableAddValue(htSiteCode2HydroID, sSiteCode, nHydroID)
          '    nHydroID = nHydroID + 1
          '  End If
          '  'pGeom = pFeature.Shape
          '  'pPoint = New ESRI.ArcGIS.Geometry.Point
          '  'pPoint.X = 0
          '  'pPoint.Y = 0
          '  'pFeatureA.Shape = pPoint
          '  pFeatureA.Store()
          '  pFeature = pFCursor.NextFeature
          'Loop
          'pConn = pSC.CreateObject("HISWEB2AO.WEB2AOConn")
          'sWhere = pConn.DoTest(TargetMDB)  '"E:\Inetpub\wwwroot\HISWEB\dboutput\TestMyDB.mdb")
          '..htSiteCodes '..Keyed on oNetwork.name, value = htSiteCodes2HydroID.
          ApSConfigAHS.HashtableAddValue(htSiteCodes, oNetwork.Name, htSiteCode2HydroID)
        End If
      Next
    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("ExportFeatureClasses:" & ex.Message & ", " & ex.StackTrace, True, -1, False)
      End If

    Finally
      'If Not pWorkspaceEdit Is Nothing Then
      '  'pWorkspaceEdit.StopEditing(True)
      '  'pWorkspaceEdit.StopEditOperation()
      '  'pWorkspaceEdit.StopEditing(True)
      'End If
      If Not pConn Is Nothing Then
        pConn = Nothing
      End If
      If Not (pSC Is Nothing) Then
        pSC.ReleaseContext()
        pSC = Nothing
      End If
    End Try

    Return htSiteCodes
  End Function
  ''' <summary>
  '''  dumps the time series information (date, value) into database in steps mentioned below:
  '''  1. Get XML time series document from WS
  '''  2. Create Time Series Object from XML document.
  '''  3. Batch Update of time series information.  ''' 
  ''' </summary>
  ''' <param name="oCartItem"></param>
  ''' <param name="outPath"></param>
  ''' <param name="FeatureID"></param>
  ''' <param name="TSTypeID"></param>
  ''' <returns></returns>
  ''' <remarks></remarks>
  Private Function dump2DatabaseBulk(ByVal oCartItem As CartItem, ByVal outPath As String, ByVal FeatureID As Integer, ByVal TSTypeID As Integer) As Boolean
    Dim isBulkUploadOk As Boolean = False
    Dim tsResponse As String
    Dim tsInfo As TimeSeries
    Dim sFile As String
    Try
      ' get time series information from WS
      tsResponse = GetTimeSeriesInfo(oCartItem)
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.ShowMsg1) = ApSConfigAHS.DebugType.ShowMsg1) Then
        sFile = Server.MapPath("tmp\" & "tsResp.xml")
        System.IO.File.WriteAllText(sFile, tsResponse)
      End If

      ' get the time series object from XML response
      tsInfo = toTimeSeriesInfo(tsResponse, FeatureID, TSTypeID)

      Dim valInfoArr As ArrayList = tsInfo.valueInfo()
      Dim j As Integer
      Dim valInfo As ValueInfo
      Dim strHeader As String = "<root>"
      Dim strFooter As String = "</root>"
      Dim strData As String = ""
      Dim sbData As StringBuilder = New StringBuilder
      'Dim dtArray() As String = Nothing
      sbData.Append(strHeader)
      For j = 0 To valInfoArr.Count - 1
        valInfo = valInfoArr.Item(j)
        'dtArray = valInfo.dateTime.Split("T")
        strData = "<values><DateTimeValue>" & valInfo.dateTime & "</DateTimeValue><ValueInfo>" & valInfo.value & "</ValueInfo><SiteCode>" & tsInfo.siteCode & "</SiteCode><VariableCode>" & tsInfo.variableCode & "</VariableCode><FeatureID>" & valInfo.FeatureID & "</FeatureID><TSTypeID>" & valInfo.TSTypeID & "</TSTypeID></values>"
        ' If j >= 70 Then Exit For
        sbData.Append(strData)
        sbData.AppendLine()
        'strData = ""
        'dtArray = Nothing
      Next

      sbData.Append(strFooter)

      Dim document As String = "tsDataSet2.xml"
      Dim myLoadSchema As String = "tsDataSet2.xsd"
      Dim myXmlDataDocument As XmlDataDocument

      Dim myStreamReader As StreamReader = Nothing
      myXmlDataDocument = New XmlDataDocument()
      myStreamReader = New StreamReader(Server.MapPath(myLoadSchema))
      myXmlDataDocument.DataSet.ReadXmlSchema(myStreamReader)
      myXmlDataDocument.LoadXml(sbData.ToString)

      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.ShowMsg1) = ApSConfigAHS.DebugType.ShowMsg1) Then
        sFile = Server.MapPath("tmp\" & "tsDataSet.xml")
        System.IO.File.WriteAllText(sFile, sbData.ToString)
      End If

      '  Console.WriteLine("Reading Schema file ...")
      'myXmlDataDocument.DataSet.ReadXmlSchema(myStreamReader)
      'myXmlDataDocument.Load(Server.MapPath(document))

      Dim tbl As DataTable = myXmlDataDocument.DataSet.Tables("values")
      Try
        BatchUpdate(tbl, 100, outPath) 'TODO: Implement commit/rollback
      Catch ex As Exception
        Throw ex
      Finally
        myXmlDataDocument = Nothing
        myStreamReader.Close()
        myStreamReader = Nothing
      End Try
      isBulkUploadOk = True
    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log(":" & ex.Message & ", " & ex.StackTrace, True, -1, False)
      End If
      isBulkUploadOk = False
    End Try
    Return (isBulkUploadOk)
  End Function

  ''' <summary>
  '''  dumps the time series information (date, value) into database in steps mentioned below:
  '''  1. Get XML time series document from WS
  '''  2. Create Time Series Object from XML document.
  '''  3. Batch Update of time series information.
  ''' </summary>
  ''' <param name="strData2"></param>
  ''' <param name="outPath"></param>
  ''' <returns>true/if batch load/insert is successful</returns>
  ''' <remarks></remarks>
  Private Function dump2DatabaseBulk(ByVal strData2 As String, ByVal outPath As String) As Boolean
    Dim isBulkUploadOk As Boolean = False
    Dim tsResponse As String
    Dim tsInfo As TimeSeries
    Try
      ' get time series information from WS
      tsResponse = GetTimeSeriesInfoDEV(strData2)
      ' get the time series object from XML response
      tsInfo = toTimeSeriesInfo(tsResponse, 1, 2)

      Dim valInfoArr As ArrayList = tsInfo.valueInfo()
      Dim j As Integer
      Dim valInfo As ValueInfo
      Dim strHeader As String = "<root>"
      Dim strFooter As String = "</root>"
      Dim strData As String = ""
      Dim sbData As StringBuilder = New StringBuilder
      'Dim dtArray() As String = Nothing
      sbData.Append(strHeader)
      For j = 0 To valInfoArr.Count - 1
        valInfo = valInfoArr.Item(j)
        'dtArray = valInfo.dateTime.Split("T")
        strData = "<values><DateTimeValue>" & valInfo.dateTime & "</DateTimeValue><ValueInfo>" & valInfo.value & "</ValueInfo><SiteCode>" & tsInfo.siteCode & "</SiteCode><VariableCode>" & tsInfo.variableCode & "</VariableCode><FeatureID>" & valInfo.FeatureID & "</FeatureID><TSTypeID>" & valInfo.TSTypeID & "</TSTypeID></values>"
        ' If j >= 70 Then Exit For
        sbData.Append(strData)
        sbData.AppendLine()
        'strData = ""
        'dtArray = Nothing
      Next

      sbData.Append(strFooter)

      Dim document As String = "tsDataSet2.xml"
      Dim myLoadSchema As String = "tsDataSet2.xsd"
      Dim myXmlDataDocument As XmlDataDocument


      Dim myStreamReader As StreamReader = Nothing
      myXmlDataDocument = New XmlDataDocument()
      myStreamReader = New StreamReader(Server.MapPath(myLoadSchema))
      myXmlDataDocument.DataSet.ReadXmlSchema(myStreamReader)
      myXmlDataDocument.LoadXml(sbData.ToString)
      '  Console.WriteLine("Reading Schema file ...")
      'myXmlDataDocument.DataSet.ReadXmlSchema(myStreamReader)
      'myXmlDataDocument.Load(Server.MapPath(document))

      Dim tbl As DataTable = myXmlDataDocument.DataSet.Tables("values")
      Try
        BatchUpdate(tbl, 100, outPath) 'TODO: Implement commit/rollback
      Catch ex As Exception
        Throw ex
      Finally
        myXmlDataDocument = Nothing
        myStreamReader.Close()
        myStreamReader = Nothing
      End Try
      isBulkUploadOk = True
    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log(":" & ex.Message & ", " & ex.StackTrace, True, -1, False)
      End If
      isBulkUploadOk = False
    End Try
    Return (isBulkUploadOk)
  End Function
  ''' <summary>
  ''' Insert records into MySelect and Variables table.
  ''' </summary>
  ''' <param name="oCartItem"></param>
  ''' <param name="outPath">FullPath pointing to the MDB to be downloaded.</param>
  ''' <remarks></remarks>
  Private Sub dump2PrimaryTables(ByVal oCartItem As CartItem, ByVal outPath As String)
    Dim ds As Long = Date.Now.Ticks
    Dim myConn As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection
    myConn.ConnectionString = ApSConfigAHS.MyDBConBase & outPath   '"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
    ' Dim sql2 As String = "insert into Variables (variableCode, variableName, BeginDate, EndDate)   values (@variableCode,@variableName, @beginDate, @endDate)"
    Dim sql3 As String = "INSERT INTO MySelect(SiteCode,SiteName,Network,VariableName,VariableCode,ObservationCount,BeginDate,EndDate) VALUES (@MySelectSiteCode,@MySelectSiteName,@MySelectNetwork,@MySelectVariableName,@MySelectVariableCode,@MySelectValueCount,@MySelectBeginDate,@MySelectEndDate)"
    Dim sql2 As String = "insert into Variables (variableCode, variableName, BeginDate, EndDate)   values (@variableCode,@variableName,@beginDate, @endDate)"
    Dim myCmd As System.Data.OleDb.OleDbCommand = New System.Data.OleDb.OleDbCommand
    'Dim myCmd As SqlCommand = New SqlCommand
    myCmd.CommandText = "insert into Sites (SiteCode, SiteName, NetworkNam) values (@siteId, @siteName, @network) "
    myCmd.CommandType = CommandType.Text
    Dim sqlTrans As OleDb.OleDbTransaction = Nothing

    Dim siteIdParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    siteIdParam.ParameterName = "@siteId"
    siteIdParam.OleDbType = OleDb.OleDbType.VarChar
    siteIdParam.Size = 50
    siteIdParam.Direction = ParameterDirection.Input
    siteIdParam.Value = oCartItem.SiteCode    'strArry(1)

    Dim siteNameParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    siteNameParam.ParameterName = "@siteName"
    siteNameParam.OleDbType = OleDb.OleDbType.VarChar
    siteNameParam.Size = 50
    siteNameParam.Direction = ParameterDirection.Input
    siteNameParam.Value = oCartItem.SiteName  'strArry(2)

    Dim networkParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    networkParam.ParameterName = "@network"
    networkParam.OleDbType = OleDb.OleDbType.VarChar
    networkParam.Size = 50
    networkParam.Direction = ParameterDirection.Input
    networkParam.Value = oCartItem.Network   'strArry(3)

    Dim varCodeParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    varCodeParam.ParameterName = "@variableCode"
    varCodeParam.OleDbType = OleDb.OleDbType.VarChar
    varCodeParam.Size = 50
    varCodeParam.Direction = ParameterDirection.Input
    varCodeParam.Value = oCartItem.VariableCode  'strArry(5)

    Dim varNameParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    varNameParam.ParameterName = "@variableName"
    varNameParam.OleDbType = OleDb.OleDbType.VarChar
    varNameParam.Size = 50
    varNameParam.Direction = ParameterDirection.Input
    varNameParam.Value = oCartItem.VariableName  'strArry(4)

    Dim beginDtParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    beginDtParam.ParameterName = "@beginDate"
    beginDtParam.OleDbType = OleDb.OleDbType.DBTimeStamp
    beginDtParam.Size = 50
    beginDtParam.Direction = ParameterDirection.Input
    beginDtParam.Value = oCartItem.BeginDate  ' strArry(7)

    Dim endDtParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    endDtParam.ParameterName = "@endDate"
    endDtParam.OleDbType = OleDb.OleDbType.DBTimeStamp
    endDtParam.Size = 50
    endDtParam.Direction = ParameterDirection.Input
    endDtParam.Value = oCartItem.EndDate  'strArry(8)


    Dim MySelectSiteCodeParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    MySelectSiteCodeParam.ParameterName = "@MySelectSiteCode"
    MySelectSiteCodeParam.OleDbType = OleDb.OleDbType.VarChar
    MySelectSiteCodeParam.Size = oCartItem.SiteCode.Length   'strArry(1).Length
    MySelectSiteCodeParam.Direction = ParameterDirection.Input
    MySelectSiteCodeParam.Value = oCartItem.SiteCode   'strArry(1)

    Dim MySelectSiteNameParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    MySelectSiteNameParam.ParameterName = "@MySelectSiteName"
    MySelectSiteNameParam.OleDbType = OleDb.OleDbType.VarChar
    MySelectSiteNameParam.Size = oCartItem.SiteName.Length  ' strArry(2).Length
    MySelectSiteNameParam.Direction = ParameterDirection.Input
    MySelectSiteNameParam.Value = oCartItem.SiteName  ' strArry(2)

    Dim MySelectNetworkParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    MySelectNetworkParam.ParameterName = "@MySelectNetwork"
    MySelectNetworkParam.OleDbType = OleDb.OleDbType.VarChar
    MySelectNetworkParam.Size = 50
    MySelectNetworkParam.Direction = ParameterDirection.Input
    MySelectNetworkParam.Value = oCartItem.Network  'strArry(3)

    Dim MySelectVarNameParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    MySelectVarNameParam.ParameterName = "@MySelectVariableName"
    MySelectVarNameParam.OleDbType = OleDb.OleDbType.VarChar
    MySelectVarNameParam.Size = oCartItem.VariableName.Length ' strArry(4).Length
    MySelectVarNameParam.Direction = ParameterDirection.Input
    MySelectVarNameParam.Value = oCartItem.VariableName  'strArry(4)

    Dim MySelectVarCodeParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    MySelectVarCodeParam.ParameterName = "@MySelectVariableCode"
    MySelectVarCodeParam.OleDbType = OleDb.OleDbType.VarChar
    MySelectVarCodeParam.Size = oCartItem.VariableCode.Length    'strArry(5).Length
    MySelectVarCodeParam.Direction = ParameterDirection.Input
    MySelectVarCodeParam.Value = oCartItem.VariableCode   'strArry(5)


    Dim MySelectValueCountParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    MySelectValueCountParam.ParameterName = "@MySelectValueCount"
    MySelectValueCountParam.OleDbType = OleDb.OleDbType.Integer
    MySelectValueCountParam.Size = 10   ' strArry(6).Length
    MySelectValueCountParam.Direction = ParameterDirection.Input
    MySelectValueCountParam.Value = oCartItem.ValueCount ' strArry(6)

    Dim MySelectBeginDtParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    MySelectBeginDtParam.ParameterName = "@MySelectBeginDate"
    MySelectBeginDtParam.OleDbType = OleDb.OleDbType.VarChar
    MySelectBeginDtParam.Size = oCartItem.BeginDate.Length  ' strArry(7).Length
    MySelectBeginDtParam.Direction = ParameterDirection.Input
    MySelectBeginDtParam.Value = oCartItem.BeginDate  'strArry(7)

    Dim MySelectEndDtParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    MySelectEndDtParam.ParameterName = "@MySelectEndDate"
    MySelectEndDtParam.OleDbType = OleDb.OleDbType.VarChar
    MySelectEndDtParam.Size = oCartItem.EndDate.Length   'strArry(8).Length
    MySelectEndDtParam.Direction = ParameterDirection.Input
    MySelectEndDtParam.Value = oCartItem.EndDate   'strArry(8)

    myCmd.Parameters.Add(siteIdParam)
    myCmd.Parameters.Add(siteNameParam)
    myCmd.Parameters.Add(networkParam)
    myCmd.Connection = myConn

    Try
      myConn.Open()
      sqlTrans = myConn.BeginTransaction
      myCmd.Transaction = sqlTrans
      myCmd.ExecuteNonQuery()
      myCmd.Parameters.Clear()
      ' run query two

      myCmd.CommandText = sql2
      myCmd.CommandType = CommandType.Text

      myCmd.Parameters.Add(varCodeParam)
      myCmd.Parameters.Add(varNameParam)
      myCmd.Parameters.Add(beginDtParam)
      myCmd.Parameters.Add(endDtParam)
      myCmd.ExecuteNonQuery()

      ' run query three
      myCmd.Parameters.Clear()
      myCmd.CommandText = sql3
      myCmd.CommandType = CommandType.Text

      myCmd.Parameters.Add(MySelectSiteCodeParam)
      myCmd.Parameters.Add(MySelectSiteNameParam)
      myCmd.Parameters.Add(MySelectNetworkParam)
      myCmd.Parameters.Add(MySelectVarNameParam)
      myCmd.Parameters.Add(MySelectVarCodeParam)
      myCmd.Parameters.Add(MySelectValueCountParam)
      myCmd.Parameters.Add(MySelectBeginDtParam)
      myCmd.Parameters.Add(MySelectEndDtParam)
      myCmd.ExecuteNonQuery()

      sqlTrans.Commit()
    Catch ex As Exception
      sqlTrans.Rollback()
      myConn.Close()
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("dump2PrimaryTables:" & ex.Message & ", " & ex.StackTrace, True, -1, False)
      End If
      Throw ex
    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("dump2PrimaryTables:", True, ds, False)
      End If
    End Try

  End Sub

  Private Sub dump2PrimaryTables(ByVal strData As String, ByVal outPath As String)
    Dim ds As Long = Date.Now.Ticks
    Dim strArry() As String = strData.Split(ApSConfigAHS.K_Sep2)
    Dim myConn As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection
    myConn.ConnectionString = ApSConfigAHS.MyDBConBase & outPath   '"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
    ' Dim sql2 As String = "insert into Variables (variableCode, variableName, BeginDate, EndDate)   values (@variableCode,@variableName, @beginDate, @endDate)"
    Dim sql3 As String = "INSERT INTO MySelect(SiteCode,SiteName,Network,VariableName,VariableCode,ObservationCount,BeginDate,EndDate) VALUES (@MySelectSiteCode,@MySelectSiteName,@MySelectNetwork,@MySelectVariableName,@MySelectVariableCode,@MySelectValueCount,@MySelectBeginDate,@MySelectEndDate)"
    Dim sql2 As String = "insert into Variables (variableCode, variableName, BeginDate, EndDate)   values (@variableCode,@variableName,@beginDate, @endDate)"
    Dim myCmd As System.Data.OleDb.OleDbCommand = New System.Data.OleDb.OleDbCommand
    'Dim myCmd As SqlCommand = New SqlCommand
    myCmd.CommandText = "insert into Sites (SiteCode, SiteName, NetworkNam) values (@siteId, @siteName, @network) "
    myCmd.CommandType = CommandType.Text
    Dim sqlTrans As OleDb.OleDbTransaction = Nothing

    Dim siteIdParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    siteIdParam.ParameterName = "@siteId"
    siteIdParam.OleDbType = OleDb.OleDbType.VarChar
    siteIdParam.Size = 50
    siteIdParam.Direction = ParameterDirection.Input
    siteIdParam.Value = strArry(1)

    Dim siteNameParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    siteNameParam.ParameterName = "@siteName"
    siteNameParam.OleDbType = OleDb.OleDbType.VarChar
    siteNameParam.Size = 50
    siteNameParam.Direction = ParameterDirection.Input
    siteNameParam.Value = strArry(2)

    Dim networkParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    networkParam.ParameterName = "@network"
    networkParam.OleDbType = OleDb.OleDbType.VarChar
    networkParam.Size = 50
    networkParam.Direction = ParameterDirection.Input
    networkParam.Value = strArry(3)

    Dim varCodeParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    varCodeParam.ParameterName = "@variableCode"
    varCodeParam.OleDbType = OleDb.OleDbType.VarChar
    varCodeParam.Size = 50
    varCodeParam.Direction = ParameterDirection.Input
    varCodeParam.Value = strArry(5)

    Dim varNameParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    varNameParam.ParameterName = "@variableName"
    varNameParam.OleDbType = OleDb.OleDbType.VarChar
    varNameParam.Size = 50
    varNameParam.Direction = ParameterDirection.Input
    varNameParam.Value = strArry(4)

    Dim beginDtParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    beginDtParam.ParameterName = "@beginDate"
    beginDtParam.OleDbType = OleDb.OleDbType.DBTimeStamp
    beginDtParam.Size = 50
    beginDtParam.Direction = ParameterDirection.Input
    beginDtParam.Value = strArry(7)

    Dim endDtParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    endDtParam.ParameterName = "@endDate"
    endDtParam.OleDbType = OleDb.OleDbType.DBTimeStamp
    endDtParam.Size = 50
    endDtParam.Direction = ParameterDirection.Input
    endDtParam.Value = strArry(8)


    Dim MySelectSiteCodeParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    MySelectSiteCodeParam.ParameterName = "@MySelectSiteCode"
    MySelectSiteCodeParam.OleDbType = OleDb.OleDbType.VarChar
    MySelectSiteCodeParam.Size = strArry(1).Length
    MySelectSiteCodeParam.Direction = ParameterDirection.Input
    MySelectSiteCodeParam.Value = strArry(1)

    Dim MySelectSiteNameParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    MySelectSiteNameParam.ParameterName = "@MySelectSiteName"
    MySelectSiteNameParam.OleDbType = OleDb.OleDbType.VarChar
    MySelectSiteNameParam.Size = strArry(2).Length
    MySelectSiteNameParam.Direction = ParameterDirection.Input
    MySelectSiteNameParam.Value = strArry(2)

    Dim MySelectNetworkParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    MySelectNetworkParam.ParameterName = "@MySelectNetwork"
    MySelectNetworkParam.OleDbType = OleDb.OleDbType.VarChar
    MySelectNetworkParam.Size = 50
    MySelectNetworkParam.Direction = ParameterDirection.Input
    MySelectNetworkParam.Value = strArry(3)

    Dim MySelectVarNameParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    MySelectVarNameParam.ParameterName = "@MySelectVariableName"
    MySelectVarNameParam.OleDbType = OleDb.OleDbType.VarChar
    MySelectVarNameParam.Size = strArry(4).Length
    MySelectVarNameParam.Direction = ParameterDirection.Input
    MySelectVarNameParam.Value = strArry(4)

    Dim MySelectVarCodeParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    MySelectVarCodeParam.ParameterName = "@MySelectVariableCode"
    MySelectVarCodeParam.OleDbType = OleDb.OleDbType.VarChar
    MySelectVarCodeParam.Size = strArry(5).Length
    MySelectVarCodeParam.Direction = ParameterDirection.Input
    MySelectVarCodeParam.Value = strArry(5)


    Dim MySelectValueCountParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    MySelectValueCountParam.ParameterName = "@MySelectValueCount"
    MySelectValueCountParam.OleDbType = OleDb.OleDbType.Integer
    MySelectValueCountParam.Size = strArry(6).Length
    MySelectValueCountParam.Direction = ParameterDirection.Input
    MySelectValueCountParam.Value = strArry(6)

    Dim MySelectBeginDtParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    MySelectBeginDtParam.ParameterName = "@MySelectBeginDate"
    MySelectBeginDtParam.OleDbType = OleDb.OleDbType.VarChar
    MySelectBeginDtParam.Size = strArry(7).Length
    MySelectBeginDtParam.Direction = ParameterDirection.Input
    MySelectBeginDtParam.Value = strArry(7)

    Dim MySelectEndDtParam As OleDb.OleDbParameter = New OleDb.OleDbParameter
    MySelectEndDtParam.ParameterName = "@MySelectEndDate"
    MySelectEndDtParam.OleDbType = OleDb.OleDbType.VarChar
    MySelectEndDtParam.Size = strArry(8).Length
    MySelectEndDtParam.Direction = ParameterDirection.Input
    MySelectEndDtParam.Value = strArry(8)

    myCmd.Parameters.Add(siteIdParam)
    myCmd.Parameters.Add(siteNameParam)
    myCmd.Parameters.Add(networkParam)
    myCmd.Connection = myConn

    Try
      myConn.Open()
      sqlTrans = myConn.BeginTransaction
      myCmd.Transaction = sqlTrans
      myCmd.ExecuteNonQuery()
      myCmd.Parameters.Clear()
      ' run query two

      myCmd.CommandText = sql2
      myCmd.CommandType = CommandType.Text

      myCmd.Parameters.Add(varCodeParam)
      myCmd.Parameters.Add(varNameParam)
      myCmd.Parameters.Add(beginDtParam)
      myCmd.Parameters.Add(endDtParam)
      myCmd.ExecuteNonQuery()

      ' run query three
      myCmd.Parameters.Clear()
      myCmd.CommandText = sql3
      myCmd.CommandType = CommandType.Text

      myCmd.Parameters.Add(MySelectSiteCodeParam)
      myCmd.Parameters.Add(MySelectSiteNameParam)
      myCmd.Parameters.Add(MySelectNetworkParam)
      myCmd.Parameters.Add(MySelectVarNameParam)
      myCmd.Parameters.Add(MySelectVarCodeParam)
      myCmd.Parameters.Add(MySelectValueCountParam)
      myCmd.Parameters.Add(MySelectBeginDtParam)
      myCmd.Parameters.Add(MySelectEndDtParam)
      myCmd.ExecuteNonQuery()

      sqlTrans.Commit()
    Catch ex As Exception
      sqlTrans.Rollback()
      myConn.Close()
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("dump2PrimaryTables:" & ex.Message & ", " & ex.StackTrace, True, -1, False)
      End If
      Throw ex
    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("dump2PrimaryTables:", True, ds, False)
      End If
    End Try

  End Sub
  ''' <summary>
  '''   Queries WS's for XML TimeSeries information
  ''' </summary>
  ''' <param name="tsInputStr"></param>
  ''' <returns>XML TimeSeries Document</returns>
  ''' <remarks></remarks>
  Private Function GetTimeSeriesInfo(ByVal oCartItem As CartItem) As String
    Dim ds As Long = Date.Now.Ticks
    Dim timeSeriesStr As String = Nothing
    Dim stationId As String = Nothing
    Dim varCode As String = Nothing
    Dim startDt As String = Nothing
    Dim endDt As String = Nothing
    Dim _startDate As String = Nothing
    Dim _endDate As String = Nothing
    Dim network As String = Nothing
    Dim timeSeriesData As String = Nothing
    Dim oNetwork As HISNetwork
    Dim ss() As String
    'Dim wsProxyIID As New edu.sdsc.water.NWISInstantaneousIrregularData
    'Dim tsProxy As New edu.sdsc.water.NWISDailyValues
    'Dim epaTimeSeriesProxy As New edu.sdsc.water.STORET
    Try
      oNetwork = Me.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
      network = oCartItem.Network
      stationId = oCartItem.Network & ":" & oCartItem.SiteCode  '"11126500" '
      varCode = oCartItem.Network & ":" & oCartItem.VariableCode  ' tsInputArray(3) & ":" & tsInputArray(5)
      startDt = oCartItem.BeginDate    '   tsInputArray(7)
      endDt = oCartItem.EndDate        '  tsInputArray(8)
      ss = startDt.Split(" ")
      ss = ss(0).Split("/")
      startDt = ss(2) & "-" & IIf(ss(0).Length < 2, "0" & ss(0), ss(0)) & "-" & IIf(ss(1).Length < 2, "0" & ss(1), ss(1))
      ss = endDt.Split(" ")
      ss = ss(0).Split("/")
      endDt = ss(2) & "-" & IIf(ss(0).Length < 2, "0" & ss(0), ss(0)) & "-" & IIf(ss(1).Length < 2, "0" & ss(1), ss(1))

      'startDt = startDt.Replace("/", "-")
      'endDt = endDt.Replace("/", "-")
      timeSeriesStr = ApSConfigAHS.GetTSFromWS(oNetwork, stationId, varCode, startDt, endDt, "")
      'tsProxy.Url = oNetwork.WebServiceURL
      'timeSeriesStr = tsProxy.GetValues(stationId, varCode, startDt, endDt, "")
    Catch ex As Exception
      Return ApSConfigAHS.K_TagError & "Error Accessing Values. " & ex.ToString & ApSConfigAHS.K_TagErrorEnd
      'Try
      '  timeSeriesStr = wsProxyIID.GetValues(stationId, varCode, startDt, endDt, "")
      'Catch ex1 As Exception
      '  ApSConfigAHS.Write2Log("GetTimeSeriesInfo: " & 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("GetTimeSeriesInfoDEV(" & stationId & "," & varCode & "," & startDt & "," & endDt & " ", True, ds, False)
      End If

    End Try
    Return timeSeriesStr
  End Function

  ''' <summary>
  '''   Queries WS's for XML TimeSeries information
  ''' </summary>
  ''' <param name="tsInputStr"></param>
  ''' <returns>XML TimeSeries Document</returns>
  ''' <remarks></remarks>
  Private Function GetTimeSeriesInfoDEV(ByVal tsInputStr As String) As String
    Dim timeSeriesStr As String = Nothing
    Dim stationId As String = Nothing
    Dim varCode As String = Nothing
    Dim startDt As String = Nothing
    Dim endDt As String = Nothing
    Dim _startDate As String = Nothing
    Dim _endDate As String = Nothing
    Dim network As String = Nothing
    Dim timeSeriesData As String = Nothing
    Dim oNetwork As HISNetwork
    Dim ss() As String
    'Dim nwisTsIIDProxy As New edu.sdsc.water.NWISInstantaneousIrregularData
    Dim tsProxy As New edu.sdsc.water.NWISDailyValues
    'Dim epaTimeSeriesProxy As New edu.sdsc.water.STORET
    Try
      oNetwork = Me.Page.Session(ApSConfigAHS.KS_ACTIVENETWORK)
      Dim tsInputArray() As String = tsInputStr.Split(ApSConfigAHS.K_Sep2)
      If tsInputArray.Length > 0 Then
        network = tsInputArray(3)
        stationId = tsInputArray(3) & ":" & tsInputArray(1) '"11126500" '
        varCode = tsInputArray(3) & ":" & tsInputArray(5)
        startDt = tsInputArray(7)
        endDt = tsInputArray(8)
        ss = startDt.Split(" ")
        ss = ss(0).Split("/")
        startDt = ss(2) & "-" & IIf(ss(0).Length < 2, "0" & ss(0), ss(0)) & "-" & IIf(ss(1).Length < 2, "0" & ss(1), ss(1))
        ss = endDt.Split(" ")
        ss = ss(0).Split("/")
        endDt = ss(2) & "-" & IIf(ss(0).Length < 2, "0" & ss(0), ss(0)) & "-" & IIf(ss(1).Length < 2, "0" & ss(1), ss(1))

        'startDt = startDt.Replace("/", "-")
        'endDt = endDt.Replace("/", "-")
        tsProxy.Url = oNetwork.WebServiceURL
        timeSeriesStr = tsProxy.GetValues(stationId, varCode, startDt, endDt, "")
      End If

    Catch ex As Exception
      '..commented out.  Instantaneous flow should have its own WebServiceURL (HISNetwork)
      'Try
      '  If network.ToLower = ApSConfigAHS.NETWORK_NAME_NWIS Then
      '    timeSeriesStr = nwisTsIIDProxy.GetValues(stationId, varCode, startDt, endDt, "")
      '  End If
      'Catch ex1 As Exception
      '  If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
      '    ApSConfigAHS.Write2Log("GetTimeSeriesInfoDEV:" & ex.Message & ", " & ex.StackTrace, True, -1, False)
      '  End If
      '  Throw ex1
      'End Try
    End Try
    Return timeSeriesStr
  End Function

  ''' <summary>
  '''   Returns Time series object from XML timeseries document  
  ''' </summary>
  ''' <param name="wsResponse"></param>
  ''' <returns>Time Series Object</returns>
  ''' <remarks></remarks>
  Private Function toTimeSeriesInfo(ByVal wsResponse As String, ByVal FeatureID As Integer, ByVal TSTypeID As Integer) As TimeSeries

    Dim settings As New XmlReaderSettings
    settings.IgnoreWhitespace = True
    settings.IgnoreComments = True
    Dim dtValue As String = Nothing
    Dim _value As String = Nothing
    Dim tsInfo As New TimeSeries
    Dim vInfo As ValueInfo = Nothing
    Dim ii As Integer
    Dim oReader As System.IO.StringReader
    Try
      ' dump the GetValues WS response into an xml file.
      Dim sName As String = getDateTimeAsString(Date.Now, True)
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.ShowMsg1) = ApSConfigAHS.DebugType.ShowMsg1) Then
        Dim outPath As String = Server.MapPath("tmp\" & sName & "TS.xml")
        System.IO.File.WriteAllText(outPath, wsResponse)
      End If

      oreader = New System.IO.StringReader(wsResponse)
      Using reader As XmlTextReader = New XmlTextReader(oReader)    ' New XmlTextReader(outPath)
        ii = 0
        While reader.Read()
          If reader.NodeType = XmlNodeType.Element Then
            sName = reader.Name
            Select Case sName.ToUpper
              Case "SITENAME"
                reader.Read()
                tsInfo.siteName = reader.Value()
              Case "SITECODE"
                reader.Read()
                tsInfo.siteCode = reader.Value()
              Case "LATITUDE"
                reader.Read()
                tsInfo.latitude = reader.Value()
              Case "LONGITITUDE"
                reader.Read()
                tsInfo.longitude = reader.Value()
              Case "VARIABLECODE"
                reader.Read()
                tsInfo.variableCode = reader.Value()
              Case "VALUES"
                Do Until (reader.NodeType = XmlNodeType.EndElement And reader.Name.ToUpper = "VALUES")
                  reader.Read()
                  If (reader.NodeType = XmlNodeType.Element And reader.Name.ToUpper = "VALUE") Then
                    dtValue = reader.GetAttribute("dateTime")
                    reader.Read()
                    If Not dtValue Is Nothing Then
                      _value = reader.Value()
                      tsInfo.addValueInfo(dtValue, _value, FeatureID, TSTypeID)
                    End If
                  End If
                  ii = ii + 1
                  If (ii > ApSConfigAHS.MAX_Loops) Then Exit Do
                Loop
            End Select
          End If
          ii = ii + 1
          If (ii > ApSConfigAHS.MAX_Loops) Then Exit While
        End While
        'Dim outPath As String = Server.MapPath("tmp\" & sName & "TS.xml")
        'System.IO.File.WriteAllText(outPath, sbCheck.ToString)
      End Using

    Catch ex As Exception
      If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
        ApSConfigAHS.Write2Log("ToTimeSeriesInfo:" & ex.Message & ", " & ex.StackTrace, True, -1, False)
      End If
      Throw ex
    End Try
    Return tsInfo
  End Function

  'Private Function toTimeSeriesInfo(ByVal wsResponse As String, ByVal FeatureID As Integer, ByVal TSTypeID As Integer) As TimeSeries
  '  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 isFlag As Boolean = False
  '  Dim dtValue As String = Nothing
  '  Dim _value As String = Nothing
  '  Dim valueCount As String = Nothing
  '  Dim isSiteCode As String = Nothing
  '  Dim isSiteName As String = Nothing
  '  Dim isLat As String = Nothing
  '  Dim isLong As String = Nothing
  '  Dim isVarCode As String = Nothing
  '  Dim isVocabulary As String = Nothing

  '  Dim tsInfo As New TimeSeries
  '  Dim vInfo As ValueInfo = Nothing

  '  Try
  '    ' dump the GetValues WS response into an xml file.
  '    Dim sName As String = getDateTimeAsString(Date.Now, True)
  '    If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.ShowMsg1) = ApSConfigAHS.DebugType.ShowMsg1) Then
  '      Dim outPath As String = Server.MapPath("tmp\" & sName & "TS.xml")
  '      System.IO.File.WriteAllText(outPath, wsResponse)
  '    End If

  '    Dim oReader As System.IO.StringReader = New System.IO.StringReader(wsResponse)
  '    Using reader As XmlTextReader = New XmlTextReader(oReader)    ' New XmlTextReader(outPath)
  '      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("value") Then
  '            isValueElement = True
  '          Else
  '            isValueElement = False
  '          End If

  '          If reader.Name.Equals("locationParam") 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("latitude") Then
  '            isLat = True
  '          Else
  '            isLat = False
  '          End If

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

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

  '        If Not isFlag Then
  '          dtValue = reader.GetAttribute("dateTime")
  '        End If

  '        If Not dtValue Is Nothing Then
  '          '  System.Diagnostics.Debug.WriteLine("DateTime :" & dtValue)
  '          ' strbData.Append(dtValue & ",")
  '          isFlag = True
  '        End If

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

  '        If reader.NodeType = XmlNodeType.Text Then
  '          If isValueElement Then
  '            'strbData.Append(reader.Value())
  '            'strbData.Append(vbCrLf)
  '            _value = reader.Value()
  '            'System.Diagnostics.Debug.WriteLine("Value :" & reader.Value())
  '            tsInfo.addValueInfo(dtValue, _value, FeatureID, TSTypeID)
  '            isFlag = False
  '          End If

  '          If isSiteCode Then
  '            'strbData.Append(reader.Value())
  '            'strbData.Append(vbCrLf)
  '            'System.Diagnostics.Debug.WriteLine("SiteCode :" & reader.Value())
  '            tsInfo.siteCode = reader.Value()
  '          End If

  '          If isSiteName Then
  '            'strbData.Append(reader.Value())
  '            'strbData.Append(vbCrLf)
  '            'System.Diagnostics.Debug.WriteLine("SiteName :" & reader.Value())
  '            tsInfo.siteName = reader.Value()
  '          End If
  '          If isLat Then
  '            'strbData.Append(reader.Value())
  '            'strbData.Append(vbCrLf)
  '            ' System.Diagnostics.Debug.WriteLine("Lat :" & reader.Value())
  '            tsInfo.latitude = reader.Value()
  '          End If

  '          If isLong Then
  '            'strbData.Append(reader.Value())
  '            'strbData.Append(vbCrLf)
  '            'System.Diagnostics.Debug.WriteLine("Long :" & reader.Value())
  '            tsInfo.longitude = reader.Value()
  '          End If

  '          If isVarCode Then
  '            'System.Diagnostics.Debug.WriteLine("Var Code :" & reader.Value())
  '            tsInfo.variableCode = reader.Value()
  '          End If
  '        End If
  '      End While
  '    End Using

  '  Catch ex As Exception
  '    If ((ApSConfigAHS.WebDebug And ApSConfigAHS.DebugType.LogError) = ApSConfigAHS.DebugType.LogError) Then
  '      ApSConfigAHS.Write2Log("ToTimeSeriesInfo:" & ex.Message & ", " & ex.StackTrace, True, -1, False)
  '    End If
  '    Throw ex
  '  End Try
  '  Return tsInfo
  'End Function

  Protected Sub Refresh_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Refresh.Click
    bindGrid(Me.CheckAll.Checked)
  End Sub

  'Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
  '  Dim sUser As String
  '  Dim s As String = ""
  '  If Not s Is Nothing Then
  '    sUser = Context.User.Identity.Name
  '    If (sUser <> "") Then
  '      Dim sMsg As String = s
  '      Dim sSubject As String = Date.Now
  '      ApSConfigAHS.SendEmail(sUser, sMsg, sSubject)
  '    End If
  '  End If

  'End Sub

  Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
    Dim s As String = ""
    Try
      s = Write2HTML()
    Catch ex As Exception
    Finally
    End Try
    Page.Response.Write(s)

  End Sub

  Private Function Write2HTML() As String
    '*****************************************************************
    'Copyright © 2006 ESRI. All Rights Reserved.
    '*****************************************************************
    'Description: write efid to the page
    'History: z.ye @1/27/2006 1:31:39 PM
    '*****************************************************************
    Dim sb As New System.Text.StringBuilder
    Dim sMsg As String
    Try
      sMsg = CType(Session(K_CartMsg), String)
    Catch ex As Exception
      sMsg = ""
    Finally
      Session(K_CartMsg) = ""
    End Try
    sb.Append((ControlChars.Lf & "<script language=""javascript"">" & ControlChars.Lf))
    sb.Append("var sMsg='" & sMsg & "';" & ControlChars.Lf)
    sb.Append(("</script>" & ControlChars.Lf))
    Return sb.ToString
  End Function

End Class
