public async Task <PolygonGeometry> ProjectPolygon(string token, string inSR, string outSR, PolygonGeometry geometry) { var queryUrl = $"{getRestServiceEndpoint()}/project"; var payLoadModel = new ArcGISProjectPolygonGeometryParam(new PolygonGeometry[] { geometry }); var encodedContent = new ArcGISEncodedContent { { "f", responseFormat }, { "token", token }, { "inSR", inSR }, { "outSR", outSR }, { "geometries", JsonConvert.SerializeObject(payLoadModel).TrimJsonRequest() } }; var resp = await ArcGISHttpClient.PostAsync(queryUrl, encodedContent.ToStringUrlEncodedContent()); var respStr = await resp.Content.ReadAsStringAsync(); if (resp.StatusCode != HttpStatusCode.OK) { throw new ArcGISInvalidResponseException($"Unsuccessfull. \n" + $"Response Code: {resp.StatusCode}\n" + $"Response: {respStr}" + $"Query String: {queryUrl}"); } var model = JsonConvert.DeserializeObject <ArcGISProjectPolygonResponse>(respStr); return(model.geometries.FirstOrDefault()); }
public async Task <ArcGISAuthToken> GetToken() { try { string reqUrl = getAuthRequestUrl(); HttpResponseMessage resp = await ArcGISHttpClient.PostAsync(reqUrl, null); string str = await resp.Content.ReadAsStringAsync(); if (resp.StatusCode != System.Net.HttpStatusCode.OK) { throw new ArcGISAuthException($"Unsuccessfull " + $"Username: {username}, StatusCode: {resp.StatusCode}, " + $"Response Returned: {str}"); } var model = JsonConvert.DeserializeObject <ArcGISAuthToken>(str); return(model); } catch (System.Exception ex) { throw new ArcGISAuthException($"{ex.Message}", ex); } }
/// <summary> /// Downloads and saved geodatabase from given Uri to the device. /// </summary> /// <param name="task">Task used.</param> /// <param name="uriToGeodatabase">Uri to geodabase that is downloaded.</param> /// <param name="locationForGeodatabase">Full file path, where geodatabase is downloaded.</param> /// <param name="geodatabaseName">Name for the geodatabase. This is the name that is used when it is saved to the device.</param> /// <returns>Returns after download is fully completed.</returns> /// <remarks>If target folder doesn't exists, it is created.</remarks> public static async Task DownloadGeodatabaseAsync( this GeodatabaseSyncTask task, Uri uriToGeodatabase, string locationForGeodatabase, string geodatabaseName) { var client = new ArcGISHttpClient(); var gdbStream = client.GetOrPostAsync(uriToGeodatabase, null); var geodatabasePath = Path.Combine(locationForGeodatabase, geodatabaseName); if (!Directory.Exists(locationForGeodatabase)) { Directory.CreateDirectory(locationForGeodatabase); } await Task.Factory.StartNew(async () => { using (var stream = File.Create(geodatabasePath)) { await gdbStream.Result.Content.CopyToAsync(stream); } }); }
// provide a callback to execute when the GeodatabaseSyncTask completes (successfully or with an exception) private async void GdbCompleteCallback(Esri.ArcGISRuntime.Tasks.Offline.GeodatabaseStatusInfo statusInfo, Exception ex) { // if unsuccessful, report the exception and return if (ex != null) { Console.WriteLine("An exception occured: " + ex.Message); //this.ReportStatus("An exception occured: " + ex.Message); return; } // if successful, read the generated geodatabase from the server var client = new ArcGISHttpClient(); var gdbStream = client.GetOrPostAsync(statusInfo.ResultUri, null); var geodatabasePath = System.IO.Path.Combine(@"C:\Temp\10_2_7Demo", "WildlifeLocal.geodatabase"); // create a local path for the geodatabase, if it doesn't already exist if (!System.IO.Directory.Exists(@"C:\Temp\10_2_7Demo")) { System.IO.Directory.CreateDirectory(@"C:\Temp\10_2_7Demo"); } // write geodatabase to local location await Task.Factory.StartNew(async delegate { using (var stream = System.IO.File.Create(geodatabasePath)) { await gdbStream.Result.Content.CopyToAsync(stream); } MessageBox.Show("Offline database created at " + geodatabasePath); }); }
// provide a callback to execute when the GeodatabaseSyncTask completes (successfully or with an exception) private async void GdbCompleteCallback(Esri.ArcGISRuntime.Tasks.Offline.GeodatabaseStatusInfo statusInfo, Exception ex) { // if unsuccessful, report the exception and return if (ex != null) { this.Dispatcher.Invoke(() => this.SyncStatusTextBlock.Text = "An exception occured: " + ex.Message); return; } // if successful, read the generated geodatabase from the server var client = new ArcGISHttpClient(); var gdbStream = client.GetOrPostAsync(statusInfo.ResultUri, null); var geodatabasePath = System.IO.Path.Combine(@"C:\Temp\Cache", "PoiLocal.geodatabase"); // create a local path for the geodatabase, if it doesn't already exist if (!System.IO.Directory.Exists(@"C:\Temp\Cache")) { System.IO.Directory.CreateDirectory(@"C:\Temp\Cache"); } await Task.Factory.StartNew(async delegate { using (var stream = System.IO.File.Create(geodatabasePath)) { await gdbStream.Result.Content.CopyToAsync(stream); } this.Dispatcher.Invoke(() => this.LocalDataPathTextBlock.Text = geodatabasePath); this.Dispatcher.Invoke(() => this.SyncProgressBar.Visibility = System.Windows.Visibility.Hidden); this.Dispatcher.Invoke(() => this.SyncStatusPanel.Visibility = System.Windows.Visibility.Collapsed); this.Dispatcher.Invoke(() => this.UseLocalDataOption.IsEnabled = true); }); }
// Batch Geocode private async void Button_Click(object sender, RoutedEventArgs e) { try { progress.Visibility = Visibility.Visible; _graphicsOverlay.Graphics.Clear(); MyMapView.Overlays.Items.Clear(); string records = string.Join(",", SourceAddresses.Where(s => !string.IsNullOrWhiteSpace(s.Address)) .Select((s, idx) => string.Format("{{ \"attributes\": {{ \"OBJECTID\": {0}, \"SingleLine\": \"{1}\" }} }}", idx, s.Address)) .ToArray()); string addresses = string.Format("{{ \"records\": [ {0} ] }}", records); Dictionary <string, string> parameters = new Dictionary <string, string>(); parameters["f"] = "json"; parameters["outSR"] = MyMapView.SpatialReference.Wkid.ToString(); parameters["addresses"] = addresses; ArcGISHttpClient httpClient = new ArcGISHttpClient(); var response = await httpClient.GetOrPostAsync(GEOCODE_SERVICE_URL, parameters); var jsonResults = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync(); var mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonResults)); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GeocodeResults)); var results = serializer.ReadObject(mStream) as GeocodeResults; foreach (var candidate in results.locations) { var location = candidate.location; MapPoint point = new MapPoint(Convert.ToDouble(location.x), Convert.ToDouble(location.y), MyMapView.SpatialReference); _graphicsOverlay.Graphics.Add(new Graphic(point)); // Create a new templated overlay for the geocoded address var overlay = new ContentControl() { HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top }; overlay.Template = layoutGrid.Resources["MapTipTemplate"] as ControlTemplate; overlay.DataContext = candidate.attributes; MapView.SetViewOverlayAnchor(overlay, point); MyMapView.Overlays.Items.Add(overlay); } await MyMapView.SetViewAsync(GeometryEngine.Union(_graphicsOverlay.Graphics.Select(g => g.Geometry)).Extent.Expand(1.5)); } catch (Exception ex) { var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync(); } finally { progress.Visibility = Visibility.Collapsed; AddressFlyout.Hide(); } }
// Batch Geocode private async void Button_Click(object sender, RoutedEventArgs e) { try { progress.Visibility = Visibility.Visible; graphicsLayer.Graphics.Clear(); mapView.Overlays.Clear(); JavaScriptSerializer serializer = new JavaScriptSerializer(); string records = string.Join(",", SourceAddresses.Where(s => !string.IsNullOrWhiteSpace(s.Address)) .Select((s, idx) => string.Format("{{ \"attributes\": {{ \"OBJECTID\": {0}, \"SingleLine\": \"{1}\" }} }}", idx, s.Address)) .ToArray()); string addresses = string.Format("{{ \"records\": [ {0} ] }}", records); Dictionary <string, string> parameters = new Dictionary <string, string>(); parameters["f"] = "json"; parameters["outSR"] = mapView.SpatialReference.Wkid.ToString(); parameters["addresses"] = addresses; ArcGISHttpClient httpClient = new ArcGISHttpClient(); var response = await httpClient.GetOrPostAsync(GEOCODE_SERVICE_URL, parameters); var jsonResults = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync(); var results = serializer.Deserialize <Dictionary <string, object> >(jsonResults); var candidates = results["locations"] as ArrayList; foreach (var candidate in candidates.OfType <Dictionary <string, object> >()) { var location = candidate["location"] as Dictionary <string, object>; MapPoint point = new MapPoint(Convert.ToDouble(location["x"]), Convert.ToDouble(location["y"]), mapView.SpatialReference); graphicsLayer.Graphics.Add(new Graphic(point)); // Create a new templated overlay for the geocoded address var overlay = new ContentControl() { HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top }; overlay.Template = layoutGrid.Resources["MapTipTemplate"] as ControlTemplate; overlay.DataContext = candidate["attributes"] as Dictionary <string, object>; MapView.SetMapOverlayAnchor(overlay, point); mapView.Overlays.Add(overlay); } await mapView.SetViewAsync(GeometryEngine.Union(graphicsLayer.Graphics.Select(g => g.Geometry)).Extent.Expand(1.5)); } catch (Exception ex) { MessageBox.Show(ex.Message, "Sample Error"); } finally { progress.Visibility = Visibility.Collapsed; } }
// Batch Geocode private async void Button_Click(object sender, RoutedEventArgs e) { try { progress.Visibility = Visibility.Visible; _graphicsOverlay.Graphics.Clear(); MyMapView.Overlays.Items.Clear(); string records = string.Join(",", SourceAddresses.Where(s => !string.IsNullOrWhiteSpace(s.Address)) .Select((s, idx) => string.Format("{{ \"attributes\": {{ \"OBJECTID\": {0}, \"SingleLine\": \"{1}\" }} }}", idx, s.Address)) .ToArray()); string addresses = string.Format("{{ \"records\": [ {0} ] }}", records); Dictionary<string, string> parameters = new Dictionary<string, string>(); parameters["f"] = "json"; parameters["outSR"] = MyMapView.SpatialReference.Wkid.ToString(); parameters["addresses"] = addresses; ArcGISHttpClient httpClient = new ArcGISHttpClient(); var response = await httpClient.GetOrPostAsync(GEOCODE_SERVICE_URL, parameters); var jsonResults = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync(); var mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonResults)); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GeocodeResults)); var results = serializer.ReadObject(mStream) as GeocodeResults; foreach (var candidate in results.locations) { var location = candidate.location; MapPoint point = new MapPoint(Convert.ToDouble(location.x), Convert.ToDouble(location.y), MyMapView.SpatialReference); _graphicsOverlay.Graphics.Add(new Graphic(point)); // Create a new templated overlay for the geocoded address var overlay = new ContentControl() { HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top }; overlay.Template = layoutGrid.Resources["MapTipTemplate"] as ControlTemplate; overlay.DataContext = candidate.attributes; MapView.SetViewOverlayAnchor(overlay, point); MyMapView.Overlays.Items.Add(overlay); } await MyMapView.SetViewAsync(GeometryEngine.Union(_graphicsOverlay.Graphics.Select(g => g.Geometry)).Extent.Expand(1.5)); } catch (Exception ex) { var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync(); } finally { progress.Visibility = Visibility.Collapsed; AddressFlyout.Hide(); } }
// Batch Geocode private async void Button_Click(object sender, RoutedEventArgs e) { try { progress.Visibility = Visibility.Visible; graphicsLayer.Graphics.Clear(); mapView.Overlays.Clear(); JavaScriptSerializer serializer = new JavaScriptSerializer(); string records = string.Join(",", SourceAddresses.Where(s => !string.IsNullOrWhiteSpace(s.Address)) .Select((s,idx) => string.Format("{{ \"attributes\": {{ \"OBJECTID\": {0}, \"SingleLine\": \"{1}\" }} }}", idx, s.Address)) .ToArray()); string addresses = string.Format("{{ \"records\": [ {0} ] }}", records); Dictionary<string, string> parameters = new Dictionary<string, string>(); parameters["f"] = "json"; parameters["outSR"] = mapView.SpatialReference.Wkid.ToString(); parameters["addresses"] = addresses; ArcGISHttpClient httpClient = new ArcGISHttpClient(); var response = await httpClient.GetOrPostAsync(GEOCODE_SERVICE_URL, parameters); var jsonResults = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync(); var results = serializer.Deserialize<Dictionary<string, object>>(jsonResults); var candidates = results["locations"] as ArrayList; foreach (var candidate in candidates.OfType<Dictionary<string, object>>()) { var location = candidate["location"] as Dictionary<string, object>; MapPoint point = new MapPoint(Convert.ToDouble(location["x"]), Convert.ToDouble(location["y"]), mapView.SpatialReference); graphicsLayer.Graphics.Add(new Graphic(point)); // Create a new templated overlay for the geocoded address var overlay = new ContentControl() { HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top }; overlay.Template = layoutGrid.Resources["MapTipTemplate"] as ControlTemplate; overlay.DataContext = candidate["attributes"] as Dictionary<string, object>; MapView.SetMapOverlayAnchor(overlay, point); mapView.Overlays.Add(overlay); } await mapView.SetViewAsync(GeometryEngine.Union(graphicsLayer.Graphics.Select(g => g.Geometry)).Extent.Expand(1.5)); } catch (Exception ex) { MessageBox.Show(ex.Message, "Sample Error"); } finally { progress.Visibility = Visibility.Collapsed; } }
// Download a generated geodatabase file private async Task <StorageFile> DownloadGeodatabase(GeodatabaseStatusInfo statusResult) { var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(GDB_NAME, CreationCollisionOption.ReplaceExisting); var client = new ArcGISHttpClient(); var download = await client.GetOrPostAsync(statusResult.ResultUri, null); using (var fileStream = await file.OpenStreamForWriteAsync()) { await download.EnsureSuccessStatusCode().Content.CopyToAsync(fileStream); } return(file); }
// Download a generated geodatabase file private async Task <StorageFile> DownloadGeodatabaseAsync(GeodatabaseStatusInfo statusResult) { var file = await GetGeodatabaseFileAsync(); var client = new ArcGISHttpClient(); var download = await client.GetOrPostAsync(statusResult.ResultUri, null); using (var fileStream = await file.OpenStreamForWriteAsync()) { await download.EnsureSuccessStatusCode().Content.CopyToAsync(fileStream); } return(file); }
// Download a generated geodatabase file private async Task DownloadGeodatabaseAsync(GeodatabaseStatusInfo statusResult) { var client = new ArcGISHttpClient(); var gdbStream = client.GetOrPostAsync(statusResult.ResultUri, null); SetGeodatabaseFileName(); await Task.Run(async() => { using (var stream = System.IO.File.Create(_gdbPath)) { await gdbStream.Result.Content.CopyToAsync(stream); } }); }
private async void DownloadGeodatabase(string url) { Console.WriteLine("Download Started"); //Create an instance of ArcGISHttpClient var client = new ArcGISHttpClient(); var geodatabaseStream = client.GetOrPostAsync(url, null); //Path on disk where the geodatabase will be downloaded to var geodatabasePath = @"<Path to location on Disk>\name.geodatabase"; await Task.Factory.StartNew(async delegate { using (var stream = System.IO.File.Create(geodatabasePath)) { await geodatabaseStream.Result.Content.CopyToAsync(stream); Console.WriteLine("Download Complete"); AddFeatureLayerToMap(geodatabasePath); } }); }
public async Task <ArcGISAreaLengthResponse> CalculateAreasAndLengths(string token, string sr, EsriGeometryCalcType calculationType, EsriAreaUnit areaUnit, PolygonGeometry geometry, string lengthUnit = "") { string queryUrl = $"{getRestServiceEndpoint()}/areasAndLengths"; var areaUnitParam = new ArcGISCalculateAreasAndLengthAreaParam(areaUnit); PolygonGeometry[] polygonPayload = { geometry }; var encodedContent = new ArcGISEncodedContent { { "f", responseFormat }, { "token", token }, { "sr", sr }, { "lengthUnit", lengthUnit }, { "calculationType", calculationType.ToString() }, { "areaUnit", JsonConvert.SerializeObject(areaUnitParam).TrimJsonRequest() }, { "polygons", JsonConvert.SerializeObject(polygonPayload).TrimJsonRequest() } }; var resp = await ArcGISHttpClient.PostAsync(queryUrl, encodedContent.ToStringUrlEncodedContent()); var respStr = await resp.Content.ReadAsStringAsync(); if (resp.StatusCode != HttpStatusCode.OK) { throw new ArcGISInvalidResponseException($"Unsuccessfull. \n" + $"Response Code: {resp.StatusCode}\n" + $"Response: {respStr}" + $"Query String: {queryUrl}"); } var model = JsonConvert.DeserializeObject <ArcGISCalculateAreasAndLengthsResponse>(respStr); if (model.areas.Count > 1 || model.lengths.Count > 1) { throw new ArcGISUnexpectedResponseException("Returned response count greater than 1 or equal to 0"); } return(new ArcGISAreaLengthResponse(model.areas.FirstOrDefault(), model.lengths.FirstOrDefault())); }
// Download a generated geodatabase file private async Task <string> DownloadGeodatabase(GeodatabaseStatusInfo statusResult) { var client = new ArcGISHttpClient(); var gdbStream = client.GetOrPostAsync(statusResult.ResultUri, null); var gdbFolder = System.IO.Path.GetTempPath(); var gdbPath = System.IO.Path.Combine(gdbFolder, statusResult.GeodatabaseName); if (!System.IO.Directory.Exists(gdbFolder)) { System.IO.Directory.CreateDirectory(gdbFolder); } await Task.Run(async() => { using (var stream = System.IO.File.Create(gdbPath)) { await gdbStream.Result.Content.CopyToAsync(stream); } }); return(gdbPath); }
public async Task <ArcGISFeaturesLayerQueryResponse> QueryFeatureLayer(string token, int layerId, string[] outFields, string whereClause = "1=1") { var queryUrl = $"{this.getRestServiceEndpoint()}/{layerId}/query" + $"?token={token}" + $"&f={responseFormat}" + $"&outFields={string.Join(",", outFields)}" + $"&where={whereClause}"; var resp = await ArcGISHttpClient.PostAsync(queryUrl, null); var respStr = await resp.Content.ReadAsStringAsync(); if (resp.StatusCode != System.Net.HttpStatusCode.OK) { throw new ArcGISInvalidResponseException($"Unsuccessfull. \n" + $"Response Code: {resp.StatusCode}\n" + $"Response: {respStr}" + $"Query String: {queryUrl}"); } var model = JsonConvert.DeserializeObject <ArcGISFeaturesLayerQueryResponse>(respStr); return(model); }
// Download a generated geodatabase file private async Task<string> DownloadGeodatabase(GeodatabaseStatusInfo statusResult) { var client = new ArcGISHttpClient(); var gdbStream = client.GetOrPostAsync(statusResult.ResultUri, null); var gdbFolder = System.IO.Path.GetTempPath(); var gdbPath = System.IO.Path.Combine(gdbFolder, statusResult.GeodatabaseName); if (!System.IO.Directory.Exists(gdbFolder)) System.IO.Directory.CreateDirectory(gdbFolder); await Task.Run(async () => { using (var stream = System.IO.File.Create(gdbPath)) { await gdbStream.Result.Content.CopyToAsync(stream); } }); return gdbPath; }
// Download a generated geodatabase file private async Task DownloadGeodatabaseAsync(GeodatabaseStatusInfo statusResult) { var client = new ArcGISHttpClient(); var gdbStream = client.GetOrPostAsync(statusResult.ResultUri, null); SetGeodatabaseFileName(); await Task.Run(async () => { using (var stream = System.IO.File.Create(_gdbPath)) { await gdbStream.Result.Content.CopyToAsync(stream); } }); }
// Download a generated geodatabase file private async Task<StorageFile> DownloadGeodatabaseAsync(GeodatabaseStatusInfo statusResult) { var file = await GetGeodatabaseFileAsync(); var client = new ArcGISHttpClient(); var download = await client.GetOrPostAsync(statusResult.ResultUri, null); using (var fileStream = await file.OpenStreamForWriteAsync()) { await download.EnsureSuccessStatusCode().Content.CopyToAsync(fileStream); } return file; }
// Download a generated geodatabase file private async Task<string> DownloadGeodatabase(GeodatabaseStatusInfo statusResult, string gdbPath) { var client = new ArcGISHttpClient(); var gdbStream = client.GetOrPostAsync(statusResult.ResultUri, null); var gdbFolder = Path.GetDirectoryName(gdbPath); if (!Directory.Exists(gdbFolder)) Directory.CreateDirectory(gdbFolder); await Task.Factory.StartNew(async () => { using (var stream = File.Create(gdbPath)) { await gdbStream.Result.Content.CopyToAsync(stream); } }); return gdbPath; }
//await CreateReplica(url, layerNumList, thisExtent, gdbName, geodatabasePath, gdbExt,prog); private static async Task CreateReplica(string featureServiceUrl, IEnumerable<int> layerNumList, Geometry geometry, string gdbNameNoExt, string geodatabasePath, string gdbExt, IProgress<string> prog) { try { DateTime begin = DateTime.UtcNow; var generationProgress = new Progress<GeodatabaseStatusInfo>(); Int64 i = 0; generationProgress.ProgressChanged += (sender, s) => { i++; }; //setup parameters var geodatabaseSyncTask = new GeodatabaseSyncTask(new Uri(featureServiceUrl)); FeatureServiceInfo serviceInfo = await geodatabaseSyncTask.GetServiceInfoAsync(); var parameters = new GenerateGeodatabaseParameters(layerNumList, geometry) { GeodatabasePrefixName = gdbNameNoExt, OutSpatialReference = SpatialReferences.WebMercator, }; if (serviceInfo.SyncEnabled) { parameters.SyncModel = serviceInfo.SyncCapabilities.SupportsPerLayerSync ? SyncModel.PerLayer : SyncModel.PerGeodatabase; } //call extension method GeodatabaseStatusInfo resultInfo = await geodatabaseSyncTask.ExGenerateGeodatabaseAsync(parameters, new TimeSpan(0, 0, 2), generationProgress); // Download geodatabase only if generation was completed without errors. Other statuses that might be checked and handled are // GeodatabaseSyncStatus.Failed and GeodatabaseSyncStatus.CompletedWithErrors. if (resultInfo.Status != GeodatabaseSyncStatus.Completed) { Logger.Report(string.Format("Geodatabase: Generating geodatabase failed. Status = {0}.", resultInfo.Status), prog); return; } //Download database ... with no buffer Logger.Report("Geodatabase: Replica created, starting download.", prog); var client = new ArcGISHttpClient(); HttpResponseMessage gdbStream = await client.GetAsync(resultInfo.ResultUri, HttpCompletionOption.ResponseHeadersRead); using (FileStream stream = File.Create(geodatabasePath + "\\" + gdbNameNoExt + gdbExt)) { await gdbStream.Content.CopyToAsync(stream); await stream.FlushAsync(); } DateTime end = DateTime.UtcNow; Logger.Report("Measured time: " + (end - begin).TotalMilliseconds + " ms.", prog); } catch (Exception ex) { Debug.WriteLine(ex.Message); Debug.WriteLine(ex.ToString()); Console.WriteLine("CreateReplica Exception" + Environment.NewLine + ex.Message); } }
// Download a generated geodatabase file private async Task<string> DownloadGeodatabase(GeodatabaseStatusInfo statusResult, string gdbName) { var client = new ArcGISHttpClient(); var gdbStream = client.GetOrPostAsync(statusResult.ResultUri, null); var gdbPath = Path.GetFullPath(string.Format("{0}/{1}{2}", _exportMapPath, gdbName, OfflineMapItem.GeodatabaseFilenameExtension)); await Task.Factory.StartNew(async () => { using (var stream = File.Create(gdbPath)) { await gdbStream.Result.Content.CopyToAsync(stream); } }); return gdbPath; }
// Download a generated geodatabase file private async Task<StorageFile> DownloadGeodatabase(GeodatabaseStatusInfo statusResult) { var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(statusResult.GeodatabaseName, CreationCollisionOption.ReplaceExisting); var client = new ArcGISHttpClient(); var download = await client.GetOrPostAsync(statusResult.ResultUri, null); using (var fileStream = await file.OpenStreamForWriteAsync()) { await download.EnsureSuccessStatusCode().Content.CopyToAsync(fileStream); } return file; }
private async void GenerateFeatuersCompleteCallback(GeodatabaseStatusInfo statusInfo, Exception ex) { if(ex != null) { this.Dispatcher.Invoke(() => StatusMessagesList.Items.Add("An exception has occured: " + ex.Message)); return; } // if successful, download the generated geodatabase from the server var client = new ArcGISHttpClient(); var geodatabaseStream = client.GetOrPostAsync(statusInfo.ResultUri, null); // create a path for the local geodatabse var outFolder = System.AppDomain.CurrentDomain.BaseDirectory; var geodatabasePath = System.IO.Path.Combine(outFolder, "Wildlife.geodatabase"); await Task.Factory.StartNew(async delegate { using (var stream = System.IO.File.Create(geodatabasePath)) { await geodatabaseStream.Result.Content.CopyToAsync(stream); } this.localGeodatabasePath = geodatabasePath; this.Dispatcher.Invoke(() => LocalDataPathTextBlock.Text = geodatabasePath); this.Dispatcher.Invoke(() => LocalDataPathTextBlock.ToolTip = geodatabasePath); this.Dispatcher.Invoke(() => StatusMessagesList.Items.Add("Features downloaded to " + geodatabasePath)); this.Dispatcher.Invoke(() => StatusProgressBar.IsIndeterminate = false); }); }