Beispiel #1
0
        public static async Task EsriHttpClientMethods2()
        {
            #region EsriHttpClient: Get a Web Map for the Current User and Add it to Pro

            UriBuilder searchURL = new UriBuilder(ArcGISPortalManager.Current.GetActivePortal().PortalUri)
            {
                Path  = "sharing/rest/portals/self",
                Query = "f=json"
            };
            EsriHttpClient          httpClient = new EsriHttpClient();
            EsriHttpResponseMessage response   = httpClient.Get(searchURL.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;
            }
            string userName = portalSelf.user.username;

            searchURL.Path = "sharing/rest/search";
            string webMaps = "(type:\"Web Map\" OR type:\"Explorer Map\" OR type:\"Web Mapping Application\" OR type:\"Online Map\")";
            searchURL.Query = string.Format("q=owner:{0} {1}&f=json", userName, webMaps);

            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.Instance.Create(itemID, ItemFactory.ItemType.PortalItem);

            if (MapFactory.Instance.CanCreateMapFrom(currentItem))
            {
                Map newMap = MapFactory.Instance.CreateMapFromItem(currentItem);
                await ProApp.Panes.CreateMapPaneAsync(newMap);
            }

            #endregion
        }
        public Tuple <bool, SDCItem> SearchPortalForItem(string itemName, string itemType)
        {
            string queryURL = String.Format(@"{0}/sharing/rest/search?q={1} AND type: {2}&f=json", PortalManager.GetActivePortal().ToString(), itemName, itemType);

            EsriHttpClient myClient = new EsriHttpClient();

            var response = myClient.Get(queryURL);

            if (response == null)
            {
                return(new Tuple <bool, SDCItem>(false, null));
            }

            string outStr = response.Content.ReadAsStringAsync().Result;

            SearchResult searchResults = JsonConvert.DeserializeObject <SearchResult>(outStr);

            if (searchResults.results.Count() > 0)
            {
                for (int i = 0; i < searchResults.results.Count; i++)
                {
                    if ((searchResults.results[i].name == itemName) && (searchResults.results[i].type.Contains(itemType)))
                    {
                        return(new Tuple <bool, SDCItem>(true, searchResults.results[i]));
                    }
                }
            }
            return(null);
        }
Beispiel #3
0
        protected override void OnClick()
        {
            // Create an HttpClient Object
            EsriHttpClient httpClient = new EsriHttpClient();

            // Web map json rest endpoint
            string webMapUrl = @"https://ess.maps.arcgis.com/sharing/rest/content/items/79d429008d7946fb98463d117aeaa4aa/data";

            try
            {
                // Get request to the web map rest endpoint
                EsriHttpResponseMessage response = httpClient.Get(webMapUrl.ToString());

                // Read the content of response object.
                string outStr = response.Content.ReadAsStringAsync().Result;

                WebMapLayerInfo webMap = null;
                // Encode response string to Unicode
                using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(outStr)))
                {
                    //De-serialize the response in JSON into a usable object.
                    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(WebMapLayerInfo));

                    // Read object and cast to WebMapLayerInfo
                    webMap = deserializer.ReadObject(ms) as WebMapLayerInfo;

                    MessageBox.Show("Number Operational Layers: " + webMap.operationalLayers.Count().ToString(), "Info", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// Gets the item title/name based on its item ID
        /// </summary>
        /// <param name="baseURI"></param>
        /// <param name="username"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        Tuple <bool, string> getServiceName(string baseURI, string username, string itemId)
        {
            EsriHttpClient myClient = new EsriHttpClient();

            #region REST call to get service name
            string requestUrl = baseURI + @"/sharing/rest/content/users/" + username + @"/items/" + itemId + "?f=json";
            var    response   = myClient.Get(requestUrl);
            if (response == null)
            {
                return(new Tuple <bool, String>(false, "HTTP response is null"));
            }

            string outStr = response.Content.ReadAsStringAsync().Result;

            //Deserialize the response in JSON into a usable object.
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            OnlineItem           obj        = (OnlineItem)serializer.Deserialize(outStr, typeof(OnlineItem));
            if (obj == null || obj.item.title == null)
            {
                return(new Tuple <bool, String>(false, "Failed item call"));
            }
            return(new Tuple <bool, String>(true, obj.item.title));

            #endregion
        }
        /// <summary>
        /// Gets the item title/name based on its item ID
        /// </summary>
        /// <param name="baseURI"></param>
        /// <param name="username"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        Tuple <bool, string> GetServiceName(string baseURI, string username, string itemId)
        {
            EsriHttpClient myClient = new EsriHttpClient();

            #region REST call to get service name
            string requestUrl = baseURI + @"/sharing/rest/content/users/" + username + @"/items/" + itemId + "?f=json";
            var    response   = myClient.Get(requestUrl);
            if (response == null)
            {
                return(new Tuple <bool, String>(false, "HTTP response is null"));
            }
            string outStr = response.Content.ReadAsStringAsync().Result;

            //De-serialize the response in JSON into a usable object.
            JavaScriptSerializer        serializer = new JavaScriptSerializer();
            SharingContracts.OnlineItem obj        =
                (SharingContracts.OnlineItem)serializer.Deserialize(outStr, typeof(SharingContracts.OnlineItem));
            if (obj?.item?.title == null)
            {
                SharingContracts.Error err = (SharingContracts.Error)serializer.Deserialize(outStr, typeof(SharingContracts.Error));
                var msg = string.IsNullOrEmpty(err.message) ? $@"error code: {err.code}" : err.message;
                return(new Tuple <bool, String>(false, $@"Failed item call: {msg}"));
            }
            return(new Tuple <bool, String>(true, obj.item.title));

            #endregion
        }
        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 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.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($@"Uploaded this item: {FilePath} to ArcGIS Online and added the item to the Map");
        }
