Exemplo n.º 1
0
        /// <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();
            SharingContracts.PortalSelf self_obj   = (SharingContracts.PortalSelf)serializer.Deserialize(outStr, typeof(SharingContracts.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;
            //De-serialize the response in JSON into a usable object.
            SharingContracts.AvailableResult obj = (SharingContracts.AvailableResult)serializer.Deserialize(outStr, typeof(SharingContracts.AvailableResult));
            if (obj == null)
            {
                return(new Tuple <bool, String>(false, "Service fails to be analyzed - " + outStr));
            }
            return(new Tuple <bool, string>(obj.available, outStr));
        }
Exemplo n.º 2
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 async Task <object> PublishService(string id, string title)
        {
            string userName   = GetLoggedInUser();
            string publishURL = String.Format("{0}/sharing/rest/content/users/{1}/publish", PortalManager.GetActivePortal(), userName);

            EsriHttpClient myClient          = new EsriHttpClient();
            string         publishParameters = string.Format("{{\"name\":\"{0}\"}}", title);
            var            postData          = new List <KeyValuePair <string, string> >();

            postData.Add(new KeyValuePair <string, string>("f", "json"));
            postData.Add(new KeyValuePair <string, string>("itemId", id));
            postData.Add(new KeyValuePair <string, string>("filetype", "vectortilepackage"));
            postData.Add(new KeyValuePair <string, string>("outputType", "VectorTiles"));
            postData.Add(new KeyValuePair <string, string>("publishParameters", publishParameters));
            HttpContent content = new FormUrlEncodedContent(postData);

            EsriHttpResponseMessage respMsg       = myClient.Post(publishURL, content);
            PublishResult           publishResult = JsonConvert.DeserializeObject <PublishResult>(await respMsg.Content.ReadAsStringAsync());

            if (publishResult.services.Count() == 1)
            {
                ShowProgress("Publish started", string.Format("Job id: {0}", publishResult.services[0].jobId), 3);
                string jobid     = publishResult.services[0].jobId;
                string jobStatus = "processing";
                int    i         = 0;
                while (jobStatus == "processing")
                {
                    i += 1;
                    Task.Delay(5000).Wait();
                    jobStatus = GetJobStatus(jobid, "publish", userName, publishResult.services[0].serviceItemId);
                    ShowProgress("Publish in progress", string.Format("Job status: {0} - {1}", jobStatus, i), 3);
                }
                ShowProgress("Publish in progress", string.Format("Job status: {0} - {1}", jobStatus, i), 3);
            }

            return(null);
        }
Exemplo n.º 4
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
        }
        /// <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();
            }
        }
        /// <summary>
        /// Execute the given query and return the result
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<string> ExecWithEsriClientAsync(OnlineQuery query, ObservableCollection<OnlineResultItem> results, int maxResults = 0) {

            if (maxResults == 0)
                maxResults = OnlineQuery.DefaultMaxResults;
            if (MaxResponseLength == 0)
                MaxResponseLength = OnlineQuery.DefaultMaxResponseLength;

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

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

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

                    query.Start = stats.Item2;

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

                    EsriHttpClient httpClient = new EsriHttpClient();
                    //submit the query
                    EsriHttpResponseMessage response = await httpClient.GetAsync(new Uri(query.FinalUrl).ToString());
                    HttpResponseHeaders headers = response.Headers;

                    //read out the json
                    string raw = await response.Content.ReadAsStringAsync();
                    //convert entity-replacement tags
                    raw = raw.Replace("&lt;", "<").Replace("&gt;", ">");
                    if (_response.Length < MaxResponseLength) {
                        _response.AppendLine("");
                        _response.AppendLine(raw);
                        if (_response.Length > MaxResponseLength)
                            _response.AppendLine("...");
                    }

                    Debug.WriteLine("");
                    Debug.WriteLine(raw);
                    Debug.WriteLine("");

                    //deserialize
                    stats = await ProcessResultsAsync(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 {
                }
            }

            return _response.ToString();
        }
