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

            // Connect to the portal (anonymously)
            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
            var queryExpression = string.Format("tags:\"{0}\" access:public type: (\"web map\" NOT \"web mapping application\")", searchText);

            // 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;
            MapsListView.IsVisible   = true;
        }
Example #2
0
        /// <summary>
        /// Gets a collection of web map items from ArcGIS Online
        /// </summary>
        /// <returns></returns>
        private async Task <ObservableCollection <AddInItem> > GetAddinsAsync()
        {
            try
            {
                await QueuedTask.Run(async() =>
                {
                    ArcGISPortal portal = ArcGISPortalManager.Current.GetPortal(new Uri(_arcgisOnline));
                    query = PortalQueryParameters.CreateForItemsOfType(PortalItemType.ArcGISProAddIn);

                    PortalQueryResultSet <PortalItem> results = await ArcGIS.Desktop.Core.ArcGISPortalExtensions.SearchForContentAsync(portal, query);

                    if (results == null)
                    {
                        return;
                    }

                    foreach (var item in results.Results.OfType <PortalItem>())
                    {
                        lock (_lock)
                            AddInsCollection.Add(new AddInItem(item));
                    }
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            return(_addInsCollection);
        }
Example #3
0
        private async Task GetRulePackages()
        {
            try
            {
                await QueuedTask.Run(async() =>
                {
                    ArcGISPortal portal = ArcGISPortalManager.Current.GetPortal(new Uri(_arcgisOnline));
                    var query           = PortalQueryParameters.CreateForItemsOfType(PortalItemType.RulePackage, "title:\"Paris Rule package 2014\" OR title:\"Venice Rule package 2014\" OR title:\"Extrude/Color/Rooftype Rule package 2014\"");

                    //Execute to return a result set
                    PortalQueryResultSet <PortalItem> results = await ArcGISPortalExtensions.SearchForContentAsync(portal, query);

                    foreach (var item in results.Results.OfType <PortalItem>())
                    {
                        lock (_rpkLock)
                        {
                            RulePackageCollection.Add(new RulePackage(item));
                        }
                    }
                });
            }

            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
Example #4
0
        // Handle the SearchTextEntered event from the search input UI.
        // SearchMapsEventArgs contains the search text that was entered.
        private async void SearchTextEntered(string searchText)
        {
            try
            {
                // Connect to the portal (anonymously).
                ArcGISPortal portal = await ArcGISPortal.CreateAsync(new Uri(ServerUrl));

                // 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.
                IEnumerable <PortalItem> mapItems = findResult.Results;

                // Show the map results.
                ShowMapList(mapItems);
            }
            catch (Exception ex)
            {
                // Report search error.
                UIAlertController alert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alert, true, null);
            }
        }
        private async void OnSearchMapsClicked(object sender, OnSearchMapEventArgs e)
        {
            try
            {
                // Get web map portal items from a keyword search
                IEnumerable <PortalItem> mapItems = null;

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

                // Create a query expression that will get public items of type 'web map' with the keyword(s) in the items tags
                string queryExpression = $"tags:\"{e.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;

                // Show the map results
                ShowMapList(mapItems);
            }
            catch (Exception ex)
            {
                new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show();
            }
        }
Example #6
0
        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");
            }
        }
Example #7
0
        /// <summary>
        /// Gets a collection of web map items from ArcGIS Online
        /// </summary>
        /// <returns></returns>
        private async Task <List <WebMapItem> > GetWebMapsAsync()
        {
            var lstWebmapItems = new List <WebMapItem>();

            try
            {
                await QueuedTask.Run(async() =>
                {
                    ArcGISPortal portal         = ArcGISPortalManager.Current.GetPortal(new Uri(_arcgisOnline));
                    PortalQueryParameters query = PortalQueryParameters.CreateForItemsOfType(PortalItemType.WebMap);

                    PortalQueryResultSet <PortalItem> results = await ArcGIS.Desktop.Core.ArcGISPortalExtensions.SearchForContentAsync(portal, query);

                    if (results == null)
                    {
                        return;
                    }

                    foreach (var item in results.Results.OfType <PortalItem>())
                    {
                        lstWebmapItems.Add(new WebMapItem(item));
                    }
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            return(lstWebmapItems);
        }
Example #8
0
        private async Task <string> QueryImpl()
        {
            var portal = ArcGISPortalManager.Current.GetActivePortal();

            string userName = ArcGISPortalManager.Current.GetActivePortal().GetSignOnUsername();

            //Searching for Vector tile packages in the current user's content
            var pqp = PortalQueryParameters.CreateForItemsOfTypeWithOwner(PortalItemType.VectorTilePackage, userName, "tags: UploadVtpkToAgol Demo");

            //Execute to return a result set
            PortalQueryResultSet <PortalItem> results = await ArcGISPortalExtensions.SearchForContentAsync(portal, pqp);


            if (results.Results.Count == 0)
            {
                return($@"Unable to find uploaded item with query: {pqp.Query}");
            }

            // Create an item from the search results
            string itemId      = results.Results[0].ID;
            var    currentItem = ItemFactory.Instance.Create(itemId, ItemFactory.ItemType.PortalItem);

            // Finally add the feature service to the map
            // if we have an item that can be turned into a layer
            // add it to the map
            if (LayerFactory.Instance.CanCreateLayerFrom(currentItem))
            {
                LayerFactory.Instance.CreateLayer(currentItem, MapView.Active.Map);
            }
            return($@"Downloaded this item: {results.Results[0].Name} [Type: {results.Results[0].Type}] to ArcGIS Online and added the item to the Map");
        }
        private async void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            // Get web map portal items in the current user's folder or from a keyword search
            IEnumerable <PortalItem> mapItems = null;
            ArcGISPortal             portal;

            // See if the user wants to search public web map items
            if (SearchPublicMaps.IsChecked == true)
            {
                // Connect to the portal (anonymously)
                portal = await ArcGISPortal.CreateAsync();

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

                // 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;
            }
            else
            {
                // Call a sub that will force the user to log in to ArcGIS Online (if they haven't already)
                var loggedIn = await EnsureLoggedInAsync();

                if (!loggedIn)
                {
                    return;
                }

                // Connect to the portal (will connect using the provided credentials)
                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
                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.Concat(from item in folderItems where item.Type == PortalItemType.WebMap select item);
                }
            }

            // Show the web map portal items in the list box
            MapListBox.ItemsSource = mapItems;
        }
Example #10
0
        // Search the portal for web maps
        private async void SearchPortal(ArcGISPortal currentPortal)
        {
            // Clear existing results and show a status message and progress bar
            MapItemListBox.Items.Clear();
            MessagesTextBlock.Text    = "Searching for web map items on the portal at " + currentPortal.Uri.AbsoluteUri;
            ProgressStatus.Visibility = Visibility.Visible;

            // Use a StringBuilder to store messages
            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
                {
                    // (this shouldn't happen for a secure portal)
                    messageBuilder.AppendLine("Anonymous");
                }

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

                // 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 list items
                foreach (var itm in resultItems)
                {
                    MapItemListBox.Items.Add(itm);
                }
            }
            catch (Exception ex)
            {
                // Report errors searching the portal
                messageBuilder.AppendLine(ex.Message);
            }
            finally
            {
                // Show messages, hide progress bar
                MessagesTextBlock.Text    = messageBuilder.ToString();
                ProgressStatus.Visibility = Visibility.Collapsed;
            }
        }
Example #11
0
        private async void addProtal()
        {
            ArcGISPortal portal = await ArcGISPortal.CreateAsync(new Uri("http://esrichina3d.arcgisonline.cn/arcgis/sharing/rest"));

            PortalQueryParameters para = PortalQueryParameters.CreateForItemsOfType(PortalItemType.WebScene);

            para.Limit = 20;
            PortalQueryResultSet <PortalItem> items = await portal.FindItemsAsync(para);

            int sum = 0;

            productList = new List <Product>();
            try
            {
                OpenFileActivity.item = items.Results.First();
                foreach (PortalItem item in items.Results)
                {
                    System.IO.Stream st = await item.GetDataAsync();

                    System.IO.StreamReader reader = new StreamReader(st);
                    st.Position = 0;
                    string json = reader.ReadToEnd();
                    reader.Close();
                    st.Close();
                    productList.Add(new Product(item.ThumbnailUri.ToString(), item.Title, json));
                }
            }
            catch
            { }

            RecyclerView recyclerView = (RecyclerView)FindViewById(Resource.Id.recyclerView);

            //设置layoutManager 布局模式
            recyclerView.SetLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.Vertical));

            //  recyclerView.SetLayoutManager(new LinearLayoutManager(this));
            //设置adapter

            Context        context = this.BaseContext;
            MasonryAdapter WebSceneItemsAdapter = new MasonryAdapter(productList, context);

            WebSceneItemsAdapter.ItemClick += WebSceneItemsAdapter_ItemClick;
            recyclerView.SetAdapter(WebSceneItemsAdapter);

            //设置item之间的间隔
            SpacesItemDecoration decoration = new SpacesItemDecoration(16);

            recyclerView.AddItemDecoration(decoration);
        }