Beispiel #7
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);
                }
            });
        }
        /// <summary>
        /// Execute the query command
        /// </summary>
        private void CmdDoQuery()
        {
            try
            {
                var httpEsri = new EsriHttpClient()
                {
                    BaseAddress = PortalManager.GetActivePortal()
                };
                // value has the following format: url with {};Redlands,...,...;Search Query,...,...
                // where Redlands ... are values and search query are keys
                var parts  = AgolQuery.Value.Split(";".ToCharArray());
                var getUrl = parts[0];

                // get parameters
                if (CallParams.Count > 0)
                {
                    var lstParams = new List <object>() as IList <object>;
                    foreach (var kv in CallParams)
                    {
                        lstParams.Add(kv.Param);
                    }
                    getUrl = string.Format(parts[0], lstParams.ToArray());
                }
                System.Diagnostics.Debug.WriteLine(getUrl);
                var httpResponse = httpEsri.Get(getUrl);
                if (httpResponse.StatusCode == HttpStatusCode.OK && httpResponse.Content != null)
                {
                    var content = httpResponse.Content.ReadAsStringAsync().Result;
                    QueryResult  = string.Format(@"{0}{1}", getUrl, System.Environment.NewLine);
                    QueryResult += string.Format(@"IsSuccessStatusCode: {0}{1}", httpResponse.IsSuccessStatusCode, System.Environment.NewLine);
                    QueryResult += string.Format(@"StatusCode: {0}{1}", httpResponse.StatusCode, System.Environment.NewLine);
                    QueryResult += content;
                    if (AgolQuery.Key == ArcGISOnlineQueries.AGSQueryType.GetSelf)
                    {
                        _AgolUser = AgolUser.LoadAgolUser(content);
                    }
                    else if (AgolQuery.Key == ArcGISOnlineQueries.AGSQueryType.GetSearch)
                    {
                        _AgolSearchResult = AgolSearchResult.LoadAgolSearchResult(content);
                    }
                    else if (AgolQuery.Key == ArcGISOnlineQueries.AGSQueryType.GetUserContent)
                    {
                        _AgolUserContent   = AgolUserContent.LoadAgolUserContent(content);
                        _AgolFolderContent = null;
                    }
                    else if (AgolQuery.Key == ArcGISOnlineQueries.AGSQueryType.GetUserContentForFolder)
                    {
                        _AgolFolderContent = AgolFolderContent.LoadAgolFolderContent(content);
                    }
                    System.Diagnostics.Debug.WriteLine(QueryResult);
                }
            }
            catch (Exception ex)
            {
                QueryResult = ex.ToString();
            }
        }
Beispiel #9
0
        private async Task GetRulePackages()
        {
            try
            {
                await QueuedTask.Run(async() =>
                {
                    //building the URL to get the ruel packages.
                    UriBuilder searchURL =
                        new UriBuilder(_arcgisOnline)
                    {
                        Path = "sharing/rest/search"
                    };

                    EsriHttpClient httpClient = new EsriHttpClient();

                    //these are the 3 rule packages we will download for this sample
                    string rulePackage =
                        "(type:\"Rule Package\" AND (title:\"Paris Rule package 2014\" OR title:\"Venice Rule package 2014\" OR title:\"Extrude/Color/Rooftype Rule package 2014\"))&f=json";
                    searchURL.Query = string.Format("q={0}&f=json", rulePackage);

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

                    //Parsing the JSON retrieved.
                    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);

                    //creating the collection of Rule packages from the parsed JSON.
                    foreach (dynamic item in resultItemList)
                    {
                        var id        = item.id.ToString();
                        var title     = item.title.ToString();
                        var name      = item.name.ToString();
                        var snippet   = item.snippet.ToString();
                        var thumbnail = item.thumbnail.ToString();
                        lock (_rpkLock)
                        {
                            RulePackageCollection.Add(new RulePackage(_arcgisOnline, id, title, name, thumbnail, snippet));
                        }
                    }
                });
            }

            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