Exemplo n.º 7
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);
            }
        }
        /// <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";
        }
Exemplo n.º 10
0
        public async void AddPortalItem()
        {
            var myPortal = ArcGISPortalManager.Current.GetActivePortal();

            if (!myPortal.IsSignedOn())
            {
                MessageBox.Show("Log onto portal before clicking this button!!");
            }
            string strToken = myPortal.GetToken();

            var owner = myPortal.GetSignOnUsername();
            //var owner = "owner";
            //var token = await Task.Run(() => GetToken(owner));
            //string strToken = Convert.ToString(token);

            //var url = $"{myPortal.PortalUri.AbsoluteUri}arcgis/sharing/rest/content/users/{owner}";
            var url      = $"https://www.arcgis.com/sharing/rest/portals/self?f=json&token=" + strToken;
            var response = new EsriHttpClient().Get(url);
            var json     = await response.Content.ReadAsStringAsync();

            dynamic portalSelf = JObject.Parse(json);

            var uploadUrl = "https://" + Convert.ToString(portalSelf.urlKey) +
                            ".maps.arcgis.com/sharing/rest/content/users/" + owner + "/addItem";

            //byte[] fileBytes = File.ReadAllBytes("C:\\Docs\\animas_AOI_prms\\maps_publish\\title_page.pdf");
            //convert filestream to byte array
            byte[] fileBytes;
            using (var fileStream = File.OpenRead("C:\\Docs\\animas_AOI_prms\\maps_publish\\title_page.pdf"))
            {
                var binaryReader = new BinaryReader(fileStream);
                fileBytes = binaryReader.ReadBytes((int)fileStream.Length);
            }
            var fileBinaryContent = new ByteArrayContent(fileBytes);

            string strTitle = "Testing 1 2 3";

            using (FileStream stream =
                       new FileStream("C:\\Docs\\animas_AOI_prms\\maps_publish\\title_page.pdf", FileMode.Open))
                using (var formData = new MultipartFormDataContent())
                {
                    // Add the HttpContent objects to the form data

                    // <input type="text" name="f" />
                    formData.Add(new StringContent("json"), "f");
                    formData.Add(new StringContent(strToken), "token");
                    formData.Add(new StringContent("true"), "async");
                    formData.Add(new StringContent("PDF"), "type");
                    formData.Add(new StringContent(strTitle), "title");
                    formData.Add(new StringContent("eBagis"), "tags");
                    formData.Add(new StringContent("upload from BAGIS"), "description");
                    var multipartContent = new MultipartFormDataContent
                    {
                        { fileBinaryContent, "file" }
                    };
                    formData.Add(multipartContent);

                    // Invoke the request to the server
                    // equivalent to pressing the submit button on
                    // a form with attributes (action="{url}" method="post")
                    response = await new EsriHttpClient().PostAsync(uploadUrl, formData);
                    json     = await response.Content.ReadAsStringAsync();
                }
        }
        /// <summary>
        /// Post "analyze" request on the portal item
        /// </summary>
        /// <param name="baseURI"></param>
        /// <param name="itemId"></param>
        /// <param name="filetype"></param>
        /// <param name="analyzeParameters"></param>
        /// <returns></returns>
        Tuple<bool, string> analyzeService(string baseURI, string itemId, string filetype, string analyzeParameters)
        {
            EsriHttpClient myClient = new EsriHttpClient();
            string requestUrl = baseURI + @"/sharing/rest/content/features/analyze";

            var postData = new List<KeyValuePair<string, string>>();
            postData.Add(new KeyValuePair<string, string>("f", "json"));
            postData.Add(new KeyValuePair<string, string>("itemId", itemId));
            postData.Add(new KeyValuePair<string, string>("filetype", filetype));
            postData.Add(new KeyValuePair<string, string>("analyzeParameters", analyzeParameters));
            HttpContent content = new FormUrlEncodedContent(postData);

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

            string outStr = respMsg.Content.ReadAsStringAsync().Result;
            //Deserialize the response in JSON into a usable object. 
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            //Deserialize the response in JSON into a usable object. 
            AnalyzedService obj = (AnalyzedService)serializer.Deserialize(outStr, typeof(AnalyzedService));
            if (obj == null)
                return new Tuple<bool, String>(false, "Service fails to be analyzed - " + outStr);
            if (obj.publishParameters != null)
            {
                string respReturn = SerializeToString(obj.publishParameters);
                if (respReturn == "")
                    return new Tuple<bool, String>(false, "Service fails to be analyzed - " + outStr);
                else
                    return new Tuple<bool, String>(true, respReturn);
            }
            return new Tuple<bool, String>(false, "Service fails to be analyzed - " + outStr);
        }
        /// <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
        }
        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());
        }