Example #12
0
        private async Task <string> UploadImpl()
        {
            // Create EsriHttpClient object
            var httpClient = new EsriHttpClient();

            // Upload vtpk file to the currently active portal
            var itemToUpload = ItemFactory.Instance.Create(FilePath);
            var tags         = new string[] { "ArcGIS Pro", "SDK", "UploadVtpkToAgol Demo" };
            var portalUrl    = ArcGISPortalManager.Current.GetActivePortal().PortalUri.ToString();

            var uploadDefn = new UploadDefinition(portalUrl, itemToUpload, tags);

            var result = httpClient.Upload(uploadDefn);

            if (result.Item1 == false)
            {
                return($@"Unable to upload this item: {FilePath} to ArcGIS Online");
            }

            // Once uploaded make another REST call to search for the uploaded data
            var    portal   = ArcGISPortalManager.Current.GetActivePortal();
            string userName = ArcGISPortalManager.Current.GetActivePortal().GetSignOnUsername();

            //Searching for Vector tile packages in the current user's content
            var pqp = PortalQueryParameters.CreateForItemsOfTypeWithOwner(PortalItemType.VectorTilePackage, userName, "tags: UploadVtpkToAgol Demo");

            //Execute to return a result set
            PortalQueryResultSet <PortalItem> results = await ArcGISPortalExtensions.SearchForContentAsync(portal, pqp);

            if (results.Results.Count == 0)
            {
                return($@"Unable to find uploaded item with query: {pqp.Query}");
            }

            // Create an item from the search results
            string itemId      = results.Results[0].ID;
            var    currentItem = ItemFactory.Instance.Create(itemId, ItemFactory.ItemType.PortalItem);
            var    lyrParams   = new LayerCreationParams(currentItem);

            // Finally add the feature service to the map
            // if we have an item that can be turned into a layer
            // add it to the map
            if (LayerFactory.Instance.CanCreateLayerFrom(currentItem))
            {
                LayerFactory.Instance.CreateLayer <FeatureLayer>(lyrParams, MapView.Active.Map);
            }
            return($@"Uploaded this item: {results.Results[0].Name} [Type: {results.Results[0].Type}] to ArcGIS Online and added the item to the Map");
        }
