private async Task <string> UploadImpl()
        {
            // Create EsriHttpClient object
            var httpClient = new EsriHttpClient();

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

            var result = httpClient.Upload(
                portalUrl, itemToUpload, string.Empty, tags);

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

            string userName = ArcGISPortalManager.Current.GetActivePortal().GetSignOnUsername();
            string query    = $@"q=owner:{userName} tags:""UploadVtpkToAgol Demo"" ";

            // Once uploaded make another REST call to search for the uploaded data
            var searchUrl = new UriBuilder(portalUrl)
            {
                Path  = "sharing/rest/search",
                Query = $@"{query}&f=json"
            };

            var searchResults = httpClient.Get(searchUrl.Uri.ToString());

            dynamic resultItems = JObject.Parse(await searchResults.Content.ReadAsStringAsync());

            long numberOfTotalItems = resultItems.total.Value;

            if (numberOfTotalItems == 0)
            {
                return($@"Unable to find uploaded item with query: {query}");
            }

            var resultItemList = new List <dynamic>();

            resultItemList.AddRange(resultItems.results);
            //get the first result
            dynamic item = resultItemList[0];

            // Create an item from the search results

            string itemId      = item.id;
            var    currentItem = ItemFactory.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.CanCreateLayerFrom(currentItem))
            {
                LayerFactory.CreateLayer(currentItem, MapView.Active.Map);
            }
            return($@"Uploaded this item: {FilePath} to ArcGIS Online and added the item to the Map");
        }
Exemplo n.º 2
0
        protected async override void OnClick()
        {
            //TODO - Get the URL of the Active Portal
            //HINT: Use PortalManager
            string portalUrl = PortalManager.GetActivePortal().ToString();

            UriBuilder searchURL = new UriBuilder(portalUrl);

            searchURL.Path = "sharing/rest/search";
            string layers = "(type:\"Map Service\" OR type:\"Image Service\" OR type:\"Feature Service\" OR type:\"WMS\" OR type:\"KML\")";

            //any public layer content
            searchURL.Query = string.Format("q={0}&f=json", layers);

            EsriHttpClient httpClient = new EsriHttpClient();

            var     searchResponse = httpClient.Get(searchURL.Uri.ToString());
            dynamic resultItems    = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());

            //Use EsriHttpClient to call Online - Use the GET method

            //TODO get the JSON result from the searchResponse
            //HINT - examine methoods of searchResponse.Content

            //TODO Parse the returned JSON - here you will use the Newtonsoft library's JObject
            //examine JObject.Parse. Use a dynamic type to get the results of the Parse
            long numberOfTotalItems = resultItems.total.Value;

            if (numberOfTotalItems == 0)
            {
                return;
            }

            List <dynamic> resultItemList = new List <dynamic>();

            resultItemList.AddRange(resultItems.results);
            //TODO add the ".results" of the returned JSON.
            //eg: resultItemList.AddRange(resultItems.results);

            //get the first result from resultItemList (or an index of your choice)
            //dynamic item = ....
            dynamic item = resultItemList[0];


            //TODO create an Item via the ItemFactory. Use the ItemFactory.ItemType.PortalItem item type.
            string itemID      = item.id;
            Item   currentItem = ItemFactory.Create(itemID, ItemFactory.ItemType.PortalItem);

            await QueuedTask.Run(() => {
                // if we have an item that can be turned into a layer
                // add it to the map
                //TODO use the LayerFactory.CreateLayer and the MapView.Active.Map
                if (LayerFactory.CanCreateLayerFrom(currentItem))
                {
                    LayerFactory.CreateLayer(currentItem, MapView.Active.Map);
                }
            });
        }
        internal void AddLayerToMap(string url)
        {
            //clear previous flag, if any
            _addFailed = false;
            OnPropertyChanged("AddStatus");

            string id = url;
            //get the query result
            var result = _results.FirstOrDefault(ri => ri.Id == id);

            if (result == null)
            {
                throw new ApplicationException(string.Format("Debug: bad id {0}", id));
            }
            if (result.Item == null)
            {
                result.Item = ItemFactory.Create(id, ItemFactory.ItemType.PortalItem);
            }
            // Syntax can get complicated here
            // Question - do you need to await the QueuedTask.Run? If so, you need a Func<Task>
            // and not an Action.
            //http://stackoverflow.com/questions/20395826/explicitly-use-a-functask-for-asynchronous-lambda-function-when-action-overloa
            //
            //As it currently stands, this QueuedTask.Run will return to the caller on the first await
            QueuedTask.Run(action: async() => {
                if (LayerFactory.CanCreateLayerFrom(result.Item))
                {
                    LayerFactory.CreateLayer(result.Item, MapView.Active.Map);
                }
                else if (MapFactory.CanCreateMapFrom(result.Item))
                {
                    Map newMap          = await MapFactory.CreateMapAsync(result.Item);
                    IMapPane newMapPane = await ProApp.Panes.CreateMapPaneAsync(newMap);
                }
                else
                {
                    _addFailed = true;//cannot be added
                    FrameworkApplication.Current.Dispatcher.Invoke(() => OnPropertyChanged("AddStatus"));
                }
            });
        }
        protected override async void OnClick()
        {
            UriBuilder searchURL = new UriBuilder(PortalManager.GetActivePortal());

            searchURL.Path = "sharing/rest/search";
            string layers = "(type:\"Map Service\" OR type:\"Image Service\" OR type:\"Feature Service\" OR type:\"WMS\" OR type:\"KML\")";

            //any public layer content
            searchURL.Query = string.Format("q={0}&f=json", layers);

            EsriHttpClient httpClient = new EsriHttpClient();

            var     searchResponse = httpClient.Get(searchURL.Uri.ToString());
            dynamic resultItems    = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());

            long numberOfTotalItems = resultItems.total.Value;

            if (numberOfTotalItems == 0)
            {
                return;
            }

            List <dynamic> resultItemList = new List <dynamic>();

            resultItemList.AddRange(resultItems.results);
            //get the first result
            dynamic item = resultItemList[0];

            string itemID      = item.id;
            Item   currentItem = ItemFactory.Create(itemID, ItemFactory.ItemType.PortalItem);

            await QueuedTask.Run(() => {
                // if we have an item that can be turned into a layer
                // add it to the map
                if (LayerFactory.CanCreateLayerFrom(currentItem))
                {
                    LayerFactory.CreateLayer(currentItem, MapView.Active.Map);
                }
            });
        }
