protected override Task <bool> OnSketchCompleteAsync(Geometry geometry) { System.Diagnostics.Debug.WriteLine("Map tool sketch complete"); //TODO blog about creating ViewModel static instance var so we can call it from codebehind MapView mapView = MapView.Active; //Task task = VehiclesPaneViewModel.instance.PerformAnalysis(geometry as MapPoint, mapView); ProgressorSource ps = new ProgressorSource("Running the drive distance analysis..."); QueuedTask.Run(() => VehiclesPaneViewModel.Instance.PerformAnalysis(geometry as MapPoint, mapView, ps), ps.Progressor); //Task<dynamic> saResult = QueuedTask.Run(() => { // return VehiclesPaneViewModel.instance.PerformAnalysis(geometry as MapPoint); //}); //saResult.Wait(); //// Add a graphics overlay //IDisposable overlay = AddOverlay() //// Add graphics return(base.OnSketchCompleteAsync(geometry)); }
protected override async void OnClick() { //If you run this in the DEBUGGER you will NOT see the dialog var ps = new ProgressorSource("Doing my thing..."); ps.Max = 5; await ProgressDialogModule.RunProgress(ps, 5); }
public static Task RunProgressWithoutBlockingTheCIM(ProgressorSource ps, int howLongInSeconds) { //simulate doing some work return(QueuedTask.Run((Action)(async() => { //Here we do NOT block the CIM but... // //this is probably unrealistic in most cases - that is //we await on the CIM so it can do something else //while our Task completes.... but, it is shown for completeness // await Task.Delay(howLongInSeconds * 1000); }), ps.Progressor)); }
public static Task RunProgressWithoutBlockingTheCIM(ProgressorSource ps, int howLongInSeconds) { //simulate doing some work return QueuedTask.Run((Action)(async () => { //Here we do NOT block the CIM but... // //this is probably unrealistic in most cases - that is //we await on the CIM so it can do something else //while our Task completes.... but, it is shown for completeness // await Task.Delay(howLongInSeconds * 1000); }), ps.Progressor); }
private async Task RemoveAllGraphics() { var ps = new ProgressorSource("Check and remove graphic..."); if (this.CurrentGraphicList != null && this.CurrentGraphicList.Count > 0) { int totalGraphic = this.CurrentGraphicList.Count; for (int i = totalGraphic - 1; i > -1; i--) { this.CurrentGraphicList[i].Dispose(); } this.CurrentGraphicList = new List <IDisposable>(); } this.GeodesicAreaInfo = "Graphic Area:"; await QueuedTask.Run(() => Task.Delay(1000).Wait(), ps.Progressor); //Lets give garbage collector 1 sec. }
public async void CalculateVolume() { // Update the viewmodel with values await FrameworkApplication.SetCurrentToolAsync("esri_mapping_exploreTool"); // Check for an active mapview if (MapView.Active == null) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("No MapView currently active. Exiting...", "Info"); return; } // Prompt before proceeding with calculation work var response = ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Save edits and calculate volume on selected features?", "Calculate Volume", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question); if (response == MessageBoxResult.No) { return; } // Save edits for reading by GP Tool await Project.Current.SaveEditsAsync(); try { await QueuedTask.Run((Func <Task>)(async() => { var featLayer = MapView.Active.Map.FindLayers("Clip_Polygon_Asphalt").FirstOrDefault() as FeatureLayer; // Get the selected records, and check/exit if there are none: var featSelectionOIDs = featLayer.GetSelection().GetObjectIDs(); if (featSelectionOIDs.Count == 0) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("No records selected for layer, " + featLayer.Name + ". Exiting...", "Info"); return; } // Ensure value for reference plane direction combobox else if (SceneCalcVM.ReferencePlaneDirection == string.Empty) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Choose the reference plane direction for volume calculation. Exiting...", "Value Needed"); return; } // Ensure there is a valid reference plane height/elevation value for all selected records RowCursor cursorPolygons = featLayer.GetSelection().Search(null); while (cursorPolygons.MoveNext()) { using (Row currentRow = cursorPolygons.Current) { // Get values for dockpane if (currentRow["PlaneHeight"] == null || Convert.ToDouble(currentRow["PlaneHeight"]) == 0) { string currentObjectID = Convert.ToString(currentRow["ObjectID"]); ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Empty or invalid Plane Height value for polygon ObjectID: " + currentObjectID + ". Exiting...", "Value Needed"); return; } } } // Get the name of the attribute to update, and the value to set: double refPlaneElevation = SceneCalcVM.ReferencePlaneElevation; string refPlaneDirection = SceneCalcVM.ReferencePlaneDirection; // Start progress dialog var progDialog = new ProgressDialog("Calculating Volume"); var progSource = new ProgressorSource(progDialog); progDialog.Show(); // Prepare for run of GP tool -- Get the path to the LAS point layer string surfaceLASDataset = "Asphalt3D_132_point_cloud.las"; var inspector = new ArcGIS.Desktop.Editing.Attributes.Inspector(true); inspector.Load(featLayer, featSelectionOIDs); inspector["PlaneDirection"] = refPlaneDirection; inspector["DateOfCapture"] = DateTime.Today; inspector["ElevationMeshFile"] = "Asphalt3D_132_3d_mesh.slpk"; inspector["PointCloudFile"] = surfaceLASDataset; var editOp = new EditOperation(); editOp.Name = "Edit " + featLayer.Name + ", " + Convert.ToString(featSelectionOIDs.Count) + " records."; editOp.Modify(inspector); await editOp.ExecuteAsync(); await Project.Current.SaveEditsAsync(); // Get the path to the layer's feature class string infc = featLayer.Name; // Place parameters into an array var parameters = Geoprocessing.MakeValueArray(surfaceLASDataset, infc, "PlaneHeight", refPlaneDirection); // Place environment settings in an array, in this case, OK to over-write var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true); // Execute the GP tool with parameters var gpResult = await Geoprocessing.ExecuteToolAsync("PolygonVolume_3d", parameters, environments); // Save edits again await Project.Current.SaveEditsAsync(); // var selFeatures = featLayer.GetSelection().GetCount(); RowCursor cursorPolygons2 = featLayer.GetSelection().Search(null); double totalVolumeValue = 0; double totalAreaValue = 0; double totalWeightInTons = 0; double currentVolume; double currentSArea; double currentWeightInTons; long currentOID; while (cursorPolygons2.MoveNext()) { using (Row currentRow = cursorPolygons2.Current) { // Get values for dockpane currentOID = currentRow.GetObjectID(); // Convert volume in cubic meters from source data to cubic feet: currentVolume = Convert.ToDouble(currentRow["Volume"]) * 35.3147; // Convert surface area value from square meters from source data to square feet: currentSArea = Convert.ToDouble(currentRow["SArea"]) * 10.7639; // Calculate estimated weight in tons = (volume in square foot * 103.7 pounds per square foot) / 2000 pounds per ton currentWeightInTons = (currentVolume * 103.7) / 2000; // Update the new cubic feet and square feet values for the feature: inspector.Load(featLayer, currentOID); inspector["Volume"] = currentVolume; inspector["SArea"] = currentSArea; inspector["EstWeightInTons"] = currentWeightInTons; await inspector.ApplyAsync(); // Combine values for display of total volume and surface area values in the dockpane: totalVolumeValue = totalVolumeValue + currentVolume; totalAreaValue = totalAreaValue + currentSArea; totalWeightInTons = totalWeightInTons + currentWeightInTons; } } // Apply the values and refresh selection update await Project.Current.SaveEditsAsync(); FeatureSelectionChanged(); // Close progress dialog progDialog.Hide(); progDialog.Dispose(); })); } catch (Exception exc) { // Catch any exception found and display a message box. ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to perform update: " + exc.Message); return; } }
public static Task RunProgress(ProgressorSource ps, int howLongInSeconds) { //simulate doing some work //I block the CIM to simulate it being busy return(QueuedTask.Run(() => Task.Delay(howLongInSeconds * 1000).Wait(), ps.Progressor)); }
internal async Task PerformAnalysis(MapPoint ptStartLoc, MapView mapView, ProgressorSource ps) { ps.Progressor.Message = "Running the analysis..."; ps.Progressor.Status = "Gathering and verifying parameter data"; string sReqUrl = Properties.Settings.Default.QryPointToState; string sReq = String.Format("{0}?returnGeometry=false&returnDistinctValues=false&geometry={1}&geometryType=esriGeometryPoint&f=json&outFields=*&spatialRel=esriSpatialRelIntersects", sReqUrl, ptStartLoc.ToJson()); // Find out what state the user clicked; or report an error if outside the U.S. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sReq); string sResp; try { using (StreamReader sread = new StreamReader(req.GetResponse().GetResponseStream())) sResp = sread.ReadToEnd(); } catch (Exception e) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Error mapping the chosen spot to a petroleum area district in the U.S.A.: " + e.Message); return; } dynamic respPADDState = JsonConvert.DeserializeObject(sResp); try { string sState = respPADDState.features[0].attributes.STATE.ToString(); // Find out what PADD zone the state is in SelectedPADDZone = PaddStateToZone[sState]; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Exception getting PADD for chosen spot: " + e.Message); ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Please choose a spot within the U.S.A."); return /*null*/; } // Find out the gallons/$1.00 in that PADD zone double nFuelCost = PADDZoneToFuelCost[SelectedPADDZone]; // Find out the miles per dollar each vehicle: (mi / gal) / (dollars / gal) // Map is in meters, so convert miles to meters Vehicle[] orderedVehicles = SelectedVehicles.OrderBy(vehicle => vehicle.Mpg).ToArray <Vehicle>(); IEnumerable <double> vehicleMetersPerDollar = orderedVehicles.Select(vehicle => (vehicle.MetersPerGallon) / nFuelCost); string sDistsParam = String.Join(" ", vehicleMetersPerDollar.ToArray()); MapPoint ptStartLocNoZ = await QueuedTask.Run(() => { MapPoint ptNoZ = MapPointBuilder.CreateMapPoint(ptStartLoc.X, ptStartLoc.Y, ptStartLoc.SpatialReference); return(ptNoZ); }); // No corresponding type for the needed GPFeatureRecordSetLayer parameter string sStartGeom = ptStartLocNoZ.ToJson(); string sStartLocParam = "{\"geometryType\":\"esriGeometryPoint\",\"features\":[{\"geometry\":" + sStartGeom + "}]}"; // Run the query ps.Progressor.Status = "Executing the analysis"; string sGPUrl = Properties.Settings.Default.GPFindSA; sGPUrl += String.Format("?Distances={0}&Start_Location={1}&f=json", sDistsParam, sStartLocParam); HttpWebRequest reqSA = (HttpWebRequest)WebRequest.Create(sGPUrl); HttpWebResponse wr; try { wr = (HttpWebResponse)reqSA.GetResponse(); if (wr.StatusCode != HttpStatusCode.OK) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Error running analysis: " + wr.StatusDescription); return; } } catch (WebException e) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Error running analysis: " + e.Message); return; } // Show the results ps.Progressor.Status = "Processing the results"; using (StreamReader sread = new StreamReader(wr.GetResponseStream())) sResp = sread.ReadToEnd(); JObject respAnalysis = JObject.Parse(sResp); JArray feats = respAnalysis["results"][0]["value"]["features"] as JArray; // Rectify results and order so that largest polygon can be added to the map first List <JToken> aryResFeats = RectifyResults(feats, orderedVehicles); int iSR = respAnalysis["results"][0]["value"]["spatialReference"]["wkid"].ToObject <Int32>(); SpatialReference sr = await QueuedTask.Run <SpatialReference>(() => { SpatialReference srTemp = SpatialReferenceBuilder.CreateSpatialReference(iSR); return(srTemp); }); /*lock (_lockResults)*/ Results.ClearResults(); // Iterate backwards to add larger polygons behind smaller ones for (int iVeh = orderedVehicles.Count() - 1; iVeh >= 0; iVeh--) { Result result = new Result(orderedVehicles[iVeh]); Polygon poly = null; IDisposable graphic = null; // Compute color for this result float multiplier = aryResFeats.Count > 1 ? ((float)iVeh) / ((float)(aryResFeats.Count - 1)) : 0; byte red = (byte)(255 - (255 * multiplier)); byte green = (byte)(255 * multiplier); Color color = Color.FromRgb(red, green, 0); result.Color = color.ToString(); result.PaddZone = SelectedPADDZone; result.DollarsPerGallon = nFuelCost; string sGeom = aryResFeats[iVeh]["geometry"].ToString(); poly = await QueuedTask.Run(() => { Polygon polyNoSR = PolygonBuilder.FromJson(sGeom); return(PolygonBuilder.CreatePolygon(polyNoSR, sr)); }); CIMStroke outline = SymbolFactory.ConstructStroke(ColorFactory.BlackRGB, 1.0, SimpleLineStyle.Solid); CIMPolygonSymbol symPoly = SymbolFactory.ConstructPolygonSymbol( ColorFactory.CreateRGBColor(color.R, color.G, color.B, RESULT_OPACITY_PCT), SimpleFillStyle.Solid, outline); CIMSymbolReference sym = symPoly.MakeSymbolReference(); CIMSymbolReference symDef = SymbolFactory.DefaultPolygonSymbol.MakeSymbolReference(); graphic = await QueuedTask.Run(() => { return(mapView.AddOverlay(poly, sym)); }); result.DriveServiceArea = poly; result.DriveServiceAreaGraphic = graphic; result.DriveDistM = aryResFeats[iVeh]["attributes"]["ToBreak"].Value <double>(); /*lock (_lockResults)*/ Results.Add(result); } }
public static Task RunProgress(ProgressorSource ps, int howLongInSeconds) { //simulate doing some work //I block the CIM to simulate it being busy return QueuedTask.Run(() => Task.Delay(howLongInSeconds*1000).Wait(), ps.Progressor); }
protected override async Task <bool> OnSketchCompleteAsync(Geometry geometry) { // Get nearest point if within tolerance; or report no feature found nearby click location MapView mv = MapView.Active; try { bool identifyResult = await QueuedTask.Run(() => { //List<Attachment> lstAllAttachments = new List<Attachment>(); List <ImageAttachment> lstImageAttachments = new List <ImageAttachment>(); Dictionary <BasicFeatureLayer, List <long> > feats = null; try { feats = mv.GetFeatures(geometry); } catch (Exception e) { MessageBox.Show("Couldn't get features at that location: " + e.Message); return(false); } if (feats.Count <= 0) { MessageBox.Show("No features are there."); return(true); } foreach (BasicFeatureLayer bfl in feats.Keys) { List <long> featIds = new List <long>(); if (feats.TryGetValue(bfl, out featIds)) { // Get OID field name using (Table tbl = bfl.GetTable()) { string sOIDField = tbl.GetDefinition().GetObjectIDField(); string sFeatIds = String.Join(",", featIds); QueryFilter qf = new QueryFilter(); qf.WhereClause = sOIDField + " IN (" + sFeatIds + ")"; using (RowCursor cur = bfl.Search(qf)) { while (cur.MoveNext()) { Row row = cur.Current; IReadOnlyList <Attachment> attachments = row.GetAttachments(null, true); if (attachments.Count > 0) { // Only add jpegs to selection list foreach (Attachment attachment in attachments) { if (attachment.GetContentType() == System.Net.Mime.MediaTypeNames.Image.Jpeg) { lstImageAttachments.Add(new ImageAttachment(attachment, row)); } } } else { row.Dispose(); } } } } } } ImageAttachment selectedAttachment = null; // Open the attachment selection dialog if (lstImageAttachments.Count <= 0) // No results { MessageBox.Show("No images are attached to that feature."); } else if (lstImageAttachments.Count == 1) // Automatically open this result { selectedAttachment = lstImageAttachments[0]; } else // More than one result { ImageAttachmentListDialog dlg = new ImageAttachmentListDialog(lstImageAttachments); //dlg.Owner = FrameworkApplication.Current.MainWindow; bool?result = dlg.ShowDialog(); if (result ?? false) { selectedAttachment = dlg.SelectedItem; } } if (selectedAttachment != null) { // Open the panorama viewer ProgressorSource ps = new ProgressorSource("Loading...", false); QueuedTask.Run(() => { IReadOnlyList <Attachment> selectedSingleAttachmentList = selectedAttachment.Row.GetAttachments( new List <long> { selectedAttachment.Attachment.GetAttachmentID() }, false); MemoryStream memStream = selectedSingleAttachmentList[0].GetData(); FrameworkApplication.Current.Dispatcher.Invoke(() => { MainWindow mw = new MainWindow(); mw.Show(); mw.Activate(); mw.Topmost = true; // important MainViewModel mvm = (MainViewModel)mw.DataContext; mvm.Open(memStream); }); }, ps.Progressor); } return(true); }); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.StackTrace); } return(true); }