Click or drag to resize

PortalQueryResultSetT Class

Represents the result of a portal search returning an enumeration of T objects.
Inheritance Hierarchy
SystemObject
  Esri.ArcGISRuntime.PortalPortalQueryResultSetT

Namespace:  Esri.ArcGISRuntime.Portal
Assembly:  Esri.ArcGISRuntime (in Esri.ArcGISRuntime.dll) Version: 100.7.0.0
Syntax
C#
public sealed class PortalQueryResultSet<T>

Type Parameters

T
The type of data returned by the search as an enumeration of T.

The PortalQueryResultSetT type exposes the following members.

Constructors
  NameDescription
Public methodPortalQueryResultSetT
Initializes a new instance of the PortalQueryResultSetT class.
Top
Properties
  NameDescription
Public propertyNextQueryParameters
Gets the query params for the next set of results based on the next start index. This is automatically generated if there are more results left to be retrieved. This will be null if there are no more results for the next page.
Public propertyQueryParameters
Gets the query parameters used to make the search.
Public propertyCode exampleResults
Gets the present results of the query. This could be and array of PortalGroup or PortalItem depending on the query that was performed.
Public propertyTotalResultsCount
Gets the total number of results irrespective of the paging.
Top
Examples

Android

Example Name: IntegratedWindowsAuth

Use Windows credentials to access services hosted on a portal secured with Integrated Windows Authentication (IWA).

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 System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Android.App;
using Android.OS;
using Android.Support.V7.View;
using Android.Text;
using Android.Views;
using Android.Views.InputMethods;
using Android.Widget;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Portal;
using Esri.ArcGISRuntime.Security;
using Esri.ArcGISRuntime.UI.Controls;
using ContextThemeWrapper = Android.Support.V7.View.ContextThemeWrapper;