Beispiel #10
0
        public async Task ExecDownloadAsync(OnlineQuery query, string fileName)
        {
            EsriHttpClient httpClient = new EsriHttpClient();
            var            response   = httpClient.Get(query.DownloadUrl);
            var            stm        = await response.Content.ReadAsStreamAsync();

            using (MemoryStream ms = new MemoryStream()) {
                stm.CopyTo(ms);
                System.IO.File.WriteAllBytes(fileName, ms.ToArray());
            }
        }
        /// <summary>
        /// Check if the service name is already in use
        /// </summary>
        /// <param name="baseURI"></param>
        /// <param name="serviceName"></param>
        /// <param name="serviceType"></param>
        /// <returns></returns>
        Tuple <bool, string> isServiceNameAvailable(string baseURI, string serviceName, string serviceType)
        {
            EsriHttpClient myClient = new EsriHttpClient();

            #region REST call to get appInfo.Item.id and user.lastLogin of the licensing portal
            string selfUri      = @"/sharing/rest/portals/self?f=json";
            var    selfResponse = myClient.Get(baseURI + selfUri);
            if (selfResponse == null)
            {
                return(new Tuple <bool, String>(false, "HTTP response is null"));
            }

            string outStr = selfResponse.Content.ReadAsStringAsync().Result;

            //Deserialize the response in JSON into a usable object.
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            PortalSelf           self_obj   = (PortalSelf)serializer.Deserialize(outStr, typeof(PortalSelf));
            if ((self_obj == null) || (self_obj.id == null))
            {
                return(new Tuple <bool, String>(false, "Failed portal self call"));
            }
            #endregion

            string requestUrl = baseURI + @"/sharing/rest/portals/" + self_obj.id + @"/isServiceNameAvailable";
            requestUrl += "?f=json&type=" + serviceType + "&name=" + serviceName;

            EsriHttpResponseMessage respMsg = myClient.Get(requestUrl);
            if (respMsg == null)
            {
                return(new Tuple <bool, String>(false, "HTTP response is null"));
            }

            outStr = respMsg.Content.ReadAsStringAsync().Result;
            //Deserialize the response in JSON into a usable object.
            AvailableResult obj = (AvailableResult)serializer.Deserialize(outStr, typeof(AvailableResult));
            if (obj == null)
            {
                return(new Tuple <bool, String>(false, "Service fails to be analyzed - " + outStr));
            }
            return(new Tuple <bool, string> (obj.available, outStr));
        }
        /// <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() =>
                {
                    //building the URL to get the webmaps.
                    UriBuilder searchURL = new UriBuilder(_arcgisOnline)
                    {
                        Path = "sharing/rest/search"
                    };
                    EsriHttpClient httpClient = new EsriHttpClient();

                    //these are the webmaps we will download for this sample
                    string webmaps =
                        "(type:\"Web Map\")&f=json";
                    searchURL.Query    = string.Format("q={0}&f=json", webmaps);
                    var searchResponse = httpClient.Get(searchURL.Uri.ToString());

                    //Parsing the JSON retrieved.
                    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);

                    //creating the collection of Rule packages from the parsed JSON.
                    foreach (dynamic item in resultItemList)
                    {
                        var id        = item.id.ToString();
                        var title     = item.title.ToString();
                        var name      = item.name.ToString();
                        var snippet   = item.snippet.ToString();
                        var thumbnail = item.thumbnail.ToString();
                        var owner     = item.owner.ToString();
                        lstWebmapItems.Add(new WebMapItem(_arcgisOnline, id, title, name, thumbnail, snippet, owner));
                    }
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            return(lstWebmapItems);
        }
        // Event Handler, gets the name of the service selected and queries it to get the list of RFT's
        private async void Service_SelectChanged(object sender)
        {
            try
            {
                ServiceURL = myDict[sender.ToString()];
                if (RFTList != null)
                {
                    RFTList.Clear();
                }
                string Path       = $"/rasterFunctionInfos";
                string Query      = "?f=json";
                var    url        = ServiceURL + Path + Query;
                var    httpClient = new EsriHttpClient();
                var    response   = httpClient?.Get(url.ToString());
                var    respStr    = await response?.Content?.ReadAsStringAsync();

                var rasterFunctionInfo      = JObject.Parse(respStr);
                var rasterFunctionInfoValue = (JArray)rasterFunctionInfo["rasterFunctionInfos"];
                if (rasterFunctionInfoValue == null)
                {
                    RFTList.Add("Test");
                }
                else
                {
                    foreach (JObject value in rasterFunctionInfoValue)
                    {
                        foreach (var property in value.Properties())
                        {
                            if (property.Name == "name")
                            {
                                string rasterFunctionTemplate = property.Value.ToString();
                                RFTList.Add(rasterFunctionTemplate);
                            }
                        }
                    }
                }

                // Update Observable Collection to reflect changes in UI
                NotifyPropertyChanged(() => RFTList);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message);
            }
        }
Beispiel #14
0
        public static async Task EsriHttpClientMethods3()
        {
            #region EsriHttpClient: Get a Service Layer and Add it to Pro

            UriBuilder searchURL = new UriBuilder(ArcGISPortalManager.Current.GetActivePortal().PortalUri)
            {
                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.Instance.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.Instance.CanCreateLayerFrom(currentItem))
                {
                    LayerFactory.Instance.CreateLayer(currentItem, MapView.Active.Map);
                }
            });

            #endregion
        }
        private string GetLoggedInUser()
        {
            UriBuilder selfURL = new UriBuilder(PortalManager.GetActivePortal());

            selfURL.Path  = "sharing/rest/portals/self";
            selfURL.Query = "f=json";
            EsriHttpClient          client   = new EsriHttpClient();
            EsriHttpResponseMessage response = client.Get(selfURL.Uri.ToString());

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

            // if the response doesn't contain the user information then it is essentially
            // an anonymous request against the portal
            if (portalSelf.user == null)
            {
                return(null);
            }
            string userName = portalSelf.user.username;

            return(userName);
        }
Beispiel #16
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
            }
        }
        /// <summary>
        /// This method uses EsriHttpClient.Get method to fetch licensing info from licensing portal
        /// </summary>
        /// <returns></returns>
        Tuple<bool, string> TestGetLicense()
        {
            string printMore = "";
            LicenseLevels ll = LicenseInformation.Level;
            string ll_str = Enum.GetName(typeof(LicenseLevels), ll);
            printMore += "License level: " + ll_str + "\n";

            Tuple<bool, string> regPortal = GetLicensingPortalFReg();
            //if (regPortal.Item1 == false)
            //Assert.Inconclusive(regPortal.Item2 + " [CR310474]");
            string portalUrl = regPortal.Item2;
            printMore += "Licensing portal: " + portalUrl + "\n";
            EsriHttpClient myClient = new EsriHttpClient();

            #region REST call to get appInfo.Item.id and user.lastLogin of the licensing portal
            string selfUri = @"/sharing/rest/portals/self?f=json";
            var selfResponse = myClient.Get(portalUrl + selfUri);
            if (selfResponse == null)
                return new Tuple<bool, string>(false, "HTTP response is null");

            if (selfResponse.StatusCode != System.Net.HttpStatusCode.OK)
                return new Tuple<bool, string>(false, "Licensing portal is not set");

            string outStr = selfResponse.Content.ReadAsStringAsync().Result;

            //Deserialize the response in JSON into a usable object. 
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            PortalSelf self_obj = (PortalSelf)serializer.Deserialize(outStr, typeof(PortalSelf));
            if ((self_obj == null) || (self_obj.appInfo == null) || (self_obj.user == null))
            {
                return new Tuple<bool, string>(true, printLicenseCodes() + "\nPro is licensed offline.");
            }
            #endregion

            #region REST call to get the userLicenses
            string layerUri = @"/sharing/rest/content/listings/" + self_obj.appInfo.itemId + "/userLicenses?f=json&nonce=007&timestamp=" + self_obj.user.lastLogin;
            var response = myClient.Get(portalUrl + layerUri);
            if (response == null)
                return new Tuple<bool, string>(false, "HTTP response is null");

            string outStr2 = response.Content.ReadAsStringAsync().Result;

            //Deserialize the response in JSON into a usable object. 
            userLicenses obj = (userLicenses)serializer.Deserialize(outStr2, typeof(userLicenses));
            if (obj == null || obj.userEntitlementsString == null)
            {
                return new Tuple<bool, string>(true, printLicenseCodes() + "\nPro is licensed offline, and signed in with a different account.");
            }
            userEntitlementsString entitlement = (userEntitlementsString)serializer.Deserialize(obj.userEntitlementsString, typeof(userEntitlementsString));
            if (entitlement == null)
                return new Tuple<bool, string>(false, "Failed to fetch valid entitlements.");
            else
            {
                printMore += printLicenseCodes() + "Entitlements returned by GET request:";
                foreach (string e in entitlement.entitlements)
                    printMore += " " + e;
                printMore += "\nLicenses returned by GET request:";
                foreach (string l in entitlement.licenses)
                    printMore += " " + l;
                return new Tuple<bool, string>(true, printMore);
            }
            #endregion
        }