Exemplo n.º 15
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
        }
        /// <summary>
        /// Post "publish" request on the portal item
        /// </summary>
        /// <param name="baseURI"></param>
        /// <param name="username"></param>
        /// <param name="itemId"></param>
        /// <param name="filetype"></param>
        /// <param name="publishParameters"></param>
        /// <returns></returns>
        Tuple<bool, string> publishService(string baseURI, string username, string itemId, string filetype, string publishParameters)
        {
            EsriHttpClient myClient = new EsriHttpClient();
            string requestUrl = baseURI + @"/sharing/rest/content/users/" + username + @"/publish";

            var postData = new List<KeyValuePair<string, string>>();
            postData.Add(new KeyValuePair<string, string>("f", "json"));
            postData.Add(new KeyValuePair<string, string>("itemId", itemId));
            postData.Add(new KeyValuePair<string, string>("filetype", filetype));
            postData.Add(new KeyValuePair<string, string>("publishParameters", publishParameters));
            HttpContent content = new FormUrlEncodedContent(postData);

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

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

            string respReturn = "";
            foreach (PublishedService ps in obj.services)
                respReturn += ps.serviceurl;
            if (respReturn == "")
                return new Tuple<bool, String>(false, "Service creation fails - " + outStr);
            else
                return new Tuple<bool, String>(true, respReturn);

        }
Exemplo n.º 17
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);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Execute the given query and return the result
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task <string> ExecWithEsriClientAsync(OnlineQuery query, ObservableCollection <OnlineResultItem> results, int maxResults = 0)
        {
            if (maxResults == 0)
            {
                maxResults = OnlineQuery.DefaultMaxResults;
            }
            if (MaxResponseLength == 0)
            {
                MaxResponseLength = OnlineQuery.DefaultMaxResponseLength;
            }

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

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

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

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

                    EsriHttpClient httpClient = new EsriHttpClient();
                    //submit the query
                    EsriHttpResponseMessage response = await httpClient.GetAsync(new Uri(query.FinalUrl).ToString());

                    HttpResponseHeaders headers = response.Headers;

                    //read out the json
                    string raw = await response.Content.ReadAsStringAsync();

                    //convert entity-replacement tags
                    raw = raw.Replace("&lt;", "<").Replace("&gt;", ">");
                    if (_response.Length < MaxResponseLength)
                    {
                        _response.AppendLine("");
                        _response.AppendLine(raw);
                        if (_response.Length > MaxResponseLength)
                        {
                            _response.AppendLine("...");
                        }
                    }

                    Debug.WriteLine("");
                    Debug.WriteLine(raw);
                    Debug.WriteLine("");

                    //deserialize
                    stats = await ProcessResultsAsync(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 {
                }
            }

            return(_response.ToString());
        }