// *****************************************
// Important: Integrated Windows Authentication does not work with the AndroidClientHandler Http handler. 
// To use IWA successfully, change the project properties to use the Managed handler (HttpClientHandler).
// *****************************************
namespace ArcGISRuntimeXamarin.Samples.IntegratedWindowsAuth
{
    [Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
           "Integrated Windows Authentication",
           "Security",
           "This sample demonstrates how to use a Windows login to authenticate with a portal that is secured with IWA.",
           "1. Enter the URL to your IWA-secured portal.\n2. Click the button to search for web maps on the secure portal.\n3. You will be prompted for a user name, password, and domain to authenticate with the portal.\n4. If you authenticate successfully, search results will display.",
           "Authentication, Security, Windows")]
    public class IntegratedWindowsAuth : Activity
    {
        // The ArcGIS Online URL for searching public web maps.
        private string _publicPortalUrl = "http://www.arcgis.com";

        // A TaskCompletionSource to store the result of a login task.
        TaskCompletionSource<Credential> _loginTaskCompletionSrc;

        // A map view to display a map in the app.
        MapView _myMapView;

        // Entry box for the iwa-secured portal.
        private EditText _securePortalEditText;

        // Label for messages.
        private TextView _messagesTextView;

        // Button for searching the public portal for web maps.
        private Button _searchPublicPortalButton;

        // Button for searching the private portal for web maps.
        private Button _searchSecurePortalButton;

        // List view to show web map items.
        private ListView _webMapListView;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Title = "Integrated Windows Authentication";

            // Call a function to create the user interface.
            CreateLayout();

            // Call a function to initialize the app.
            Initialize();
        }

        private void CreateLayout()
        {
            // Create a new vertical layout for the app.
            LinearLayout layout = new LinearLayout(this) { Orientation = Orientation.Vertical };

            // Create the entry for the secure portal URL.
            _securePortalEditText = new EditText(this) { Hint = "IWA-secured portal URL" };
            _securePortalEditText.InputType = InputTypes.TextVariationUri;

            // Hide the keyboard on enter.
            _securePortalEditText.KeyPress += (sender, args) =>
            {
                if (args.Event.Action == KeyEventActions.Down && args.KeyCode == Keycode.Enter)
                {
                    InputMethodManager imm = (InputMethodManager)GetSystemService(InputMethodService);
                    imm.HideSoftInputFromWindow(_securePortalEditText.WindowToken, 0);
                    SearchSecurePortalButton_Click(this, null);
                }
                else
                {
                    args.Handled = false;
                }
            };

            // A label to show errors and other messages.
            _messagesTextView = new TextView(this);

            // Buttons to search a public and private portal.
            _searchPublicPortalButton = new Button(this) { Text = "Search public" };
            _searchSecurePortalButton = new Button(this) { Text = "Search secure" };

            // Event handlers to perform the appropriate search.
            _searchSecurePortalButton.Click += SearchSecurePortalButton_Click;
            _searchPublicPortalButton.Click += SearchPublicPortalButton_Click;

            // Add the buttons to a horizontal layout.
            LinearLayout buttonLayout = new LinearLayout(this) { Orientation = Orientation.Horizontal };
            buttonLayout.AddView(_searchPublicPortalButton);
            buttonLayout.AddView(_searchSecurePortalButton);

            // Create a list view to show web map item results.
            _webMapListView = new ListView(this)
            {
                ChoiceMode = ChoiceMode.Single
            };

            // Handle item click events to load the selected web map.
            _webMapListView.ItemClick += WebMapListView_ItemSelected;

            // Create a scroll view for the list.
            ScrollView listScroll = new ScrollView(this);
            listScroll.SetMinimumHeight(Resources.DisplayMetrics.HeightPixels / 5);
            listScroll.FillViewport = true;

            // Add the listview to the scroll view.
            listScroll.AddView(_webMapListView);

            // Add the controls to the layout.
            layout.AddView(_securePortalEditText);
            layout.AddView(buttonLayout);
            layout.AddView(listScroll);
            layout.AddView(_messagesTextView);
            _myMapView = new MapView(this);
            layout.AddView(_myMapView);

            // Show the layout in the app.
            SetContentView(layout);
        }

        private void WebMapListView_ItemSelected(object sender, AdapterView.ItemClickEventArgs e)
        {
            // When a row in the list is selected, get the associated web map item.
            PortalItemAdapter itemAdapter = _webMapListView.Adapter as PortalItemAdapter;
            PortalItem selectedItem = itemAdapter[e.Position];

            // Create a new map from the portal item and display it in the map view.
            Map webMap = new Map(selectedItem);
            _myMapView.Map = webMap;
        }


        private void Initialize()
        {
            // Define a challenge handler method for the AuthenticationManager.
            // This method handles getting credentials when a secured resource is encountered.
            AuthenticationManager.Current.ChallengeHandler = new ChallengeHandler(CreateCredentialAsync);

            // Show a default map (light gray canvas).
            Map defaultMap = new Map(Basemap.CreateLightGrayCanvasVector())
            {
                InitialViewpoint = new Viewpoint(0.0, 0.0, 200000000)
            };
            _myMapView.Map = defaultMap;
        }


        async void SearchSecurePortalButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Clear the current results from the list.
                _webMapListView.Adapter = null;

                // Get the value entered for the secure portal URL.
                string securedPortalUrl = _securePortalEditText.Text.Trim();

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

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

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

                // Report the username for this connection.
                if (iwaSecuredPortal.User != null)
                {
                    _messagesTextView.Text = "Connected as: " + iwaSecuredPortal.User.UserName;
                }
                else
                {
                    // This shouldn't happen (if the portal is truly secured)!
                    _messagesTextView.Text = "Connected anonymously";
                }
            }
            catch (TaskCanceledException)
            {
                // Report canceled login.
                _messagesTextView.Text = "Login was canceled";
            }
            catch (Exception ex)
            {
                // Report errors (connecting to the secured portal, for example).
                _messagesTextView.Text = ex.Message;
            }
            finally
            {
                // Set the task completion source to null so user can attempt another login (if it failed).
                _loginTaskCompletionSrc = null;
            }
        }

        private async void SearchPublicPortalButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Clear the current results from the list.
                _webMapListView.Adapter = null;

                // Create an instance of the public portal.
                var publicPortal = await ArcGISPortal.CreateAsync(new Uri(_publicPortalUrl));

                // Call a function to search the portal.
                SearchPortal(publicPortal);
            }
            catch (Exception ex)
            {
                // Report errors, if any.
                _messagesTextView.Text = ex.Message;
            }
        }


        private async void SearchPortal(ArcGISPortal currentPortal)
        {
            // Show status message.
            _messagesTextView.Text = "Searching for web map items on the portal at " + currentPortal.Uri.AbsoluteUri;
            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.
                var resultItems = from r in items.Results select new KeyValuePair<string, PortalItem>(r.Title, r);

                // Add the items to a dictionary.
                List<PortalItem> webMapItems = new List<PortalItem>();
                foreach (var itm in resultItems)
                {
                    webMapItems.Add(itm.Value);
                }

                // Create an array adapter for the result list.
                PortalItemAdapter adapter = new PortalItemAdapter(this, webMapItems);

                // Apply the adapter to the list view to show the results.
                _webMapListView.Adapter = adapter;

            }
            catch (Exception ex)
            {
                // Report errors searching the portal.
                messageBuilder.AppendLine(ex.Message);
            }
            finally
            {
                // Show messages.
               _messagesTextView.Text = messageBuilder.ToString();
            }
        }

        // AuthenticationManager.ChallengeHandler function that prompts the user for login information to create a credential.
        private  Task<Credential> CreateCredentialAsync(CredentialRequestInfo info)
        {
            // Ignore token or certificate challenges (needs additional code and UI).
            if(info.AuthenticationType != AuthenticationType.NetworkCredential)
            {
                Console.WriteLine("Skipped authentication for " + info.ServiceUri.Host);
                return null;
            }

            // See if authentication is already in progress.
            if (_loginTaskCompletionSrc != null) { return null; }

            // Create a new TaskCompletionSource for the login operation.
            // Passing the CredentialRequestInfo object to the constructor will make it available from its AsyncState property.
            _loginTaskCompletionSrc = new TaskCompletionSource<Credential>(info);

            // Create a dialog (fragment) with login controls.
            LoginDialogFragment enterLoginDialog = new LoginDialogFragment();

            // Handle the login and the cancel events.
            enterLoginDialog.OnLoginClicked += LoginClicked;
            enterLoginDialog.OnLoginCanceled += (s, e) =>
            {
                _loginTaskCompletionSrc?.TrySetCanceled();
                _loginTaskCompletionSrc = null;
            };

            // Begin a transaction to show a UI fragment (the login dialog).
            FragmentTransaction transax = FragmentManager.BeginTransaction();
            enterLoginDialog.Show(transax, "login");

            // Return the login task, the result will be ready when completed (user provides login info and clicks the "Login" button).
            return _loginTaskCompletionSrc.Task;
        }

        // Handler for the OnLoginClicked event defined in the LoginDialogFragment, OnEnterCredentialsEventArgs contains the username, password, and domain the user entered
        private void LoginClicked(object sender, OnEnterCredentialsEventArgs e)
        {
            // If no login information is available from the Task, return.
            if (_loginTaskCompletionSrc == null || _loginTaskCompletionSrc.Task == null || _loginTaskCompletionSrc.Task.AsyncState == null)
            {
                return;
            }

            // Get the CredentialRequestInfo object that was stored with the task.
            var credRequestInfo = _loginTaskCompletionSrc.Task.AsyncState as CredentialRequestInfo;

            try
            {
                // Create a new System.Net.NetworkCredential with the user name, password, and domain provided.
                var networkCredential = new System.Net.NetworkCredential(e.Username, e.Password, e.Domain);

                // Create a new ArcGISNetworkCredential with the NetworkCredential and URI of the secured resource.
                var credential = new ArcGISNetworkCredential
                {
                    Credentials = networkCredential,
                    ServiceUri = credRequestInfo.ServiceUri
                };

                // Set the result of the login task with the new ArcGISNetworkCredential.
                _loginTaskCompletionSrc.TrySetResult(credential);
            }
            catch (Exception ex)
            {
                _loginTaskCompletionSrc.TrySetException(ex);
            }
            finally
            {
                // Set the task completion source to null to indicate authentication is complete.
                _loginTaskCompletionSrc = null;
            }
        }
    }

    // Custom DialogFragment class to show input controls for providing network login information (username, password, domain).
    public class LoginDialogFragment : DialogFragment
    {
        // Login entries for the user to complete.
        private EditText _usernameTextbox;
        private EditText _passwordTextbox;
        private EditText _domainTextbox;

        // Event raised when the login button is clicked.
        public event EventHandler<OnEnterCredentialsEventArgs> OnLoginClicked;

        // Event raised when the login is canceled (Cancel button is clicked).
        public event EventHandler<EventArgs> OnLoginCanceled;

        // Override OnCreateView to create the dialog controls.
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            base.OnCreateView(inflater, container, savedInstanceState);
            var ctx = this.Activity.ApplicationContext;
            ContextThemeWrapper ctxWrapper = new ContextThemeWrapper(ctx, Android.Resource.Style.ThemeMaterialLight);

            // The container for the dialog is a vertical linear layout.
            LinearLayout dialogView = new LinearLayout(ctxWrapper) { Orientation = Orientation.Vertical };

            // Add a text box for entering a username.
            _usernameTextbox = new EditText(ctxWrapper)
            {
                Hint = "Username"
            };
            dialogView.AddView(_usernameTextbox);

            // Add a text box for entering a password.
            _passwordTextbox = new EditText(ctxWrapper)
            {
                Hint = "Password",
                InputType = Android.Text.InputTypes.TextVariationPassword | Android.Text.InputTypes.ClassText
            };
            dialogView.AddView(_passwordTextbox);

            // Add a text box for entering the domain.
            _domainTextbox = new EditText(ctxWrapper)
            {
                Hint = "Domain"
            };
            dialogView.AddView(_domainTextbox);

            // Use a horizontal layout for the two buttons (login and cancel).
            LinearLayout buttonsRow = new LinearLayout(ctxWrapper) { Orientation = Orientation.Horizontal };

            // Create a button to login with these credentials.
            Button loginButton = new Button(ctxWrapper)
            {
                Text = "Login"
            };
            loginButton.Click += LoginButtonClick;
            buttonsRow.AddView(loginButton);

            // Create a button to cancel.
            Button cancelButton = new Button(ctxWrapper)
            {
                Text = "Cancel"
            };
            cancelButton.Click += CancelButtonClick;
            buttonsRow.AddView(cancelButton);

            dialogView.AddView(buttonsRow);

            // Return the new view for display.
            return dialogView;
        }

        // Click handler for the login button.
        private void LoginButtonClick(object sender, EventArgs e)
        {
            try
            {
                // Get information for the login.
                var username = _usernameTextbox.Text;
                var password = _passwordTextbox.Text;
                var domain = _domainTextbox.Text;

                // Make sure all required info was entered.
                if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(domain))
                {
                    throw new Exception("Please enter a username, password, and domain.");
                }

                // Create a new OnEnterCredentialsEventArgs object to store the information entered by the user.
                var credentialsEnteredArgs = new OnEnterCredentialsEventArgs(username, password, domain);

                // Raise the OnLoginClicked event so the main activity can handle the event and try to authenticate with the credentials.
                OnLoginClicked(this, credentialsEnteredArgs);

                // Close the dialog.
                this.Dismiss();
            }
            catch (Exception ex)
            {
                // Show the exception message (dialog will stay open so user can try again).
                var alertBuilder = new AlertDialog.Builder(this.Activity);
                alertBuilder.SetTitle("Error");
                alertBuilder.SetMessage(ex.Message);
                alertBuilder.Show();
            }
        }

        // Click handler for the cancel button.
        private void CancelButtonClick(object sender, EventArgs e)
        {
            // Raise an event to indicate that the login was canceled.
            OnLoginCanceled(this, e);

            // Close the dialog.
            this.Dismiss();
        }
    }

    // Custom EventArgs class for containing login info.
    public class OnEnterCredentialsEventArgs : EventArgs
    {
        public string Username { get; set; }
        public string Password { get; set; }
        public string Domain { get; set; }

        // Constructor gets username, password, and domain and stores them in properties.
        public OnEnterCredentialsEventArgs(string username, string password, string domain) : base()
        {
            Username = username;
            Password = password;
            Domain = domain;
        }
    }

}