Beispiel #18
0
        public static async Task EsriHttpClientMethods()
        {
            #region EsriHttpClient: Get the Current signed on User

            //Reference Newtonsoft - Json.Net
            //Reference System.Net.Http
            UriBuilder selfURL = new UriBuilder(ArcGISPortalManager.Current.GetActivePortal().PortalUri)
            {
                Path  = "sharing/rest/portals/self",
                Query = "f=json"
            };
            EsriHttpResponseMessage response = new EsriHttpClient().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;
            }
            string userName = portalSelf.user.username;

            #endregion

            #region Get the Groups for the Current Signed on User

            //Assume that you have executed the "Get the Current signed on User" snippet and have 'userName'
            UriBuilder groupsURL = new UriBuilder(ArcGISPortalManager.Current.GetActivePortal().PortalUri)
            {
                Path  = String.Format("sharing/rest/community/users/{0}", userName),
                Query = "f=json"
            };
            var     groupResponse = new EsriHttpClient().Get(groupsURL.Uri.ToString());
            dynamic portalGroups  = JObject.Parse(await groupResponse.Content.ReadAsStringAsync());

            string groups = portalGroups.groups.ToString();

            #endregion

            #region EsriHttpClient: Query for esri content on the active Portal
            //http://www.arcgis.com/sharing/search?q=owner:esri&f=json

            UriBuilder searchURL = new UriBuilder(ArcGISPortalManager.Current.GetActivePortal().PortalUri)
            {
                Path  = "sharing/rest/search",
                Query = "q=owner:esri&f=json"
            };
            EsriHttpClient httpClient     = new EsriHttpClient();
            var            searchResponse = httpClient.Get(searchURL.Uri.ToString());
            dynamic        resultItems    = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());

            long numberOfTotalItems = resultItems.total.Value;
            long currentCount       = 0;

            List <dynamic> resultItemList = new List <dynamic>();
            // store the first results in the list
            resultItemList.AddRange(resultItems.results);
            currentCount = currentCount + resultItems.num.Value;
            //Up to 50
            while (currentCount < numberOfTotalItems && currentCount <= 50)
            {
                searchURL.Query = String.Format("q=owner:esri&start={0}&f=json", resultItems.nextStart.Value);
                searchResponse  = httpClient.Get(searchURL.Uri.ToString());
                resultItems     = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());
                resultItemList.AddRange(resultItems.results);
                currentCount = currentCount + resultItems.num.Value;
            }

            #endregion
        }
