Click or drag to resize

ArcGISPortalFindItemsAsync Method (PortalQueryParameters)

Finds portal items that match the query parameters specified.

Namespace:  Esri.ArcGISRuntime.Portal
Assembly:  Esri.ArcGISRuntime (in Esri.ArcGISRuntime.dll) Version: 100.11.0
Syntax
public Task<PortalQueryResultSet<PortalItem>> FindItemsAsync(
	PortalQueryParameters queryParams
)

Parameters

queryParams
Type: Esri.ArcGISRuntime.PortalPortalQueryParameters
The search parameters.

Return Value

Type: TaskPortalQueryResultSetPortalItem
The task object representing the asynchronous search items operation. The value of the task result is a PortalQueryResultSetT object.
Remarks

This method obtains a PortalQueryResultSetT object that contains PortalItem objects. Use the Results property to get the collection of PortalItem objects.

Portal.PortalItem objects are user items, usually related to a specific area of interest such as maps, applications, and tools. This method allows searching for specific items within ArcGIS Online (AGOL) or ArcGIS Portal by providing PortalQueryParameters to limit the scope of which items are returned.

You do not have to be a logged in user to get information from this method. You can gain this information from anonymous access. However, to obtain information about items that have a PortalAccess level of Private you need to use the AuthenticationManager by supplying the appropriate username/password credentials.

By default the Query property that is used in this method uses a default set of high performance index fields when providing simple keyword string(s) for the search. As of AGOL/ArcGIS Portal v2.1, these fields are: title, tags, snippet, description, accessinformation, spatialreference, type and typekeywords. For more advanced searches, developers can preface their simple keyword strings with a more exhaustive set of REST named fields followed by a colon (:). These advanced searches can also take advantage of Boolean operators (AND, NOT, OR, +), wildcard operators (* and ?), as well as other techniques to more fully utilize the AGOL/ArcGIS Portal search capabilities. Comprehensive details on using the advanced search strings that follow the REST specification can be found in the Search Reference document in the ArcGIS Portal API.

The following are a few advanced REST search scenarios with example strings that you might consider using for the Query property:

To find one specific PortalItem by it's Id: "id:00e5e70929e14055ab686df16c842ec1"
To find all WebMap PortalItems with the word 'florida' in the Title field: "title:florida AND type:web map"
To find all Layer Package PortalItems with the word 'florida' in the Title field: "title:florida AND type:layer package"
To find all PortalItems with the word 'florida' in the Title field and the word 'esri' in the LicenseInfo field: "title:florida AND licenseinfo:esri"
To find all PortalItems with the word 'florida' in the Title field and not have the word 'esri' in the LicenseInfo field: "title:florida NOT licenseinfo:esri"
To find all PortalItems with located within a specific spatial extent and the word 'esri' in the LicenseInfo: "extent:[-114.3458, 21.7518] - [-73.125, 44.0658] AND licenseinfo:esri"
To find all PortalItems with a SpatialReference.WKID of 4267: "spatialreference:4267"
To find all PortalItems with a SpatialReference.WKID of 4267 or have the word 'cancer' in the Title field: "spatialreference:4267 OR title:cancer"

NOTE: It is not required to use the advanced REST search syntax to find PortalItems with this method. Simple string syntax for the Query property such as: "florida" will find all occurrences of that string in the default high performance index fields.

Examples

WPF

Example Name: IntegratedWindowsAuth

Connect to an IWA secured Portal and search for maps.

Code example screen shot.

C#
// Copyright 2018 Esri.
// 
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an 
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific 
// language governing permissions and limitations under the License.