// A custom item adapter for showing a list of portal items.
public class PortalItemAdapter : BaseAdapter<PortalItem>
{
    // Store a list of the portal items displayed.
    List<PortalItem> _portalItems;

    // The current activity.
    Activity _context;

    // Take the list of portal items and the current activity in the constructor.
    public PortalItemAdapter(Activity context, List<PortalItem> items) : base()
    {
        _context = context;
        _portalItems = items;
    }

    // Get the ID of the item at a given position (just return the position).
    public override long GetItemId(int position)
    {
        return position;
    }

    // Get the portal item at a given position.
    public override PortalItem this[int position]
    {
        get { return _portalItems[position]; }
    }

    // Get the count of portal items in the list.
    public override int Count
    {
        get { return _portalItems.Count; }
    }

    // Construct a view to display a row in the table.
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        // Re-use an existing view, if one is available.
        View view = convertView;

        // Create a new view if necessary.
        if (view == null) { view = _context.LayoutInflater.Inflate(Android.Resource.Layout.SimpleListItem1, null); }

        // Set the text for the row with the portal item title.
        view.FindViewById<TextView>(Android.Resource.Id.Text1).Text = _portalItems[position].Title;

        // Return the view for this row.
        return view;
    }
}
Examples

Xamarin Forms Android