Beispiel #19
0
        public async Task <BA_ReturnCode> UpdateAoiItemsAsync(string stationTriplet)
        {
            string        nwccAoiName   = "";
            string        huc           = "";
            string        aoiSummaryTag = "";
            BA_ReturnCode success       = GeneralTools.LoadBatchToolSettings();

            if (success != BA_ReturnCode.Success)
            {
                MessageBox.Show("Batch tool settings could not be loaded. The portal files cannot be updated!!");
                return(success);
            }
            string[] arrResults = await GeneralTools.QueryMasterAoiProperties(stationTriplet);

            if (arrResults.Length == 4)
            {
                nwccAoiName = arrResults[0].Trim();
                nwccAoiName = nwccAoiName.Replace(" ", "_");
                huc         = arrResults[3];
                string[] pieces = stationTriplet.Split(':');
                if (pieces.Length == 3)
                {
                    aoiSummaryTag = arrResults[0].Trim() + " " + pieces[0] + " " + pieces[1];
                }
                else
                {
                    MessageBox.Show("Unable to parse station triplet. The portal files cannot be updated!!");
                    return(BA_ReturnCode.ReadError);
                }
            }
            else
            {
                MessageBox.Show("Unable to retrieve AOI properties from Master. The portal files cannot be updated!!");
                return(BA_ReturnCode.ReadError);
            }
            // Ensure that the user is signed into the NRCS Portal
            BA_Objects.AGSPortalProperties portalProps = new BA_Objects.AGSPortalProperties();
            var info = await ArcGISPortalManager.Current.GetActivePortal().GetPortalInfoAsync();

            if (info.OrganizationName.Equals(BA_Objects.AGSPortalProperties.PORTAL_ORGANIZATION))
            {
                portalProps.IsNrcsPortal = true;
            }
            await QueuedTask.Run(() =>
            {
                portalProps.IsSignedIn = ArcGISPortalManager.Current.GetActivePortal().IsSignedOn();
                portalProps.UserName   = ArcGISPortalManager.Current.GetActivePortal().GetSignOnUsername();
                if (portalProps.UserName.Equals(BA_Objects.AGSPortalProperties.NWCC_NRCS_USER))
                {
                    portalProps.IsNrcsUser = true;
                }
            });

            if (!portalProps.IsNrcsPortal)
            {
                MessageBox.Show("Please sign into the USDA NRCS ArcGIS Online portal before trying to update items!!", "BAGIS-PRO");
                return(BA_ReturnCode.NotSupportedOperation);
            }
            if (!portalProps.IsSignedIn)
            {
                var result = await ArcGISPortalManager.Current.GetActivePortal().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? Items cannot be updated ! " +
                                                              "ArcGIS Pro will use a previous version of the file if it exists");
                    return(BA_ReturnCode.NotSupportedOperation);
                }
            }

            UriBuilder searchURL = new UriBuilder(ArcGISPortalManager.Current.GetActivePortal().PortalUri);

            EsriHttpClient httpClient = new EsriHttpClient();

            searchURL.Path = "sharing/rest/search";
            string pdfDocs  = "(type:\"PDF\")";
            string titleAoi = "(title:\"" + nwccAoiName + "\")";

            searchURL.Query = string.Format("q=owner:{0} {1} {2} &f=json", portalProps.UserName, titleAoi, pdfDocs);
            var     searchResponse = httpClient.Get(searchURL.Uri.ToString());
            dynamic resultItems    = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());

            long numberOfTotalItems = resultItems.total.Value;

            if (numberOfTotalItems == 0)
            {
                return(BA_ReturnCode.ReadError);
            }
            //string fileName = aoiName + "_overview.pdf";
            List <string> allFileNames = new List <string>
            {
                nwccAoiName + "_" + Constants.FILE_EXPORT_OVERVIEW_PDF,
                nwccAoiName + "_" + Constants.FILE_EXPORT_MAP_ELEV_PDF,
                nwccAoiName + "_" + Constants.FILE_EXPORT_LAND_COVER_PDF,
                nwccAoiName + "_" + Constants.FILE_EXPORT_ASPECT_DISTRIBUTION_PDF,
                nwccAoiName + "_" + Constants.FILE_EXPORT_SLOPE_DISTRIBUTION_PDF,
                nwccAoiName + "_" + Constants.FILE_EXPORT_SITE_REPRESENTATION_PDF,
                nwccAoiName + "_" + Constants.FILE_EXPORT_PRECIPITATION_DISTRIBUTION_PDF,
                nwccAoiName + "_" + Constants.FILE_EXPORT_SEASONAL_PRECIP_DISTRIBUTION_PDF,
                nwccAoiName + "_" + Constants.FILE_EXPORT_SNODAS_SWE_PDF,
                nwccAoiName + "_" + Constants.FILE_EXPORT_POTENTIAL_SITE_ANALYSIS_PDF,
                nwccAoiName + "_" + Constants.FILE_EXPORT_WATERSHED_REPORT_PDF
            };
            List <string> requiredTags = new List <string>()
            {
                "GIS",
                "BAGIS",
                "SNOTEL",
                "eBagis",
                huc,
                aoiSummaryTag
            };
            List <dynamic> resultItemList = new List <dynamic>();

            resultItemList.AddRange(resultItems.results);
            foreach (var item in resultItemList)
            {
                string itemFile = (string)item.name;
                if (allFileNames.Contains(itemFile))
                {
                    string        itemId   = (string)item.id;
                    string        strTitle = (string)item.title;
                    List <string> tags     = item.tags.ToObject <List <string> >();
                    UpdateItem(portalProps.UserName, itemId, strTitle, requiredTags, tags);
                }
            }
            return(BA_ReturnCode.Success);
        }
        /// <summary>
        /// Gets the item title/name based on its item ID
        /// </summary>
        /// <param name="baseURI"></param>
        /// <param name="username"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        Tuple<bool, string> getServiceName(string baseURI, string username, string itemId)
        {
            EsriHttpClient myClient = new EsriHttpClient();

            #region REST call to get service name
            string requestUrl = baseURI + @"/sharing/rest/content/users/" + username + @"/items/" + itemId + "?f=json";
            var response = myClient.Get(requestUrl);
            if (response == null)
                return new Tuple<bool, String>(false, "HTTP response is null");

            string outStr = response.Content.ReadAsStringAsync().Result;

            //Deserialize the response in JSON into a usable object. 
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            OnlineItem obj = (OnlineItem)serializer.Deserialize(outStr, typeof(OnlineItem));
            if (obj == null || obj.item.title == null)
            {
                return new Tuple<bool, String>(false, "Failed item call");
            }
            return new Tuple<bool, String>(true, obj.item.title);
            #endregion
        }
        /// <summary>
        /// Execute the query command
        /// </summary>
        private void CmdDoQuery()
        {
            try
            {
                var httpEsri = new EsriHttpClient() { BaseAddress = PortalManager.GetActivePortal() };
                // value has the following format: url with {};Redlands,...,...;Search Query,...,...
                // where Redlands ... are values and search query are keys
                var parts = AgolQuery.Value.Split(";".ToCharArray());
                var getUrl = parts[0];

                // get parameters
                if (CallParams.Count > 0)
                {
                    var lstParams = new List<object>() as IList<object>;
                    foreach (var kv in CallParams)
                        lstParams.Add(kv.Param);
                    getUrl = string.Format(parts[0], lstParams.ToArray());
                }
                System.Diagnostics.Debug.WriteLine(getUrl);
                var httpResponse = httpEsri.Get(getUrl);
                if (httpResponse.StatusCode == HttpStatusCode.OK && httpResponse.Content != null)
                {
                    var content = httpResponse.Content.ReadAsStringAsync().Result;
                    QueryResult = string.Format(@"{0}{1}", getUrl, System.Environment.NewLine);
                    QueryResult += string.Format(@"IsSuccessStatusCode: {0}{1}", httpResponse.IsSuccessStatusCode, System.Environment.NewLine);
                    QueryResult += string.Format(@"StatusCode: {0}{1}", httpResponse.StatusCode, System.Environment.NewLine);
                    QueryResult += content;
                    if (AgolQuery.Key == ArcGISOnlineQueries.AGSQueryType.GetSelf)
                    {
                        _AgolUser = AgolUser.LoadAgolUser(content);
                    }
                    else if (AgolQuery.Key == ArcGISOnlineQueries.AGSQueryType.GetSearch)
                    {
                        _AgolSearchResult = AgolSearchResult.LoadAgolSearchResult(content);
                    }
                    else if (AgolQuery.Key == ArcGISOnlineQueries.AGSQueryType.GetUserContent)
                    {
                        _AgolUserContent = AgolUserContent.LoadAgolUserContent(content);
                        _AgolFolderContent = null;
                    }
                    else if (AgolQuery.Key == ArcGISOnlineQueries.AGSQueryType.GetUserContentForFolder)
                    {
                        _AgolFolderContent = AgolFolderContent.LoadAgolFolderContent(content);
                    }
                    System.Diagnostics.Debug.WriteLine(QueryResult);
                }
            }
            catch (Exception ex)
            {
                QueryResult = ex.ToString();
            }
        }