Example #13
0
        public static async void PortalMethods6()
        {
            Uri portalUri = new Uri("");

            #region Portal: Execute a portal search

            var portal     = ArcGISPortalManager.Current.GetPortal(portalUri);
            var owner      = portal.GetSignOnUsername();
            var portalInfo = await portal.GetPortalInfoAsync();

            //1. Get all web maps
            var query1 = PortalQueryParameters.CreateForItemsOfType(PortalItemType.WebMap);

            //2. Get all web maps and map services - include user, organization
            // and "usa" in the title
            var query2 = PortalQueryParameters.CreateForItemsOfTypes(new List <PortalItemType>()
            {
                PortalItemType.WebMap, PortalItemType.MapService
            }, owner, "", "title:usa");
            query2.OrganizationId = portalInfo.OrganizationId;

            //retrieve in batches of up to a 100 each time
            query2.Limit = 100;

            //Loop until done
            var portalItems = new List <PortalItem>();
            while (query2 != null)
            {
                //run the search
                PortalQueryResultSet <PortalItem> results = await portal.SearchForContentAsync(query2);

                portalItems.AddRange(results.Results);
                query2 = results.NextQueryParameters;
            }

            //process results
            foreach (var pi in portalItems)
            {
                //Do something with the portal items
            }

            #endregion
        }
