Common Query New Window
Common_QueryNewWindow_VBNet\Default.aspx.vb
' Copyright 2010 ESRI
' 
' All rights reserved under the copyright laws of the United States
' and applicable international laws, treaties, and conventions.
' 
' You may freely redistribute and use this sample code, with or
' without modification, provided you include the original copyright
' notice and use restrictions.
' 
' See the use restrictions.
' 

Imports Microsoft.VisualBasic
Imports System
Public Partial Class [Default]
  Inherits System.Web.UI.Page
  Protected Sub btnQuery_Click(ByVal sender As Object, ByVal eventArgs As System.EventArgs)
    Try
      ' Specify the name of the layer to query
      Dim queryLayerName As String = "States"
      ' Specify the name of the field to query
      Dim queryFieldName As String = "STATE_NAME"
      ' Specify the value sought.  With the out-of-the-box implementation, the query will search
      ' for values in the query field that begin with this value
      Dim matchValue As String = "A"

      ' Since no Map is present, we need to initialize the MapResourceManager
      If (Not MapResourceManager1.Initialized) Then
        MapResourceManager1.Initialize()
      End If

      ' Retrieve the resource to be used
      Dim mapResourceItem As ESRI.ArcGIS.ADF.Web.UI.WebControls.MapResourceItem = MapResourceManager1.ResourceItems.Find("Map Resource")
      Dim gisResource As ESRI.ArcGIS.ADF.Web.DataSources.IGISResource = mapResourceItem.Resource

      ' We also need to initialize the resource underlying the resource item we will use
      If (Not gisResource.Initialized) Then
        mapResourceItem.InitializeResource()
      End If

      ' Generate a random number.  This will be used to enable storing and retrieving multiple
      ' tables to and from Session
      Dim random As System.Random = New System.Random()
      Dim randomTableID As Integer = random.Next(0, 1000)

      ' Create a Common Data Source API QueryFunctionality object to use for querying the resource    
      Dim commonQueryFunctionality As ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality = CType(gisResource.CreateFunctionality(GetType(ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality), Nothing), ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality)

      ' Populate arrays with the IDs and names of the queryable layers contained in the resource
      Dim layerIDs As String()
      Dim layerNames As String()
      commonQueryFunctionality.GetQueryableLayers(Nothing, layerIDs, layerNames)

      ' Find the index of the query layer in the layer ID and name arrays
      Dim queryLayerIndex As Integer = 0
      Dim i As Integer = 0
      Do While i < layerNames.Length
        If layerNames(i) = queryLayerName Then
          queryLayerIndex = i
          Exit Do
        End If
        i += 1
      Loop

      ' Initialize a query filter to search the specified field for any values that begin with
      ' the specified value.
      Dim adfQueryFilter As ESRI.ArcGIS.ADF.Web.QueryFilter = New ESRI.ArcGIS.ADF.Web.QueryFilter()
      Dim fieldStringCollection As ESRI.ArcGIS.ADF.StringCollection = New ESRI.ArcGIS.ADF.StringCollection(queryFieldName, ","c)
      adfQueryFilter.SubFields = fieldStringCollection
      adfQueryFilter.ReturnADFGeometries = False
      adfQueryFilter.WhereClause = String.Format("{0} LIKE '{1}%'", queryFieldName, matchValue)

      ' Execute the query and store the results in a DataTable
      Dim resultsDataTable As System.Data.DataTable = commonQueryFunctionality.Query(Nothing, layerIDs(queryLayerIndex), adfQueryFilter)

      ' Retrieve the LayerFormat object for the query layer.  This will provide access to field aliases.
      Dim layerFormat As ESRI.ArcGIS.ADF.Web.UI.WebControls.LayerFormat = ESRI.ArcGIS.ADF.Web.UI.WebControls.LayerFormat.FromMapResourceManager(MapResourceManager1, "Map Resource", layerIDs(queryLayerIndex))

      ' Set the name of the query field column in the results data table to the query field alias
      i = 0
      Do While i < layerFormat.Fields.Count
        ' Before changing the column name, make sure that the query field has a valid alias defined
        ' that is distinct from the actual field name
        If (layerFormat.Fields(i).Name = queryFieldName) AndAlso (layerFormat.Fields(i).Alias <> queryFieldName) AndAlso (layerFormat.Fields(i).Alias <> "") Then
          resultsDataTable.Columns(queryFieldName).ColumnName = layerFormat.Fields(i).Alias
        End If
        i += 1
      Loop

      ' Store the results data table in Session, using the random table ID as part of the key
      Dim tableSessionKey As String = String.Format("dataTable{0}", randomTableID)
      Session(tableSessionKey) = resultsDataTable

      ' Construct a JavaScript string to inject into the page that will open the TableDialog page.
      ' Include the random table ID in this page so that (a) TableDialog can retrieve the proper table
      ' from Session and (b) a new window is always opened, even when the query is executed multiple
      ' times
      Dim jsOpenQueryResultsWindow As String = String.Format("<script>window.open('TableDialog.aspx?id={0}" & "', '{0}', 'dependent=yes ,width=400, height=200, status=no, toolbar=no, menubar=no, " & "location=no, resizable=yes, scrollbars=yes'); </script>", randomTableID)
      Response.Write(jsOpenQueryResultsWindow)

      ' Construct a JavaScript string to open the query results in a modeless dialog.  For more info, see:
      ' http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/methods/showmodelessdialog.asp
      'string jsOpenQueryResultsModelessDialog = string.Format("<script>window.showModelessDialog(" +
      '    "'TableDialog.aspx?id={0}'); </script>", randomTableID);
      'Response.Write(jsOpenQueryResultsModelessDialog);
    Catch exception As System.Exception
      Dim jsAlertError As String = String.Format("<script>{0}</script>", GetJavaScriptErrorString(exception))
      Response.Write(jsAlertError)
    End Try
  End Sub

  ' Constructs JavaScript necessary to display an error message based on the passed-in exception.
  Private Function GetJavaScriptErrorString(ByVal exception As System.Exception) As String
    ' Get the website's configuration file
    Dim webConfig As System.Configuration.Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.HttpContext.Current.Request.ApplicationPath)

    ' Get the "compilation" section of the config file
    Dim compilationSection As System.Web.Configuration.CompilationSection = TryCast(webConfig.GetSection("system.web/compilation"), System.Web.Configuration.CompilationSection)

    ' If the config file's compilation section specifies debug mode, include 
    ' stack trace information in the error message.  Otherwise, just return 
    ' the exception message.
    Dim errorMessage As String = Nothing
    If (Not compilationSection Is Nothing) AndAlso (compilationSection.Debug) Then
      Dim stackTrace As String = exception.StackTrace.Replace("\", "\\")
      errorMessage = exception.Message & "\n\n" & stackTrace.Trim()
    Else
      errorMessage = exception.Message
    End If

    ' Create a callback result to display an error message
    Dim jsAlertException As String = "alert('" & errorMessage & "')"
    Return jsAlertException
  End Function
End Class