Exemplo n.º 19
0
        public void UpdateItem(string userName, string itemId, string strTitle, List <string> requiredTags, List <string> tags)
        {
            string strCredits = "Basin Analysis GIS is developed under the collaboration between NRCS NWCC " +
                                "and the Center for Spatial Analysis &Research at Portland State University.";
            string strDescription = "This report was generated in Basin Analysis GIS (BAGIS). See the " +
                                    "<a href=\"https://nrcs.maps.arcgis.com/sharing/rest/content/items/b121d25cc73c4b30a700b8d2d2ea23bc/data\" " +
                                    "target=\"_blank\">Basin Analysis Report Users Manual</a> for a complete description of the report. Please contact NWCC " +
                                    "(<a href=\"https://www.wcc.nrcs.usda.gov/\" target=\"_blank\">https://www.wcc.nrcs.usda.gov/</a>) for any questions.";
            string strLicense = "Public domain data. See <a href='https://www.wcc.nrcs.usda.gov/disclaimer.htm' target='_blank' " +
                                "rel='nofollow ugc noopener noreferrer'>https://www.wcc.nrcs.usda.gov/disclaimer.htm</a> for disclaimer.";

            if (tags == null)
            {
                tags = new List <string>();  // Ensure tags is never null to avoid exception
            }
            List <string> mergedTags = requiredTags.Union(tags).ToList();
            string        strMerged  = string.Join(",", mergedTags);

            // Generate summary from title
            string strSummary = "";

            if (!string.IsNullOrEmpty(strTitle))
            {
                string[] pieces = strTitle.Split(new char[0]);
                if (pieces.Length > 0)
                {
                    strSummary = pieces[0];
                }
                if (pieces.Length > 1)
                {
                    for (int i = 1; i < pieces.Length; i++)
                    {
                        strSummary = strSummary + " " + pieces[i].ToUpper();
                    }
                }
            }

            // Updating fields on item
            UriBuilder searchURL = new UriBuilder(ArcGISPortalManager.Current.GetActivePortal().PortalUri);

            searchURL.Path = "sharing/rest/content/users/" + userName + "/items/" + itemId + "/update";
            EsriHttpClient myClient = new EsriHttpClient();
            var            postData = new List <KeyValuePair <string, string> >();

            postData.Add(new KeyValuePair <string, string>("f", "json"));
            postData.Add(new KeyValuePair <string, string>("description", strDescription));
            postData.Add(new KeyValuePair <string, string>("snippet", strSummary));
            postData.Add(new KeyValuePair <string, string>("licenseInfo", strLicense));
            postData.Add(new KeyValuePair <string, string>("accessInformation", strCredits));
            postData.Add(new KeyValuePair <string, string>("tags", strMerged));

            using (HttpContent content = new FormUrlEncodedContent(postData))
            {
                EsriHttpResponseMessage respMsg = myClient.Post(searchURL.Uri.ToString(), content);
                if (respMsg == null)
                {
                    return;
                }
                string outStr = respMsg.Content.ReadAsStringAsync().Result;
            }

            // Updating sharing for item
            searchURL.Path = "sharing/rest/content/users/" + userName + "/items/" + itemId + "/share";
            postData.Clear();
            postData.Add(new KeyValuePair <string, string>("f", "json"));
            postData.Add(new KeyValuePair <string, string>("everyone", "true"));
            postData.Add(new KeyValuePair <string, string>("groups", "a4474cec000e46869a9980930c7c9bd0"));
            using (HttpContent content = new FormUrlEncodedContent(postData))
            {
                EsriHttpResponseMessage respMsg = myClient.Post(searchURL.Uri.ToString(), content);
                if (respMsg == null)
                {
                    return;
                }
                string outStr = respMsg.Content.ReadAsStringAsync().Result;
            }
        }
        /// <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>
        /// 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
        }
        // 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>
        /// Execute the query command to get these info:
        /// 1. basic portal info;
        /// 2. advanced portal self calls;
        /// 3. fed server and registered ds.
        /// </summary>
        private async void CmdDoQuery()
        {
            #region setup
            ArcGISPortal arcGISportal = ArcGISPortalManager.Current.GetActivePortal();
            if (arcGISportal == null)
            {
                return;
            }
            if (!arcGISportal.IsSignedOn())
            {
                //Calling "SignIn" will trigger the OAuth popup if your credentials are
                //not cached (eg from a previous sign in in the session)
                await QueuedTask.Run(() =>
                {
                    SignInResult result = arcGISportal.SignIn();
                    if (result.success)
                    {
                        envFailure = false;
                    }
                    else
                    {
                        envFailure = true;
                    }
                });
            }            //fill in username and password manually
            #endregion

            #region portal basic info
            var online = ArcGISPortalManager.Current.GetPortal(new Uri(_portalUrl));

            //print out portal info
            StringBuilder out_str = new StringBuilder();
            out_str.AppendLine("Portal URL: " + arcGISportal.PortalUri);
            out_str.AppendLine("User name: " + arcGISportal.GetSignOnUsername());
            #endregion

            /*
             * the following calls are only present for portals; For online, just print the info generated above.
             */
            if (!_portalUrl.Contains("arcgis.com"))
            {
                //get web adaptor
                string wa = arcGISportal.PortalUri.Segments[1];
                _portalUrl = arcGISportal.PortalUri.ToString();

                /*
                 * Make Portal self call to understand the current role - user, publisher or admin? and other portal info
                 */
                #region portal self call
                //get portal self call's response
                UriBuilder selfURL = new UriBuilder(new Uri(_portalUrl))
                {
                    Path  = wa + "sharing/rest/portals/self",
                    Query = "f=json"
                };
                EsriHttpResponseMessage response = new EsriHttpClient().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;
                }
                string   userRole        = portalSelf.user.role;
                string[] userPriviledges = portalSelf.user.privileges.ToObject <string[]>();

                if (portalSelf.isPortal == null)
                {
                    return;
                }
                string IsPortal = (bool)(portalSelf.isPortal) ? "True" : "False";

                if (portalSelf.supportsSceneServices == null)
                {
                    return;
                }
                string SupportsSceneServices = (bool)(portalSelf.supportsSceneServices) ? "True" : "False";

                if (portalSelf.helperServices == null)
                {
                    return;
                }

                var elevationService = portalSelf.helperServices.elevation;
                var routeService     = portalSelf.helperServices.route;

                out_str.AppendLine("User role: " + userRole);
                out_str.AppendLine("User Privileges:");
                userPriviledges.ToList().ForEach(i => out_str.Append("\t" + i));

                out_str.AppendLine();
                out_str.AppendLine("Supports Scene services? " + SupportsSceneServices);
                out_str.AppendLine("Is it a portal? " + IsPortal);
                out_str.AppendLine("Helper Services: (1) elevation: " + ((elevationService == null) ? "null" : elevationService.url) + "\t" +
                                   "(2) Route: " + ((routeService == null) ? "null" : routeService.url));
                #endregion

                /*
                 * Make rest calls to get the list of fed servers, signaling which is the hosting fed server;
                 * Also to print the registered data sources
                 */
                #region portal self server call
                selfURL = new UriBuilder(new Uri(_portalUrl))
                {
                    Path  = wa + "sharing/rest/portals/self/servers",
                    Query = "f=json"
                };
                response = new EsriHttpClient().Get(selfURL.Uri.ToString());

                dynamic portalSelf_servers = 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_servers == null)
                {
                    return;
                }
                out_str.AppendLine();
                out_str.AppendLine("Fed servers:");
                int cnt = 0;
                foreach (var server in portalSelf_servers.servers)
                {
                    out_str.Append("\t(" + (++cnt) + ") {" + server.url + ", " + server.adminUrl + ", " + server.serverRole + "}");

                    /*
                     * generate a new token from portal
                     * re-using old tokens would only yield empty item list for data sources
                     */
                    #region generate server token
                    ArcGISPortal arcGISportal_2 = ArcGISPortalManager.Current.GetActivePortal();
                    string       server_token   = arcGISportal_2.GetToken();
                    #endregion

                    /*
                     * get the registered data source from each server
                     */
                    #region data sources
                    string wa_2 = (new Uri(server.adminUrl.Value)).Segments[1];
                    //1. get registered shared folder
                    selfURL = new UriBuilder(new Uri(server.adminUrl.Value))
                    {
                        Path  = wa_2 + "/admin/data/findItems/",
                        Query = "f=json&parentPath=/fileShares&types=folder&token=" + server_token
                    };
                    response = new EsriHttpClient().Get(selfURL.Uri.ToString());

                    dynamic server_registeredFolder = 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 (server_registeredFolder == null)
                    {
                        return;
                    }
                    out_str.AppendLine();
                    out_str.AppendLine();
                    out_str.Append("Registered Folder:\t");
                    if (server_registeredFolder.items == null)
                    {
                        out_str.Append("\tRegistered Folder not accessible\t");
                    }
                    foreach (var item in server_registeredFolder.items)
                    {
                        out_str.Append("\t{" + item.type + " - " + item.info.path + "}");
                    }

                    //2. get registered shared egdb
                    selfURL = new UriBuilder(new Uri(server.adminUrl.Value))
                    {
                        Path  = wa_2 + "/admin/data/findItems/",
                        Query = "f=json&parentPath=enterpriseDatabases&types=egdb&token=" + server_token
                    };
                    response = new EsriHttpClient().Get(selfURL.Uri.ToString());

                    dynamic server_registeredDS = 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 (server_registeredDS == null)
                    {
                        return;
                    }
                    out_str.AppendLine();
                    out_str.AppendLine();
                    out_str.Append("Registered egdb:\t");
                    if (server_registeredDS.items == null)
                    {
                        out_str.Append("\tRegistered egdb not accessible\t");
                    }
                    foreach (var ds in server_registeredDS.items)
                    {
                        out_str.Append("\t{" + ds.type + " - " + ds.path + "}");
                    }

                    //3. get registered nosql
                    //query="f=json&parentPath=nosqlDatabases&types=nosql"
                    #endregion
                }
                #endregion
            }
            else
            {
                out_str.AppendLine();
                out_str.AppendLine($@"To see further Portal Info details you have to connect to a portal other then ArcGIS Online");
            }

            if (envFailure)
            {
                QueryResult = "Not able to sign into portal!\n\n" + out_str.ToString();
            }
            else
            {
                QueryResult = "Successfully signed into portal\n\n" + out_str.ToString();
            }

            System.Diagnostics.Debug.WriteLine(QueryResult);
        }
   /// <summary>
   /// Uploads a local item to online with its parameters
   /// </summary>
   /// <param name="baseURI"></param>
   /// <param name="itemPathStr"></param>
   /// <param name="thumbnail"></param>
   /// <param name="tags"></param>
   /// <returns></returns>
   Tuple<bool, string> uploadItem(string baseURI, string itemPathStr, string thumbnail, String tags)
   {
       String[] tags_arr = tags.Split(new Char[] { ',', ':', '\t' });
 
       EsriHttpClient myClient = new EsriHttpClient();
       Tuple<bool, string> response = null;
       Item itemToUpload = ItemFactory.Create(itemPathStr);
       if (itemToUpload != null)
       {
           response = myClient.Upload(baseURI, itemToUpload, thumbnail, tags_arr);
           if (response.Item1)
           {
               Tuple<bool, SDCItem> result = SearchPortalItemREST(itemToUpload.Name, itemToUpload.Type, baseURI);
               if(result.Item1)
                   return new Tuple<bool, string>(true, result.Item2.id);
               else
                   return new Tuple<bool, string>(true,"Cannot find item online");
           }
           else
               return new Tuple<bool, String>(false, "Upload fails - " + response.Item2);
       }else
           return new Tuple<bool, String>(false, "Null item cannot be uploaded - " + response.Item2);
   }