Example #14
0
        private PortalQueryParameters MakePortalQuery()
        {
            StringBuilder query = new StringBuilder();

            if (!this.GroupID.IsEmpty())
            {
                query.Append(String.Format("group:{0} ", this.GroupID));
            }
            query.Append((string)(this.Content == PortalItemType.Layer ? DefaultEsriLayerContentTypes : DefaultEsriWebMapContentTypes));
            if (!this.Keywords.IsEmpty())
            {
                //tokenize
                string[] _keys = this.Keywords.Split(new char[] { ' ', ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries);
                query.Append(" AND (");
                string sep = "";
                foreach (string key in _keys)
                {
                    query.Append(String.Format("{0}\"{1}\"", sep, key));
                    sep = " OR ";
                }
                query.Append(")");
            }
            if (!this.OnlineUri.Tags.IsEmpty())
            {
                query.Append(String.Format(" AND (tags:{0})", this.OnlineUri.Tags));
            }
            PortalQueryParameters pq = new PortalQueryParameters(query.ToString());

            pq.StartIndex = Start;


            if (Start > 0)
            {
                query.Append(String.Format("&start={0}", this.Start));
            }

            pq.Limit = DefaultNumResultsPerQuery;
            query.Append(String.Format("&num={0}", pq.Limit));

            return(pq);
        }
        /// <summary>
        /// Searches the active portal for the item that has been uploaded.
        /// </summary>
        /// <param name="portalUrl"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        private async Task <Tuple <bool, PortalItem> > SearchPortalForItemsAsync(string portalUrl, Item item)
        {
            var portal = ArcGISPortalManager.Current.GetPortal(new Uri(portalUrl));
            //Get the PortalItemType of the item
            var portalItemType = GetProtalItemTypeFromItem(item);
            //Get the item name without the extension
            var portalItemName = System.IO.Path.GetFileNameWithoutExtension(item.Name);
            //Create the Query and the params
            var pqp = PortalQueryParameters.CreateForItemsOfType(portalItemType, $@"""{portalItemName}"" tags:""{ItemTags}""");
            //Search active portal
            PortalQueryResultSet <PortalItem> results = await ArcGISPortalExtensions.SearchForContentAsync(portal, pqp);

            //Iterate through the returned items for THE item.
            var myPortalItem = results.Results?.OfType <PortalItem>().FirstOrDefault();

            if (myPortalItem == null)
            {
                return(null);
            }
            return(new Tuple <bool, PortalItem>(true, myPortalItem));
        }
        // Handle the SearchTextEntered event from the search input UI
        // SearchMapsEventArgs contains the search text that was entered
        private async void SearchTextEntered(object sender, SearchMapsEventArgs e)
        {
            try
            {
                // Get web map portal items from a keyword search
                IEnumerable <PortalItem> mapItems = null;
                ArcGISPortal             portal;

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

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

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

                // Show the map results
                ShowMapList(mapItems);
            }
            catch (Exception ex)
            {
                // Report search error
                UIAlertController alert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alert, true, null);
            }
            finally
            {
                // Get rid of the search input controls
                _searchMapsUI.Hide();
                _searchMapsUI = null;
            }
        }
Example #17
0
        private async void SearchMapsClicked(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            // Get web map portal items in the current user's folder or from a keyword search
            IEnumerable <PortalItem> mapItems = null;
            ArcGISPortal             portal;

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

            // Create a query expression that will get public items of type 'web map' with the keyword(s) in the items tags
            var queryExpression = string.Format("tags:\"{0}\" access:public type: (\"web map\" NOT \"web mapping application\")", SearchText.Text);
            // 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;

            // Show the search result items in the list
            SearchMapsList.ItemsSource = mapItems;
        }
        private async void OnSearchMapsClicked(object sender, OnSearchMapEventArgs e)
        {
            // Get web map portal items from a keyword search
            IEnumerable <PortalItem> mapItems = null;
            ArcGISPortal             portal;

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

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

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

            // Show the map results
            ShowMapList(mapItems);
        }