using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Portal;
using Esri.ArcGISRuntime.Security;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace ArcGISRuntime.WPF.Samples.IntegratedWindowsAuth
{
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Integrated Windows Authentication",
        category: "Security",
        description: "Connect to an IWA secured Portal and search for maps.",
        instructions: "1. Enter the URL to your IWA-secured portal.",
        tags: new[] { "Portal", "Windows", "authentication", "security" })]
    [ArcGISRuntime.Samples.Shared.Attributes.ClassFile("LoginWindow.xaml.cs")]
    [ArcGISRuntime.Samples.Shared.Attributes.XamlFiles("LoginWindow.xaml")]
    public partial class IntegratedWindowsAuth
    {
        // The ArcGIS Online URL for searching public web maps.
        private string _publicPortalUrl = "https://www.arcgis.com";

        // The public and secured portals.
        ArcGISPortal _iwaSecuredPortal = null;
        ArcGISPortal _publicPortal = null;

        // Track if the user is looking at search results from the public or secured portal.
        bool _usingPublicPortal;

        // Track if the user has canceled the login dialog.
        bool _canceledLogin;

        public IntegratedWindowsAuth()
        {
            InitializeComponent();

            // Define a challenge handler method for the AuthenticationManager.
            // This method handles getting credentials when a secured resource is encountered.
            // Note: for IWA-secured services, the current system credentials will be used by default.
            // The user will only be challenged for resources the current account doesn't have permissions for.
            AuthenticationManager.Current.ChallengeHandler = new ChallengeHandler(CreateCredentialAsync);
        }

        // Prompt the user for a credential if unauthorized access to a secured resource is attempted.
        public async Task<Credential> CreateCredentialAsync(CredentialRequestInfo info)
        {
            Credential credential = null;
            try
            {
                // Dispatch to the UI thread to show the login UI.
                credential = Dispatcher.Invoke(new Func<Credential>(() =>
                {
                    Credential cred = null;

                    // Exit if the user clicked "Cancel" in the login window.
                    // The dialog will continue to be challenge the user if incorrect credentials are entered.
                    if (_canceledLogin)
                    {
                        _canceledLogin = false;
                        return null;
                    }

                    // Create a new login window.
                    var win = new LoginWindow();

                    // Show the window to get the user login (if canceled, false is returned).
                    _canceledLogin = (win.ShowDialog() == false);

                    if (!_canceledLogin)
                    {
                        // Get the credential information provided.
                        var username = win.UsernameTextBox.Text;
                        var password = win.PasswordTextBox.Password;
                        var domain = win.DomainTextBox.Text;

                        // Create a new network credential using the user input and the URI of the resource.
                        cred = new ArcGISNetworkCredential()
                        {
                            Credentials = new System.Net.NetworkCredential(username, password, domain),
                            ServiceUri = info.ServiceUri
                        };
                    }

                    // Return the credential
                    return cred;
                }));
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception: " + ex.Message);
            }

            // Add the credential to the AuthenticationManager.
            AuthenticationManager.Current.AddCredential(credential);

            // Return the credential.
            return credential;
        }

        // Search the public portal for web maps and display the results in a list.
        private async void SearchPublicMapsClick(object sender, RoutedEventArgs e)
        {
            // Set a variable that indicates this is the public portal.
            // When a map is loaded from the results, will need to know which portal it came from.
            _usingPublicPortal = true;

            try
            {
                // Create an instance of the public portal.
                _publicPortal = await ArcGISPortal.CreateAsync(new Uri(_publicPortalUrl));

                // Call a function to search the portal.
                SearchPortal(_publicPortal);
            }
            catch (Exception ex)
            {
                // Report any errors encountered.
                MessagesTextBlock.Text = ex.Message;
            }
        }

        // Search the IWA-secured portal for web maps and display the results in a list.
        private async void SearchSecureMapsButtonClick(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get the string entered for the secure portal URL.
                string securedPortalUrl = SecurePortalUrlTextBox.Text.Trim();

                // Make sure a portal URL has been entered in the text box.
                if (string.IsNullOrEmpty(securedPortalUrl))
                {
                    MessageBox.Show("Please enter the URL of the secured portal.", "Missing URL");
                    return;
                }


                // Check if the current Window credentials should be used or require an explicit login.
                bool requireLogin = RequireLoginCheckBox.IsChecked == true;

                // Create an instance of the IWA-secured portal, the user may be challenged for access.
                _iwaSecuredPortal = await ArcGISPortal.CreateAsync(new Uri(securedPortalUrl), requireLogin);

                // Call a function to search the portal.
                SearchPortal(_iwaSecuredPortal);

                // Set a variable that indicates this is the secure portal.
                // When a map is loaded from the results, will need to know which portal it came from.
                _usingPublicPortal = false;
            }
            catch (Exception ex)
            {
                // Report errors (connecting to the secured portal, for example).
                MessagesTextBlock.Text = ex.Message;
            }
        }

        private async void SearchPortal(ArcGISPortal currentPortal)
        {
            // Remove any existing results from the list.
            MapItemListBox.Items.Clear();

            // Show a status message and progress bar.
            MessagesTextBlock.Text = "Searching for web map items on the portal at " + currentPortal.Uri.AbsoluteUri;
            ProgressStatus.Visibility = Visibility.Visible;
            var messageBuilder = new StringBuilder();

            try
            {
                // Report connection info.
                messageBuilder.AppendLine("Connected to the portal on " + currentPortal.Uri.Host);

                // Report the user name used for this connection.
                if (currentPortal.User != null)
                {
                    messageBuilder.AppendLine("Connected as: " + currentPortal.User.UserName);
                }
                else
                {
                    // Note: This shouldn't happen for a secure portal!
                    messageBuilder.AppendLine("Anonymous");
                }

                // Search the portal for web maps.
                var items = await currentPortal.FindItemsAsync(new PortalQueryParameters("type:(\"web map\" NOT \"web mapping application\")"));

                // Build a list of items from the results that shows the map name and stores the item ID (with the Tag property).
                var resultItems = from r in items.Results select new ListBoxItem { Tag = r.ItemId, Content = r.Title };

                // Add the items to the list box.
                foreach (var itm in resultItems)
                {
                    MapItemListBox.Items.Add(itm);
                }

                // Enable the button for adding a web map.
                AddMapItem.IsEnabled = true;
            }
            catch (Exception ex)
            {
                // Report errors searching the portal.
                messageBuilder.AppendLine(ex.Message);
            }
            finally
            {
                // Show messages, hide the progress bar.
                MessagesTextBlock.Text = messageBuilder.ToString();
                ProgressStatus.Visibility = Visibility.Hidden;
            }
        }

        private async void AddMapItemClick(object sender, RoutedEventArgs e)
        {
            // Get a web map from the selected portal item and display it in the map view.
            if (MapItemListBox.SelectedItem == null)
            {
                MessageBox.Show("No web map item is selected.");
                return;
            }

            // Clear status messages.
            MessagesTextBlock.Text = string.Empty;

            // Store status (or errors) when adding the map.
            var statusInfo = new StringBuilder();

            try
            {
                // Clear the current MapView control from the app.
                MyMapGrid.Children.Clear();

                // See if using the public or secured portal; get the appropriate object reference.
                ArcGISPortal portal = null;
                if (_usingPublicPortal)
                {
                    portal = _publicPortal;
                }
                else
                {
                    portal = _iwaSecuredPortal;
                }

                // Throw an exception if the portal is null.
                if (portal == null)
                {
                    throw new Exception("Portal has not been instantiated.");
                }

                // Get the portal item ID from the selected list box item (read it from the Tag property).
                var itemId = (this.MapItemListBox.SelectedItem as ListBoxItem).Tag.ToString();

                // Use the item ID to create a PortalItem from the portal.
                var portalItem = await PortalItem.CreateAsync(portal, itemId);

                if (portalItem != null)
                {
                    // Create a Map using the web map (portal item).
                    Map webMap = new Map(portalItem);

                    // Create a new MapView control to display the Map.
                    MapView myMapView = new MapView
                    {
                        Map = webMap
                    };

                    // Add the MapView to the UI.
                    MyMapGrid.Children.Add(myMapView);
                }

                // Report success.
                statusInfo.AppendLine("Successfully loaded web map from item #" + itemId + " from " + portal.Uri.Host);
            }
            catch (Exception ex)
            {
                // Add an error message.
                statusInfo.AppendLine("Error accessing web map: " + ex.Message);
            }
            finally
            {
                // Show messages.
                MessagesTextBlock.Text = statusInfo.ToString();
            }
        }
    }
}
C#
using System.Windows;
using System.Windows.Controls;

