Beispiel #1
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);
            }
        }
Beispiel #2
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
        }
        /// <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>tuple: bool ok/failed string: result msg/error msg</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;
            //De-serialize the response in JSON into a usable object.
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            //De-serialize the response in JSON into a usable object.
            SharingContracts.PublishedServices obj = (SharingContracts.PublishedServices)serializer.Deserialize(outStr, typeof(SharingContracts.PublishedServices));
            if (obj?.services == null)
            {
                return(new Tuple <bool, String>(false, "Service creation fails - " + outStr));
            }

            string respReturn = "";

            foreach (SharingContracts.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));
            }
        }
        /// <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;
            //De-serialize the response in JSON into a usable object.
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            //De-serialize the response in JSON into a usable object.
            SharingContracts.AnalyzedService obj = (SharingContracts.AnalyzedService)serializer.Deserialize(outStr, typeof(SharingContracts.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>
        /// 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));
        }
        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);
        }
        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);
        }
Beispiel #8
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());
        }
Beispiel #9
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;
            }
        }
        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");
        }