Exemplo n.º 5
0
        /// <summary>
        /// Query the portal and load all the content items to a list.
        /// </summary>
        private async void LoadMyContent()
        {
            try
            {
                UriBuilder searchURL = new UriBuilder(ArcGISPortalManager.Current.GetActivePortal().PortalUri);
                searchURL.Path  = "sharing/rest/search";
                searchURL.Query = string.Format("q=owner:\"{0}\"&num=100&f=json", ArcGISPortalManager.Current.GetActivePortal().GetSignOnUsername());

                EsriHttpClient httpClient = new EsriHttpClient();

                var searchResponse = httpClient.Get(searchURL.Uri.ToString());

                dynamic resultItems = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());

                if (resultItems.total.Value == 0)
                {
                    return;
                }

                List <dynamic> resultItemList = new List <dynamic>();
                resultItemList.AddRange(resultItems.results);

                foreach (var item in resultItemList)
                {
                    string itemID = item.id;

                    Item currentItem = ItemFactory.Create(itemID, ItemFactory.ItemType.PortalItem);

                    if (LayerFactory.CanCreateLayerFrom(currentItem))
                    {
                        Items.Add(currentItem);
                    }
                }
            }
            catch (Exception)
            {
                // handle exception
            }
        }
        private Task AddToMap()
        {
            return(QueuedTask.Run(() =>
            {
                try
                {
                    // first we create an 'Item' using itemfactory
                    Item currentItem = ItemFactory.Create(FilePath);

                    // 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.CanCreateLayerFrom(currentItem))
                    {
                        LayerFactory.CreateLayer(currentItem, MapView.Active.Map);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error while adding vector tile to map");
                }
            }));
        }
        protected override void OnClick()
        {
            OpenItemDialog openDlg = new OpenItemDialog();

            openDlg.Title           = "Add Layers";
            openDlg.InitialLocation = Project.Current.HomeFolderPath;
            openDlg.Filter          = ItemFilters.default_addToMap;
            openDlg.MultiSelect     = true;

            if (openDlg.ShowDialog() ?? false)
            {
                QueuedTask.Run(() =>
                {
                    IEnumerable <ArcGIS.Desktop.Core.Item> selectedItems = openDlg.Items;
                    foreach (var item in selectedItems)
                    {
                        if (LayerFactory.CanCreateLayerFrom(item))
                        {
                            LayerFactory.CreateLayer(item, MapView.Active.Map);
                        }
                    }
                });
            }
        }
        private async Task <string> QueryImpl()
        {
            // Create EsriHttpClient object
            var httpClient = new EsriHttpClient();

            // Make a self call to extract the signed on username for now.
            // Coming soon - An API which will give you the the signed on username for a portal
            var selfUrl = new UriBuilder(PortalManager.GetActivePortal())
            {
                Path  = "sharing/rest/portals/self",
                Query = "f=json"
            };

            EsriHttpResponseMessage response = httpClient.Get(selfUrl.Uri.ToString());

            dynamic portalSelf = JObject.Parse(await response.Content.ReadAsStringAsync());

            // if the response doesn't contain the user information then it is essentially
            // an anonymous request against the portal
            if (portalSelf.user == null)
            {
                return("Unable to get current user from portal");
            }

            string userName = portalSelf.user.username;
            string query    = $@"q=owner:{userName} tags:""UploadVtpkToAgol Demo"" type:""Vector Tile Service"" ";

            // Once uploaded make another REST call to search for the uploaded data
            var searchUrl = new UriBuilder(PortalManager.GetActivePortal())
            {
                Path  = "sharing/rest/search",
                Query = $@"{query}&f=json"
            };

            var searchResults = httpClient.Get(searchUrl.Uri.ToString());

            dynamic resultItems = JObject.Parse(await searchResults.Content.ReadAsStringAsync());

            long numberOfTotalItems = resultItems.total.Value;

            if (numberOfTotalItems == 0)
            {
                return($@"Unable to find uploaded item with query: {query}");
            }

            var resultItemList = new List <dynamic>();

            resultItemList.AddRange(resultItems.results);
            //get the first result
            dynamic item = resultItemList[0];

            // Create an item from the search results

            string itemId      = item.id;
            var    currentItem = ItemFactory.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.CanCreateLayerFrom(currentItem))
            {
                LayerFactory.CreateLayer(currentItem, MapView.Active.Map);
            }
            return($@"Downloaded this item: {item.name} [Type: {item.type}] to ArcGIS Online and added the item to the Map");
        }
        protected internal async virtual void ExecuteItemAction(string url)
        {
            _result = _results.FirstOrDefault(ri => ri.Id == url);
            if (_result == null)
            {
                return;
            }

            //Either we open a project and then create the item or
            //we download the item and then create a project from it.
            //MapPackage is a special case. We download it, create
            //a project and then add the map package to it.
            switch (_result.OnlineItemType)
            {
            case OnlineItemType.WebMap:
            {
                await Project.CreateAsync(new CreateProjectSettings()
                    {
                        Name = System.IO.Path.GetFileNameWithoutExtension(_result.Name)
                    });

                var currentItem = ItemFactory.Create(_result.Id, ItemFactory.ItemType.PortalItem);
                if (MapFactory.CanCreateMapFrom(currentItem))
                {
                    var newMap = await MapFactory.CreateMapAsync(currentItem);

                    await FrameworkApplication.Panes.CreateMapPaneAsync(newMap);
                }
            }
            break;

            case OnlineItemType.Layer:
            {
                var ps = new CreateProjectSettings()
                {
                    Name         = System.IO.Path.GetFileNameWithoutExtension(_result.Name),
                    LocationPath = ConfigWithStartWizardModule.DefaultFolder(),
                    TemplatePath = ConfigWithStartWizardModule.GetDefaultTemplates()[0]         //Scene
                };
                _eventToken = ArcGIS.Desktop.Mapping.Events.MapViewInitializedEvent.Subscribe((args) =>
                    {
                        Item currentItem = ItemFactory.Create(_result.Id, ItemFactory.ItemType.PortalItem);
                        if (LayerFactory.CanCreateLayerFrom(currentItem))
                        {
                            QueuedTask.Run(() => LayerFactory.CreateLayer(currentItem, args.MapView.Map));
                        }
                        ArcGIS.Desktop.Mapping.Events.MapViewInitializedEvent.Unsubscribe(_eventToken);
                        _eventToken = null;
                    });
                try
                {
                    await Project.CreateAsync(ps);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                }
            }
            break;

            default:
                var query = new OnlineQuery(_activePortalUri);
                query.ConfigureData("", _result.Id, _result.Name);

                await new SubmitQuery().DownloadFileAsync(query);

                //Project package
                if (_result.OnlineItemType == OnlineItemType.ProjectPackage)
                {
                    Project.OpenAsync(query.DownloadFileName);
                }
                //Project Template
                else if (_result.OnlineItemType == OnlineItemType.Template)
                {
                    var ps = new CreateProjectSettings()
                    {
                        Name         = System.IO.Path.GetFileNameWithoutExtension(_result.Name),
                        LocationPath = ConfigWithStartWizardModule.DefaultFolder(),
                        TemplatePath = query.DownloadFileName
                    };
                    try
                    {
                        await Project.CreateAsync(ps);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
                    }
                }
                //Map Package
                else if (_result.OnlineItemType == OnlineItemType.MapPackage)
                {
                    await Project.CreateAsync(new CreateProjectSettings()
                    {
                        Name = System.IO.Path.GetFileNameWithoutExtension(_result.Name)
                    });

                    try
                    {
                        var mapPackage = ItemFactory.Create(query.DownloadFileName);
                        await Project.Current.AddAsync(mapPackage);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
                    }
                }
                break;
            }
        }