namespace ArcGISRuntime.WPF.Samples.IntegratedWindowsAuth
{    
    // A simple UI for entering network credential information (username, password, and domain)
    public partial class LoginWindow : Window
    {
        public LoginWindow()
        {
            InitializeComponent();
        }

        // A handler for both the "Login" and "Cancel" buttons on the page
        private void ButtonClick(object sender, RoutedEventArgs e)
        {
            // Set the dialog result to indicate whether or not "Cancel" was clicked
            this.DialogResult = !(sender as Button).IsCancel;

            // Close the window
            this.Close();
        }
    }
}
XAML
<UserControl x:Class="ArcGISRuntime.WPF.Samples.IntegratedWindowsAuth.IntegratedWindowsAuth" 
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013"
             xmlns:mapping="clr-namespace:Esri.ArcGISRuntime.Mapping;assembly=Esri.ArcGISRuntime">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="350" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <Border Grid.Column="0" Background="LightGray" BorderBrush="Black" BorderThickness="0,0,2,0">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="100" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="50" />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Button
                    x:Name="SearchPublicMapsButton"
                    Grid.Row="0"
                    Width="265"
                    Height="35"
                    Margin="0,50,0,0"
                    Click="SearchPublicMapsClick"
                    Content="Search ArcGIS Online maps" />
                <Grid Grid.Row="1">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                    </Grid.RowDefinitions>
                    <Button
                        x:Name="SearchSecureMapsButton"
                        Grid.Row="1"
                        Width="265"
                        Height="35"
                        Click="SearchSecureMapsButtonClick"
                        Content="Search IWA secured maps" />
                    <TextBox
                        x:Name="SecurePortalUrlTextBox"
                        Grid.Row="0"
                        Width="265"
                        Height="20"
                        Margin="0,5" />
                    <TextBlock
                        Grid.Row="0"
                        Margin="50,5"
                        HorizontalAlignment="Left"
                        VerticalAlignment="Center"
                        Foreground="DarkGray"
                        IsHitTestVisible="False"
                        Text="Enter the URL to your secured portal">
                        <TextBlock.Style>
                            <Style TargetType="{x:Type TextBlock}">
                                <Setter Property="Visibility" Value="Collapsed" />
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding Text, ElementName=SecurePortalUrlTextBox}" Value="">
                                        <Setter Property="Visibility" Value="Visible" />
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </TextBlock.Style>
                    </TextBlock>
                    <CheckBox
                        x:Name="RequireLoginCheckBox"
                        Grid.Row="2"
                        Margin="45,5"
                        Content="Force login"
                        IsChecked="False" />
                </Grid>
                <ListBox
                    x:Name="MapItemListBox"
                    Grid.Row="2"
                    Width="265"
                    Height="150"
                    Margin="0,40,0,5"
                    FontSize="12" />
                <Button
                    x:Name="AddMapItem"
                    Grid.Row="3"
                    Width="265"
                    Height="35"
                    Click="AddMapItemClick"
                    Content="Load Web Map"
                    IsEnabled="False" />
                <StackPanel x:Name="MessagePanel" Grid.Row="4" Margin="10" Orientation="Vertical">
                    <ScrollViewer>
                        <TextBlock x:Name="MessagesTextBlock" Text="Using default system credentials." TextWrapping="Wrap" />
                    </ScrollViewer>
                    <ProgressBar x:Name="ProgressStatus" IsIndeterminate="True" Visibility="Collapsed" />
                </StackPanel>
            </Grid>
        </Border>

        <Grid x:Name="MyMapGrid" Grid.Column="1">
            <esri:MapView>
                <mapping:Map>
                    <mapping:Map.OperationalLayers>
                        <mapping:ArcGISTiledLayer Source="http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer" />
                    </mapping:Map.OperationalLayers>
                </mapping:Map>
            </esri:MapView>
        </Grid>
    </Grid>