Beispiel #22
0
        /// <summary>
        /// This method uses EsriHttpClient.Get method to fetch licensing info from licensing portal
        /// </summary>
        /// <returns></returns>
        Tuple <bool, string> TestGetLicense()
        {
            string        printMore = "";
            LicenseLevels ll        = LicenseInformation.Level;
            string        ll_str    = Enum.GetName(typeof(LicenseLevels), ll);

            printMore += "License level: " + ll_str + "\n";

            Tuple <bool, string> regPortal = GetLicensingPortalFReg();
            //if (regPortal.Item1 == false)
            //Assert.Inconclusive(regPortal.Item2 + " [CR310474]");
            string portalUrl = regPortal.Item2;

            printMore += "Licensing portal: " + portalUrl + "\n";
            EsriHttpClient myClient = new EsriHttpClient();

            #region REST call to get appInfo.Item.id and user.lastLogin of the licensing portal
            string selfUri      = @"/sharing/rest/portals/self?f=json";
            var    selfResponse = myClient.Get(portalUrl + selfUri);
            if (selfResponse == null)
            {
                return(new Tuple <bool, string>(false, "HTTP response is null"));
            }

            if (selfResponse.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return(new Tuple <bool, string>(false, "Licensing portal is not set"));
            }

            string outStr = selfResponse.Content.ReadAsStringAsync().Result;

            //Deserialize the response in JSON into a usable object.
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            PortalSelf           self_obj   = (PortalSelf)serializer.Deserialize(outStr, typeof(PortalSelf));
            if ((self_obj == null) || (self_obj.appInfo == null) || (self_obj.user == null))
            {
                return(new Tuple <bool, string>(true, printLicenseCodes() + "\nPro is licensed offline."));
            }
            #endregion

            #region REST call to get the userLicenses
            string layerUri = @"/sharing/rest/content/listings/" + self_obj.appInfo.itemId + "/userLicenses?f=json&nonce=007&timestamp=" + self_obj.user.lastLogin;
            var    response = myClient.Get(portalUrl + layerUri);
            if (response == null)
            {
                return(new Tuple <bool, string>(false, "HTTP response is null"));
            }

            string outStr2 = response.Content.ReadAsStringAsync().Result;

            //Deserialize the response in JSON into a usable object.
            userLicenses obj = (userLicenses)serializer.Deserialize(outStr2, typeof(userLicenses));
            if (obj == null || obj.userEntitlementsString == null)
            {
                return(new Tuple <bool, string>(true, printLicenseCodes() + "\nPro is licensed offline, and signed in with a different account."));
            }
            userEntitlementsString entitlement = (userEntitlementsString)serializer.Deserialize(obj.userEntitlementsString, typeof(userEntitlementsString));
            if (entitlement == null)
            {
                return(new Tuple <bool, string>(false, "Failed to fetch valid entitlements."));
            }
            else
            {
                printMore += printLicenseCodes() + "Entitlements returned by GET request:";
                foreach (string e in entitlement.entitlements)
                {
                    printMore += " " + e;
                }
                printMore += "\nLicenses returned by GET request:";
                foreach (string l in entitlement.licenses)
                {
                    printMore += " " + l;
                }
                return(new Tuple <bool, string>(true, printMore));
            }
            #endregion
        }