Example Name: SearchPortalMaps

Find webmap portal items by using a search term.

Code example screen shot.

C#
// Copyright 2017 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 System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Esri.ArcGISRuntime;
using Xamarin.Forms;


#if __IOS__
using Xamarin.Forms.Platform.iOS;
using Xamarin.Auth;
using UIKit;
#endif

#if __ANDROID__
using Android.App;
using Application = Xamarin.Forms.Application;
using Xamarin.Auth;
#endif

namespace ArcGISRuntime.Samples.SearchPortalMaps
{
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        "Search a portal for maps",
        "Map",
        "This sample demonstrates searching a portal for web maps and loading them in the map view. You can search ArcGIS Online public web maps using tag values or browse the web maps in your account. OAuth is used to authenticate with ArcGIS Online to access items in your account.",
        "1. When the sample starts, you will be presented with a dialog for entering OAuth settings. If you need to create your own settings, sign in with your developer account and use the [ArcGIS for Developers dashboard](https://developers.arcgis.com/dashboard) to create an Application to store these settings.\n2. Enter values for the following OAuth settings.\n\t1. **Client ID**: a unique alphanumeric string identifier for your application\n\t2. **Redirect URL**: a URL to which a successful OAuth login response will be sent\n3. If you do not enter OAuth settings, you will be able to search public web maps on ArcGIS Online. Browsing the web map items in your ArcGIS Online account will be disabled, however.")]
    public partial class SearchPortalMaps : ContentPage, IOAuthAuthorizeHandler
    {
        // Constants for OAuth-related values ...
        // URL of the server to authenticate with (ArcGIS Online)
        private const string ArcGISOnlineUrl = "https://www.arcgis.com/sharing/rest";

        // Client ID for the app registered with the server (Portal Maps)
        public string _appClientId = "2Gh53JRzkPtOENQq";

        // Redirect URL after a successful authorization (configured for the Portal Maps application)
        private string _oAuthRedirectUrl = "https://developers.arcgis.com";

        public SearchPortalMaps()
        {
            InitializeComponent();

            // Display a default map
            DisplayDefaultMap();

            // Show the default OAuth settings in the entry controls
            ClientIDEntry.Text = _appClientId;
            RedirectUrlEntry.Text = _oAuthRedirectUrl;

            // Change the style of the layer list view for Android and UWP
            if (Device.RuntimePlatform == Device.UWP)
            {
                // Semi-transparent background on Windows with a small margin around the control
                MapsListView.BackgroundColor = Color.FromRgba(255, 255, 255, 0.3);
                MapsListView.Margin = new Thickness(50);
                SearchMapsUI.BackgroundColor = Color.FromRgba(255, 255, 255, 0.3);
                SearchMapsUI.Margin = new Thickness(50);
                OAuthSettingsGrid.BackgroundColor = Color.FromRgba(255, 255, 255, 0.3);
                OAuthSettingsGrid.Margin = new Thickness(50);
            }
        }

        private void DisplayDefaultMap()
        {
            // Create a new Map instance
            Map myMap = new Map(Basemap.CreateStreets());

            // Provide Map to the MapView
            MyMapView.Map = myMap;
        }

        private void OAuthSettingsCancel(object sender, EventArgs e)
        {
            OAuthSettingsGrid.IsVisible = false;
        }

        private void SaveOAuthSettings(object sender, EventArgs e)
        {
            var appClientId = ClientIDEntry.Text.Trim();
            var oAuthRedirectUrl = RedirectUrlEntry.Text.Trim();

            if (!String.IsNullOrWhiteSpace(appClientId) && !String.IsNullOrWhiteSpace(oAuthRedirectUrl))
            {
                _appClientId = appClientId;
                _oAuthRedirectUrl = oAuthRedirectUrl;
            }

            OAuthSettingsGrid.IsVisible = false;

            // Call a function to set up the AuthenticationManager
            UpdateAuthenticationManager();
        }

        private async void SearchPublicMaps(string searchText)
        {
            try
            {
                // Get web map portal items from a keyword search
                IEnumerable<PortalItem> mapItems;

                // Connect to the portal (anonymously)
                ArcGISPortal portal = await ArcGISPortal.CreateAsync(new Uri(ArcGISOnlineUrl));

                // Create a query expression that will get public items of type 'web map' with the keyword(s) in the items tags
                string queryExpression = $"tags:\"{searchText}\" access:public type: (\"web map\" NOT \"web mapping application\")";

                // Create a query parameters object with the expression and a limit of 10 results
                PortalQueryParameters queryParams = new PortalQueryParameters(queryExpression, 10);

                // Search the portal using the query parameters and await the results
                PortalQueryResultSet<PortalItem> findResult = await portal.FindItemsAsync(queryParams);

                // Get the items from the query results
                mapItems = findResult.Results;

                // Hide the search controls
                SearchMapsUI.IsVisible = false;

                // Show the list of web maps
                MapsListView.ItemsSource = mapItems.ToList(); // Explicit ToList() needed to avoid Xamarin.Forms UWP ListView bug.
                MapsListView.IsVisible = true;
            }
            catch (Exception e)
            {
                await Application.Current.MainPage.DisplayAlert("Error", e.ToString(), "OK");
            }
        }

        private void ShowSearchUI(object sender, EventArgs e)
        {
            // Show the map search controls
            SearchMapsUI.IsVisible = true;
        }

        private async void GetMyMaps(object sender, EventArgs e)
        {
            try
            {
                // Call a sub that will force the user to log in to ArcGIS Online (if they haven't already)
                bool loggedIn = await EnsureLoggedInAsync();
                if (!loggedIn) { return; }

                // Connect to the portal (will connect using the provided credentials)
                ArcGISPortal portal = await ArcGISPortal.CreateAsync(new Uri(ArcGISOnlineUrl));

                // Get the user's content (items in the root folder and a collection of sub-folders)
                PortalUserContent myContent = await portal.User.GetContentAsync();

                // Get the web map items in the root folder
                IEnumerable<PortalItem> mapItems = from item in myContent.Items where item.Type == PortalItemType.WebMap select item;

                // Loop through all sub-folders and get web map items, add them to the mapItems collection
                foreach (PortalFolder folder in myContent.Folders)
                {
                    IEnumerable<PortalItem> folderItems = await portal.User.GetContentAsync(folder.FolderId);
                    mapItems = mapItems.Concat(from item in folderItems where item.Type == PortalItemType.WebMap select item);
                }

                // Show the list of web maps
                MapsListView.ItemsSource = mapItems.ToList(); // Explicit ToList() needed to avoid Xamarin.Forms UWP ListView bug.
                MapsListView.IsVisible = true;
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK");
            }
        }

        private void MapItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            // Get the selected web map item in the list box
            PortalItem selectedMap = MapsListView.SelectedItem as PortalItem;
            if (selectedMap == null) { return; }

            // Create a new map, pass the web map portal item to the constructor
            Map webMap = new Map(selectedMap);

            // Handle change in the load status (to report load errors)
            webMap.LoadStatusChanged += WebMapLoadStatusChanged;

            // Show the web map in the map view
            MyMapView.Map = webMap;

            // Hide the list of maps
            MapsListView.IsVisible = false;
        }

        private void WebMapLoadStatusChanged(object sender, Esri.ArcGISRuntime.LoadStatusEventArgs e)
        {
            // Report errors if map failed to load
            if (e.Status == LoadStatus.FailedToLoad)
            {
                Map map = (Map)sender;
                Exception err = map.LoadError;
                if (err != null)
                {
                    Device.BeginInvokeOnMainThread(() => Application.Current.MainPage.DisplayAlert(err.Message, "Map Load Error", "OK"));
                }
            }
        }

        private async Task<bool> EnsureLoggedInAsync()
        {
            bool loggedIn = false;

            try
            {
                // Create a challenge request for portal credentials (OAuth credential request for arcgis.com)
                CredentialRequestInfo challengeRequest = new CredentialRequestInfo
                {

                    // Use the OAuth implicit grant flow
                    GenerateTokenOptions = new GenerateTokenOptions
                    {
                        TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit
                    },

                    // Indicate the url (portal) to authenticate with (ArcGIS Online)
                    ServiceUri = new Uri(ArcGISOnlineUrl)
                };

                // Call GetCredentialAsync on the AuthenticationManager to invoke the challenge handler
                Credential cred = await AuthenticationManager.Current.GetCredentialAsync(challengeRequest, false);
                loggedIn = cred != null;
            }
            catch (OperationCanceledException)
            {
                // Login was canceled
                // .. ignore, user can still search public maps without logging in
            }
            catch (Exception ex)
            {
                // Login failure
                await Application.Current.MainPage.DisplayAlert("Login Error", ex.Message, "OK");
            }

            return loggedIn;
        }

        private void CancelSearchClicked(object sender, EventArgs e)
        {
            // Hide the search controls if the cancel button is clicked
            SearchMapsUI.IsVisible = false;
        }

        private void SearchMapsClicked(object sender, EventArgs e)
        {
            // Search ArcGIS Online maps with the text entered
            SearchPublicMaps(SearchTextEntry.Text);
        }

        #region OAuth
        private void UpdateAuthenticationManager()
        {
            // Define the server information for ArcGIS Online
            ServerInfo portalServerInfo = new ServerInfo
            {
                // ArcGIS Online URI
                ServerUri = new Uri(ArcGISOnlineUrl),
                // Type of token authentication to use
                TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit
            };

            // Define the OAuth information
            OAuthClientInfo oAuthInfo = new OAuthClientInfo
            {
                ClientId = _appClientId,
                RedirectUri = new Uri(_oAuthRedirectUrl)
            };
            portalServerInfo.OAuthClientInfo = oAuthInfo;

            // Get a reference to the (singleton) AuthenticationManager for the app
            AuthenticationManager thisAuthenticationManager = AuthenticationManager.Current;

            // Register the ArcGIS Online server information with the AuthenticationManager
            thisAuthenticationManager.RegisterServer(portalServerInfo);

            // Create a new ChallengeHandler that uses a method in this class to challenge for credentials
            thisAuthenticationManager.ChallengeHandler = new ChallengeHandler(CreateCredentialAsync);

            // Set the OAuthAuthorizeHandler component (this class) for Android or iOS platforms
#if __ANDROID__ || __IOS__
            thisAuthenticationManager.OAuthAuthorizeHandler = this;
#endif
        }

        // ChallengeHandler function that will be called whenever access to a secured resource is attempted
        public async Task<Credential> CreateCredentialAsync(CredentialRequestInfo info)
        {
            Credential credential = null;

            try
            {
                // IOAuthAuthorizeHandler will challenge the user for OAuth credentials
                credential = await AuthenticationManager.Current.GenerateCredentialAsync(info.ServiceUri);
            }
            catch (TaskCanceledException) { return credential; }
            catch (Exception)
            {
                // Exception will be reported in calling function
                throw;
            }

            return credential;
        }

        #region IOAuthAuthorizationHandler implementation
        // Use a TaskCompletionSource to track the completion of the authorization
        private TaskCompletionSource<IDictionary<string, string>> _taskCompletionSource;

        // IOAuthAuthorizeHandler.AuthorizeAsync implementation
        public Task<IDictionary<string, string>> AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
        {
            // If the TaskCompletionSource is not null, authorization may already be in progress and should be cancelled
            if (_taskCompletionSource != null)
            {
                // Try to cancel any existing authentication task
                _taskCompletionSource.TrySetCanceled();
            }

            // Create a task completion source
            _taskCompletionSource = new TaskCompletionSource<IDictionary<string, string>>();
#if __ANDROID__ || __IOS__

#if __ANDROID__
            // Get the current Android Activity
            Activity activity = (Activity)ArcGISRuntime.Droid.MainActivity.Instance;
#endif
            // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in
            Xamarin.Auth.OAuth2Authenticator authenticator = new Xamarin.Auth.OAuth2Authenticator(
                clientId: _appClientId,
                scope: "",
                authorizeUrl: authorizeUri,
                redirectUrl: callbackUri)
            {
                ShowErrors = false
            };

            // Allow the user to cancel the OAuth attempt
            authenticator.AllowCancel = true;

            // Define a handler for the OAuth2Authenticator.Completed event
            authenticator.Completed += (sender, authArgs) =>
            {
                try
                {
#if __IOS__
                    // Dismiss the OAuth UI when complete
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        var viewController = UIApplication.SharedApplication.KeyWindow.RootViewController;
                        viewController.DismissViewController(true, null);
                    });
#endif

                    // Check if the user is authenticated
                    if (authArgs.IsAuthenticated)
                    {
                        // If authorization was successful, get the user's account
                        Xamarin.Auth.Account authenticatedAccount = authArgs.Account;

                        // Set the result (Credential) for the TaskCompletionSource
                        _taskCompletionSource.SetResult(authenticatedAccount.Properties);
                    }
                    else
                    {
                        throw new Exception("Unable to authenticate user.");
                    }
                }
                catch (Exception ex)
                {
                    // If authentication failed, set the exception on the TaskCompletionSource
                    _taskCompletionSource.TrySetException(ex);

                    // Cancel authentication
                    authenticator.OnCancelled();
                }