Example #19
0
        /// <summary>
        /// Async task to load maps from the portal instance and put them in groups
        /// </summary>
        /// <param name="portal">Portal instance</param>
        /// <returns></returns>
        private async Task LoadMaps(ArcGISPortal portal)
        {
            StatusMessage = "Loading maps...";

            var task1 = portal.GetBasemapsAsync();
            var items = await task1;

            Basemaps = items.Select(b => b.Item).OfType <PortalItem>();
            var groups = new ObservableCollection <MapGroup>();

            Groups = groups;
            groups.Add(new MapGroup()
            {
                Name = "Base maps", Items = Basemaps
            });
            IsLoadingBasemaps = false;
            StatusMessage     = string.Format("Connected to {0} ({1})", portal.PortalInfo.PortalName, portal.PortalInfo.PortalName);
            foreach (var item in await portal.GetFeaturedGroupsAsync())
            {
                var query = PortalQueryParameters.CreateForItemsOfTypeInGroup(PortalItemType.WebMap, item.GroupId);
                query.Limit = 20;
                var result = await portal.FindItemsAsync(query);

                if (result.TotalResultsCount > 0)
                {
                    groups.Add(new MapGroup()
                    {
                        Name = item.Title, Items = result.Results
                    });
                    if (Featured == null)
                    {
                        Featured = result.Results;
                    }
                }
            }
        }
Example #20
0
        public async Task <BA_ReturnCode> GetPortalFile(string portalOrganization, string itemId, string downLoadPath)
        {
            try
            {
                var          enumPortal = ArcGISPortalManager.Current.GetPortals();
                ArcGISPortal myPortal   = null;
                foreach (var oPortal in enumPortal)
                {
                    var info = await oPortal.GetPortalInfoAsync();

                    if (info.OrganizationName.Equals(portalOrganization))
                    {
                        myPortal = oPortal;
                    }
                }
                if (myPortal == null)
                {
                    Module1.Current.ModuleLogManager.LogError(nameof(GetPortalFile),
                                                              "The NRCS Portal is missing from the ArcGIS Pro 'Portals' tab. The requested file cannot be downloaded! ArcGIS Pro will " +
                                                              "use a previous version of the file if it exists");
                    return(BA_ReturnCode.UnknownError);
                }
                if (!myPortal.IsSignedOn())
                {
                    var result = await myPortal.SignInAsync();

                    if (result.success == false)
                    {
                        Module1.Current.ModuleLogManager.LogError(nameof(GetPortalFile),
                                                                  "Unable to signIn to the NRCS Portal. Can you connect to the portal in the ArcGIS Pro 'Portals' tab? The requested file cannot be downloaded! " +
                                                                  "ArcGIS Pro will use a previous version of the file if it exists");
                        return(BA_ReturnCode.UnknownError);
                    }
                }

                //assume we query for some content
                var query   = PortalQueryParameters.CreateForItemsWithId(itemId);
                var results = await myPortal.SearchForContentAsync(query);

                var portalItem = results.Results.First();   //first item

                bool success = false;
                if (portalItem != null)
                {
                    //rename the original, if it exists so that we get the most current copy
                    if (File.Exists(downLoadPath))
                    {
                        string strDirectory = Path.GetDirectoryName(downLoadPath);
                        string strFile      = Path.GetFileNameWithoutExtension(downLoadPath) + "_1" + Path.GetExtension(downLoadPath);
                        File.Copy(downLoadPath, strDirectory + "\\" + strFile, true);
                        File.Delete(downLoadPath);
                        Module1.Current.ModuleLogManager.LogDebug(nameof(GetPortalFile),
                                                                  "Renamed " + downLoadPath + " so a new copy could be downloaded");
                    }
                    //download the item
                    success = await portalItem.GetItemDataAsync(downLoadPath);
                }
                if (success == true)
                {
                    Module1.Current.ModuleLogManager.LogDebug(nameof(GetPortalFile),
                                                              "The requested file cannot was successfully downloaded from the Portal");
                    return(BA_ReturnCode.Success);
                }
                else
                {
                    Module1.Current.ModuleLogManager.LogError(nameof(GetPortalFile),
                                                              "The requested file cannot be downloaded from the Portal! ArcGIS Pro will " +
                                                              "use a previous version of the file if it exists");
                    return(BA_ReturnCode.UnknownError);
                }
            }
            catch (Exception e)
            {
                Module1.Current.ModuleLogManager.LogError(nameof(GetPortalFile),
                                                          "Exception: " + e.Message);
                return(BA_ReturnCode.UnknownError);
            }
        }