Beispiel #23
0
        /// <summary>
        /// Search for item in the active portal or the portal URL specified.
        /// Returns itemdID or null if item not found.
        /// </summary>
        /// <param name="itemName">Item Name as a string</param>
        /// <param name="itemType">Item TYpe as a string. Use types used by AGO/portal</param>
        /// <param name="portalURL">PortalURL as a string. Optional. When specified, searchs in that URL, else under active portal</param>
        /// <returns>PortalItem. Null if item was not found</returns>
        public static Tuple <bool, SDCItem> SearchPortalItemREST(string @itemName, string itemType, string portalURL)
        {
            //string extension = System.IO.Path.GetExtension(@itemName);
            //@itemName = @itemName.Substring(0, @itemName.Length - extension.Length);

            try
            {
                #region Construct and make REST query
                if (!portalURL.EndsWith("/"))
                {
                    portalURL += "/";
                }

                string         queryURL = portalURL + @"sharing/rest/search?q=" + @itemName + " AND type:" + itemType + "&f=json";
                EsriHttpClient myClient = new EsriHttpClient();
                var            response = myClient.Get(queryURL);
                if (response == null)
                {
                    return(new Tuple <bool, SDCItem>(false, null));
                }

                string outStr = response.Content.ReadAsStringAsync().Result;
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                SearchResult         sr         = (SearchResult)serializer.Deserialize(outStr, typeof(SearchResult));
                #endregion

                #region Get ItemID from search result, rerun the search for the item and return the full item
                if (sr != null)
                {
                    while (sr.nextStart <= sr.total)
                    {
                        for (int i = 0; i < sr.results.Count; i++)
                        {
                            //string srID = sr.results[i].id; //Technically, only one item with a particular name and type can exist
                            //string itemQueryURL = portalURL + @"sharing/rest/content/items/" + srID + "?f=json&token=" + pToken;
                            //SDCItem resultItem = (SDCItem)RESTcaller(itemQueryURL, typeof(SDCItem));
                            //if ((resultItem.title == itemName) && (resultItem.type == itemType))
                            //    return resultItem;
                            if ((sr.results[i].name == itemName) && (sr.results[i].type.Contains(itemType)))
                            {
                                return(new Tuple <bool, SDCItem>(true, sr.results[i]));
                            }
                        }
                        if (sr.nextStart <= 0)
                        {
                            return(new Tuple <bool, SDCItem>(false, null));
                        }

                        #region prepare for the next batch of search results
                        queryURL = portalURL + @"sharing/rest/search?q=" + itemName + " AND type:" + itemType + "&f=json&start=" + sr.nextStart;
                        response = myClient.Get(queryURL);
                        if (response == null)
                        {
                            return(new Tuple <bool, SDCItem>(false, null));
                        }
                        outStr = response.Content.ReadAsStringAsync().Result;
                        sr     = (SearchResult)serializer.Deserialize(outStr, typeof(SearchResult));
                        #endregion
                    }
                    return(new Tuple <bool, SDCItem>(false, null));
                }
                else
                {
                    return(new Tuple <bool, SDCItem>(false, null));
                }
                #endregion
            }
            catch (Exception exRESTsearch)
            {
                Console.WriteLine("Exception occurred when search for item through REST call. Exception: " + exRESTsearch.ToString());
                return(null);
            }
        }
        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";
        }
        /// <summary>
        /// Execute the given query and return the result
        /// </summary>
        /// <param name="query"></param>
        /// <param name="results"></param>
        /// <param name="maxResults"></param>
        /// <returns></returns>
        public string Exec(OnlineQuery query, ObservableCollection <OnlineResultItem> results,
                           int maxResults = 0)
        {
            if (maxResults == 0)
            {
                maxResults = DefaultMaxResults;
            }
            if (MaxResponseLength == 0)
            {
                MaxResponseLength = DefaultMaxResponseLength;
            }

            _response      = new StringBuilder();
            _errorResponse = "";

            //slap in the initial request
            _response.AppendLine(query.FinalUrl);
            _response.AppendLine("");

            results.Clear();

            try {
                Tuple <long, long> stats = new Tuple <long, long>(-1, -1);
                do
                {
                    query.Start = stats.Item2;

                    System.Diagnostics.Debug.WriteLine("");
                    System.Diagnostics.Debug.WriteLine(query.FinalUrl);
                    System.Diagnostics.Debug.WriteLine("");

                    EsriHttpClient httpClient = new EsriHttpClient();

                    var response = httpClient.Get(query.FinalUri.ToString());
                    var raw      = response.Content.ReadAsStringAsync().Result;//block
                    stats = ProcessResults(results, raw, query);
                } while (stats.Item2 < maxResults && stats.Item2 > 0);
            }
            catch (WebException we) {
                //bad request
                _response.AppendLine("");
                _response.AppendLine("WebException: " + we.Message);
                _response.AppendLine(query.FinalUrl);
                _response.AppendLine("");
                _response.AppendLine(new Uri(query.FinalUrl).Scheme.ToUpper() + " " +
                                     ((int)we.Status).ToString());
                try {
                    _errorResponse = new StreamReader(we.Response.GetResponseStream()).ReadToEnd();
                    _response.AppendLine(_errorResponse);
                }
                catch {
                }
            }
            finally {
                //content = _response.ToString()
                //    .Replace("{", "{\r\n")
                //    .Replace("}", "\r\n}")
                //    .Replace(",\"", ",\r\n\"");
            }
            return(_response.ToString());
        }
        /// <summary>
        /// Search for item in the active portal or the portal URL specified.
        /// Returns itemdID or null if item not found.
        /// </summary>
        /// <param name="itemName">Item Name as a string</param>
        /// <param name="itemType">Item TYpe as a string. Use types used by AGO/portal</param>
        /// <param name="portalURL">PortalURL as a string. Optional. When specified, searchs in that URL, else under active portal</param>
        /// <returns>PortalItem. Null if item was not found</returns>
        public static Tuple<bool, SDCItem> SearchPortalItemREST(string @itemName, string itemType, string portalURL)
        {
            //string extension = System.IO.Path.GetExtension(@itemName);
            //@itemName = @itemName.Substring(0, @itemName.Length - extension.Length);

            try
            {
                #region Construct and make REST query
                if (!portalURL.EndsWith("/"))
                    portalURL += "/";

                string queryURL = portalURL + @"sharing/rest/search?q=" + @itemName + " AND type:" + itemType + "&f=json";
                EsriHttpClient myClient = new EsriHttpClient();
                var response = myClient.Get(queryURL);
                if (response == null)
                    return new Tuple<bool, SDCItem>(false, null);

                string outStr = response.Content.ReadAsStringAsync().Result;
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                SearchResult sr = (SearchResult)serializer.Deserialize(outStr, typeof(SearchResult));
                #endregion

                #region Get ItemID from search result, rerun the search for the item and return the full item
                if (sr != null)
                {
                    while (sr.nextStart <= sr.total)
                    {
                        for (int i = 0; i < sr.results.Count; i++)
                        {
                            //string srID = sr.results[i].id; //Technically, only one item with a particular name and type can exist
                            //string itemQueryURL = portalURL + @"sharing/rest/content/items/" + srID + "?f=json&token=" + pToken;
                            //SDCItem resultItem = (SDCItem)RESTcaller(itemQueryURL, typeof(SDCItem));
                            //if ((resultItem.title == itemName) && (resultItem.type == itemType))
                            //    return resultItem;
                            if ((sr.results[i].name == itemName) && (sr.results[i].type.Contains(itemType)))
                                return new Tuple<bool, SDCItem>(true, sr.results[i]);
                        }
                        if (sr.nextStart <= 0)
                            return new Tuple<bool, SDCItem>(false, null);

                        #region prepare for the enxt batch of search results
                        queryURL = portalURL + @"sharing/rest/search?q=" + itemName + " AND type:" + itemType + "&f=json&start=" + sr.nextStart;
                        response = myClient.Get(queryURL);
                        if (response == null)
                            return new Tuple<bool, SDCItem>(false, null);
                        outStr = response.Content.ReadAsStringAsync().Result;
                        sr = (SearchResult)serializer.Deserialize(outStr, typeof(SearchResult));
                        #endregion
                    }
                    return new Tuple<bool, SDCItem>(false, null);
                }
                else
                    return new Tuple<bool, SDCItem>(false, null);
                #endregion
            }
            catch (Exception exRESTsearch)
            {
                Console.WriteLine("Exception occurred when search for item through REST call. Exception: " + exRESTsearch.ToString());
                return null;
            }
        }
        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");
        }
        // Do a Query request on the selected point to get the list of overlapping scenes
        private Task ExtractInfoAsync(string X, string Y)
        {
            return(Application.Current.Dispatcher.Invoke(async() =>
            {
                try
                {
                    if (Scenes != null)
                    {
                        Scenes.Clear();
                        _selection.Clear();
                    }
                    // Get the image service URL from the current layer
                    SelectedLayer = MapView.Active.GetSelectedLayers().FirstOrDefault();
                    if (SelectedLayer is ImageServiceLayer)
                    {
                        string ImageServiceURL = null;
                        ImageServiceLayer imageServiceLayer = (ImageServiceLayer)SelectedLayer;
                        await QueuedTask.Run(() =>
                        {
                            CIMDataConnection DataConnection = imageServiceLayer.GetDataConnection();
                            string DataConnectionXMLString = DataConnection.ToXml();
                            var ParsedDataConnectionString = XElement.Parse(DataConnectionXMLString);
                            var URLNode = ParsedDataConnectionString.Elements("URL");
                            foreach (XElement nodeValue in URLNode)
                            {
                                ImageServiceURL = nodeValue.ToString();
                            }
                        });

                        // Send a request to the REST end point to get information
                        var point = "{x:" + X + ",y:" + Y + "}";
                        string[] URLSplit = Regex.Split(ImageServiceURL, "arcgis/");
                        //string ServiceURL = "https://landsat2.arcgis.com/";
                        string ServiceURL = URLSplit[0].Replace("<URL>", string.Empty);
                        string url = ServiceURL + "query";
                        var ubldr = new UriBuilder(ServiceURL);
                        string path = "arcgis/rest/" + URLSplit[1].Replace("</URL>", string.Empty) + "/query";
                        ubldr.Path = path;
                        //ubldr.Path = $"arcgis/rest/services/Landsat/MS/ImageServer/query";

                        // Allows to give parameters as dictionary key,pair values rather than manually constructing a json
                        var query = HttpUtility.ParseQueryString(ubldr.Query);
                        query["f"] = "json";
                        query["geometry"] = point;
                        query["geometryType"] = "esriGeometryPoint";
                        query["spatialRel"] = "esriSpatialRelIntersects";
                        query["outFields"] = "*";
                        query["pixelSize"] = "30";
                        query["returnGeometry"] = "false";
                        ubldr.Query = query.ToString();
                        var httpClient = new EsriHttpClient();
                        var response = httpClient?.Get(ubldr.Uri.ToString());
                        var respstr = await response?.Content?.ReadAsStringAsync();
                        var SceneList = JObject.Parse(respstr);
                        var SceneListInfo = (JArray)SceneList["features"];
                        foreach (JObject value in SceneListInfo)
                        {
                            foreach (var property in value.Properties())
                            {
                                if (property.Name == "attributes")
                                {
                                    {
                                        // Add obtained json response as a dictionary to a list of dictionaries
                                        var attribute = property.Value.ToString();
                                        var attributeValue = JObject.Parse(attribute);
                                        var category = Int32.Parse(attributeValue["Category"].ToString());
                                        var attributeValueDict = attributeValue.ToObject <Dictionary <string, string> >();
                                        if (category == 1)
                                        {
                                            _selection.Add(attributeValueDict);
                                        }
                                    }
                                }
                            }
                        }

                        foreach (var value in _selection)
                        {
                            // Extract and convert epoch time to dd/MM/yyyy format
                            double UnixTime = Convert.ToDouble(value["AcquisitionDate"].ToString());
                            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                            DateTime date = epoch.AddMilliseconds(UnixTime);
                            var AcqDate = date.ToString("dd / MM / yyyy");
                            var objID = value["OBJECTID"].ToString();
                            var ClCover = value["CloudCover"].ToString();
                            var SceneName = value["Name"].ToString();
                            Scenes.Add(new Scene {
                                AcqDate = AcqDate, Name = SceneName, CloudCover = ClCover, ObjectID = objID
                            });
                        }
                        // Add recieved information to an Observable Collection and notfy UI
                        NotifyPropertyChanged(() => Scenes);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine(ex.Message);
                }
            }));
        }
        /// <summary>
        /// Check if the service name is already in use
        /// </summary>
        /// <param name="baseURI"></param>
        /// <param name="serviceName"></param>
        /// <param name="serviceType"></param>
        /// <returns></returns>
        Tuple<bool, string> isServiceNameAvailable(string baseURI, string serviceName, string serviceType)
        {
            EsriHttpClient myClient = new EsriHttpClient();

            #region REST call to get appInfo.Item.id and user.lastLogin of the licensing portal
            string selfUri = @"/sharing/rest/portals/self?f=json";
            var selfResponse = myClient.Get(baseURI + selfUri);
            if (selfResponse == null)
                return new Tuple<bool, String>(false, "HTTP response is null");

            string outStr = selfResponse.Content.ReadAsStringAsync().Result;

            //Deserialize the response in JSON into a usable object. 
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            PortalSelf self_obj = (PortalSelf)serializer.Deserialize(outStr, typeof(PortalSelf));
            if ((self_obj == null) || (self_obj.id == null))
            {
                return new Tuple<bool, String>(false, "Failed portal self call");
            }
            #endregion

            string requestUrl = baseURI + @"/sharing/rest/portals/" + self_obj.id + @"/isServiceNameAvailable";
            requestUrl += "?f=json&type=" + serviceType + "&name=" + serviceName;

            EsriHttpResponseMessage respMsg = myClient.Get(requestUrl);
            if (respMsg == null)
                return new Tuple<bool, String>(false, "HTTP response is null");

            outStr = respMsg.Content.ReadAsStringAsync().Result;
            //Deserialize the response in JSON into a usable object. 
            AvailableResult obj = (AvailableResult)serializer.Deserialize(outStr, typeof(AvailableResult));
            if (obj == null)
                return new Tuple<bool, String>(false, "Service fails to be analyzed - " + outStr);
            return new Tuple<bool, string> (obj.available, outStr);
        }