</UserControl>
XAML
<Window x:Class="ArcGISRuntime.WPF.Samples.IntegratedWindowsAuth.LoginWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Please Login" Height="185" Width="350">
  <Grid>
    <Canvas x:Name="LoginPanel"
        Margin="10">
      <Border x:Name="ToolsPanel" 
          CornerRadius="10" 
          Background="DarkGray" Opacity="0.85"
          Width="320" 
          Canvas.Top="0">
        <Grid x:Name="AddDataGrid" 
            Margin="0,10,0,0">
          <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
          </Grid.RowDefinitions>
          <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="2*"/>
          </Grid.ColumnDefinitions>
          <TextBlock Text="User:"
              Grid.Row="0" Grid.Column="0"
              FontSize="14"
              HorizontalAlignment="Right" VerticalAlignment="Center"/>
          <TextBox x:Name="UsernameTextBox"
              Grid.Row="0" Grid.Column="1"
              Margin="5"
              FontSize="14"/>
          <TextBlock Text="Password:"
              Grid.Row="1" Grid.Column="0"
              FontSize="14"
              HorizontalAlignment="Right" VerticalAlignment="Center"/>
          <PasswordBox x:Name="PasswordTextBox"
              Grid.Row="1" Grid.Column="1"
              Margin="5"
              FontSize="14"/>
          <TextBlock Text="Domain:"
              Grid.Row="2" Grid.Column="0"
              FontSize="14"
              HorizontalAlignment="Right" VerticalAlignment="Center"/>
          <TextBox x:Name="DomainTextBox"
              Grid.Row="2" Grid.Column="1"
              Margin="5"
              FontSize="14"/>
          <Button x:Name="CancelButton" 
              Grid.Row="3" Grid.Column="0"
              HorizontalAlignment="Right" VerticalAlignment="Center"
              Margin="5"
              Content="Cancel" 
              Width="75"
              Click="ButtonClick" IsCancel="True"/>
          <Button x:Name="LoginButton" 
              Grid.Row="3" Grid.Column="1"
              HorizontalAlignment="Center" VerticalAlignment="Center"
              Margin="5"
              Content="Login" 
              Width="75"
              Click="ButtonClick"/>
        </Grid>
      </Border>
    </Canvas>
  </Grid>
</Window>
See Also
Additional Examples
Hyperlink to ExampleDescription
IntegratedWindowsAuthConnect to an IWA secured Portal and search for maps.
SearchPortalMapsFind webmap portal items by using a search term.