#if __ANDROID__ 
                finally
                {
                    // Dismiss the OAuth login
                    activity.FinishActivity(99);
                }
#endif
            };

            // If an error was encountered when authenticating, set the exception on the TaskCompletionSource
            authenticator.Error += (sndr, errArgs) =>
            {
                // If the user cancels, the Error event is raised but there is no exception ... best to check first
                if (errArgs.Exception != null)
                {
                    _taskCompletionSource.TrySetException(errArgs.Exception);
                }
                else
                {
                    // Login canceled: dismiss the OAuth login
                    if (_taskCompletionSource != null)
                    {
                        _taskCompletionSource.TrySetCanceled();
#if __ANDROID__ 
                        activity.FinishActivity(99);
#endif
                    }
                }

                // Cancel authentication
                authenticator.OnCancelled();
            };

            // Present the OAuth UI so the user can enter user name and password
#if __ANDROID__
            var intent = authenticator.GetUI(activity);
            activity.StartActivityForResult(intent, 99);
#endif
#if __IOS__
            // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password
            Device.BeginInvokeOnMainThread(() =>
            {
                var viewController = UIApplication.SharedApplication.KeyWindow.RootViewController;
                viewController.PresentViewController(authenticator.GetUI(), true, null);
            });
#endif

#endif 
            // Return completion source task so the caller can await completion
            return _taskCompletionSource.Task;
        }
        #endregion

        #endregion
    }
}
XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"             
             xmlns:esriUI="clr-namespace:Esri.ArcGISRuntime.Xamarin.Forms;assembly=Esri.ArcGISRuntime.Xamarin.Forms"
             x:Class="ArcGISRuntime.Samples.SearchPortalMaps.SearchPortalMaps">
  <Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
      <RowDefinition/>
      <RowDefinition Height="70"/>
    </Grid.RowDefinitions>

        <esriUI:MapView x:Name="MyMapView"
                        Grid.Row="0"/>
        <TableView x:Name="SearchMapsUI"
                   Grid.Row="0"
                   IsVisible="False"
                   Intent="Form">
            <TableRoot>
                <TableSection Title="Search Public Maps">
                    <EntryCell x:Name="SearchTextEntry"
                               Label="Search Text:"
                               Text=""/>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal"
                                     HorizontalOptions="CenterAndExpand">
                            <Button Text="Cancel"
                                    Clicked="CancelSearchClicked"
                                    Margin="20,0"/>
                            <Button Text="Search"
                                    Clicked="SearchMapsClicked"/>
                        </StackLayout>
                    </ViewCell>
                </TableSection>
            </TableRoot>
        </TableView>
        <ListView x:Name="MapsListView" 
                  IsVisible="False"
                  SelectionMode="Single"
                  ItemSelected="MapItemSelected">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.View>
                            <StackLayout>
                                <Label Text="{Binding Title}"/>
                            </StackLayout>
                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Grid x:Name="OAuthSettingsGrid" 
          Grid.Row="0"
          HorizontalOptions="Center" VerticalOptions="Center"
          WidthRequest="300">
            <Grid.RowDefinitions>
                <RowDefinition Height="60"/>
                <RowDefinition Height="40"/>
                <RowDefinition Height="40"/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="100"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Label Grid.Row="0" Grid.ColumnSpan="2" 
             HorizontalOptions="Center" VerticalOptions="Start"
             Text="OAuth Settings"/>
            <Label Grid.Row="1"
             HorizontalOptions="End" VerticalOptions="Center"
             Text="Client ID:"/>
            <Entry x:Name="ClientIDEntry" 
             Grid.Row="1" Grid.Column="1" 
             Placeholder="mYCl1enTiD"
             HorizontalOptions="Start" VerticalOptions="Center"
             WidthRequest="240"/>
            <Label Grid.Row="2"
             HorizontalOptions="End" VerticalOptions="Center"
             Text="Redirect URL:"/>
            <Entry x:Name="RedirectUrlEntry" 
             Grid.Row="2" Grid.Column="1" 
             Placeholder="http://my.redirect/url"
             HorizontalOptions="Start" VerticalOptions="Center"
             WidthRequest="240"/>
            <Button Grid.Row="3" Grid.Column="0"
              HorizontalOptions="End" VerticalOptions="End"
              Text="Cancel"
              Clicked="OAuthSettingsCancel"/>
            <Button Grid.Row="3" Grid.Column="1"
              HorizontalOptions="CenterAndExpand" VerticalOptions="End"
              Text="Use Settings"
              Clicked="SaveOAuthSettings"/>
        </Grid>
        <StackLayout Grid.Row="1"
                     Orientation="Horizontal"
                     HorizontalOptions="Center">
            <Button Text="Search Maps"
              Clicked="ShowSearchUI"/>
            <Button Text="My Maps"
              Clicked="GetMyMaps"/>
        </StackLayout>
  </Grid>
</ContentPage>
See Also
Additional Examples
Hyperlink to ExampleDescription
IntegratedWindowsAuthUse Windows credentials to access services hosted on a portal secured with Integrated Windows Authentication (IWA).
SearchPortalMapsFind webmap portal items by using a search term.