protected override async Task <bool> OnSketchCompleteAsync(Geometry geometry) { //1 select features based on geometry System.Windows.Point bottomRight = new System.Windows.Point(); Dictionary <BasicFeatureLayer, List <long> > allfeatures = new Dictionary <BasicFeatureLayer, List <long> >(); await QueuedTask.Run(() => { allfeatures = ActiveMapView.SelectFeatures(geometry, SelectionCombinationMethod.New, false, false); }); //2 build a context menu with the layers and (re)select by user's layer-choice ShowContextMenu(bottomRight, allfeatures); //3 BasicFeatureLayer bfl = null; foreach (KeyValuePair <BasicFeatureLayer, List <long> > entry in allfeatures) { if (entry.Key.SelectionCount > 0) { bfl = entry.Key; } } return(true); }
private Task <Tuple <IDisposable, long> > AddFeatureToOverlay(MapViewMouseEventArgs e) { return(QueuedTask.Run(() => { double llx = e.ClientPoint.X - 3; double lly = e.ClientPoint.Y - 3; double urx = e.ClientPoint.X + 3; double ury = e.ClientPoint.Y + 3; EnvelopeBuilder envBuilder = new EnvelopeBuilder(ActiveMapView.ClientToMap(new Point(llx, lly)), ActiveMapView.ClientToMap(new Point(urx, ury))); MapPoint mp = ActiveMapView.ClientToMap(e.ClientPoint); var cursor = _trees.Search(new SpatialQueryFilter() { FilterGeometry = envBuilder.ToGeometry(), SpatialRelationship = SpatialRelationship.Intersects }); if (cursor.MoveNext()) { return new Tuple <IDisposable, long>( ActiveMapView.AddOverlay(ActiveMapView.ClientToMap(e.ClientPoint), _overlaySymbol.MakeSymbolReference()), cursor.Current.GetObjectID()); } //var select = _trees.Select(new SpatialQueryFilter() { // FilterGeometry = envBuilder.ToGeometry(), // SpatialRelationship = SpatialRelationship.Intersects //}); //if (select.GetCount() > 0) { // return ActiveMapView.AddOverlay(ActiveMapView.ClientToMap(e.ClientPoint), _overlaySymbol.MakeSymbolReference()); //} return new Tuple <IDisposable, long>(null, -1); })); }
/// <summary> /// Happens if the tool is activated. /// </summary> /// <param name="active"></param> /// <returns></returns> protected override Task OnToolActivateAsync(bool active) { // get the first selected raster layer var selectedRasterLayer = ActiveMapView.GetSelectedLayers().OfType <BasicRasterLayer>().FirstOrDefault(); QueuedTask.Run(() => { // get the raster from layer _selectedRaster = selectedRasterLayer?.GetRaster(); if (selectedRasterLayer?.GetColorizer() is CIMRasterRGBColorizer) { // if the rgb renderer is used get the index of the band used to render the reb color component var rgbColorizer = selectedRasterLayer?.GetColorizer() as CIMRasterRGBColorizer; _bandindex = rgbColorizer.RedBandIndex; } else if (selectedRasterLayer?.GetColorizer() is CIMRasterStretchColorizer) { // if the stretch renderer is used get the selected band index var stretchColorizer = selectedRasterLayer?.GetColorizer() as CIMRasterStretchColorizer; _bandindex = stretchColorizer.BandIndex; } }); RasterValuesPaneViewModel.Show(); return(base.OnToolActivateAsync(active)); }
/// <summary> /// Called when the OnToolMouseDown event is handled. Allows the opportunity to perform asynchronous operations corresponding to the event. /// </summary> protected override Task HandleMouseDownAsync(MapViewMouseButtonEventArgs e) { //Get the instance of the ViewModel var vm = OverlayEmbeddableControl as EmbeddedControlViewModel; if (vm == null) { return(Task.FromResult(0)); } //Get the map coordinates from the click point and set the property on the ViewModel. return(QueuedTask.Run(() => { var mapPoint = ActiveMapView.ClientToMap(e.ClientPoint); var coords = GeometryEngine.Project(mapPoint, SpatialReferences.WGS84) as MapPoint; if (coords == null) { return; } var sb = new StringBuilder(); sb.AppendLine($"X: {coords.X:0.000}"); sb.Append($"Y: {coords.Y:0.000}"); if (coords.HasZ) { sb.AppendLine(); sb.Append($"Z: {coords.Z:0.000}"); } vm.Text = sb.ToString(); })); }
/// <summary> /// Called when a sketch is completed. /// </summary> protected override async Task <bool> OnSketchCompleteAsync(ArcGIS.Core.Geometry.Geometry geometry) { var popupContent = await QueuedTask.Run(() => { //Get the features that intersect the sketch geometry. var result = ActiveMapView.GetFeatures(geometry); //For each feature in the result create a new instance of our custom pop-up content class. List <PopupContent> popups = new List <PopupContent>(); foreach (var kvp in result) { kvp.Value.ForEach(id => popups.Add(new DynamicPopupContent(kvp.Key, id))); } //Flash the features that intersected the sketch geometry. ActiveMapView.FlashFeature(result); //return the collection of pop-up content object. return(popups); }); //Show the custom pop-up with the custom commands and the default pop-up commands. ActiveMapView.ShowCustomPopup(popupContent, null, true); return(true); }
protected override async Task <bool> OnSketchCompleteAsync(Geometry geometry) { var bottomRight = new Point(); IList <Tuple <string, string, long> > tripleTuplePoints = new List <Tuple <string, string, long> >(); var hasSelection = await QueuedTask.Run(() => { // geometry is a point var clickedPnt = geometry as MapPoint; if (clickedPnt == null) { System.Windows.MessageBox.Show("Clicked point is null"); return(false); } // pixel tolerance var tolerance = 10; //Get the client point edges var topLeft = new Point(clickedPnt.X - tolerance, clickedPnt.Y + tolerance); bottomRight = new Point(clickedPnt.X + tolerance, clickedPnt.Y - tolerance); //convert the client points to Map points var mapTopLeft = MapView.Active.ClientToMap(topLeft); var mapBottomRight = MapView.Active.ClientToMap(bottomRight); //create a geometry using these points Geometry envelopeGeometry = EnvelopeBuilder.CreateEnvelope(mapTopLeft, mapBottomRight); if (envelopeGeometry == null) { System.Windows.MessageBox.Show("envleope is null"); return(false); } //Get the features that intersect the sketch geometry. var result = ActiveMapView.GetFeatures(geometry); foreach (var kvp in result) { var bfl = kvp.Key; // only look at points if (kvp.Key.ShapeType != esriGeometryType.esriGeometryPoint) { continue; } var layerName = bfl.Name; var oidName = bfl.GetTable().GetDefinition().GetObjectIDField(); foreach (var oid in kvp.Value) { tripleTuplePoints.Add(new Tuple <string, string, long>(layerName, oidName, oid)); } } return(true); }); if (hasSelection) { //System.Windows.MessageBox.Show("Has selection"); ShowContextMenu(bottomRight, tripleTuplePoints); } return(true); }
protected override Task <bool> OnSketchCompleteAsync(Geometry geometry) { return(ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { // Using the active map view to select // the features that intersect the sketch geometry ActiveMapView.SelectFeatures(geometry); return true; })); }
protected override Task HandleKeyDownAsync(MapViewKeyEventArgs k) { // only called when 'handled' in OnToolKeyDown if (k.Key == Key.Up) { // Key.Up => zoom out return(ActiveMapView.ZoomOutFixedAsync(TimeSpan.FromSeconds(1))); } // Key.Down => zoom in // else if (k.Key == Key.Down) { return(ActiveMapView.ZoomInFixedAsync(TimeSpan.FromSeconds(1))); } }
protected override void OnToolMouseMove(MapViewMouseEventArgs e) { if (_active) { QueuedTask.Run(() => { _counter++; if (_counter % 10 == 0) { MapView.Active.LookAtAsync(ActiveMapView.ClientToMap(e.ClientPoint), new TimeSpan(0, 0, 0, 0, 15)); _counter = 0; } }); } e.Handled = true; }
protected override Task <bool> OnSketchCompleteAsync(Geometry geometry) { WKTExportFlags exportFlagsNoZ = WKTExportFlags.wktExportStripZs; WKTExportFlags exportFlagsNoM = WKTExportFlags.wktExportStripMs; var wktString = GeometryEngine.Instance.ExportToWKT(exportFlagsNoZ | exportFlagsNoM, geometry); Debug.WriteLine("geometry = " + wktString); var srid = geometry.SpatialReference.GcsWkid; Debug.WriteLine("srid = " + srid); //String sql = String.Format("select id from public.features where ST_Intersects(geom, ST_GeomFromText('{0}', {1}))", wktString, srid); String sql = String.Format("select id from public.features where ST_Intersects(geom, ST_Buffer(ST_GeomFromText('{0}', {1}), 0.05))", wktString, srid); Debug.WriteLine("sql = " + sql); Npgsql.NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres; " + "Password=postgres;Database=geomapmaker;"); conn.Open(); NpgsqlCommand command = new NpgsqlCommand(sql, conn); NpgsqlDataReader dr = command.ExecuteReader(); DataTable dT = new DataTable(); dT.Load(dr); foreach (DataRow row in dT.Rows) { Debug.Write("Hi there \n"); //Debug.Write("{0} \n", row["name"].ToString()); Debug.WriteLine(row["id"].ToString()); } conn.Close(); //return base.OnSketchCompleteAsync(geometry); return(ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { // Using the active map view to select // the features that intersect the sketch geometry ActiveMapView.SelectFeatures(geometry); return true; })); }
protected override Task HandleMouseDownAsync(MapViewMouseButtonEventArgs e) { // Get the map coordinates from the click point and change the Camera to zoom in or out. return(QueuedTask.Run(() => { var mapClickPnt = MapView.Active.ClientToMap(e.ClientPoint); ActiveMapView.LookAt(mapClickPnt, TimeSpan.FromSeconds(1)); // zoom out if (e.ChangedButton == MouseButton.Right) { ActiveMapView.ZoomOutFixed(TimeSpan.FromSeconds(1)); } // zoom in else if (e.ChangedButton == MouseButton.Left) { ActiveMapView.ZoomInFixed(TimeSpan.FromSeconds(1)); } })); }
protected override void OnKeyUpCore(MapViewKeyEventArgs k) { _msg.VerboseDebug("OnKeyUpCore"); if (IsShiftKey(k.Key)) { _intermittentSelectionPhase = false; // TODO: Maintain selection by using SelectionChanged? Event? IList <Feature> selection = SelectionUtils.GetSelectedFeatures(ActiveMapView).ToList(); if (CanUseSelection(selection)) { StartSketchPhase(); if (_editSketchBackup != null) { ActiveMapView.SetCurrentSketchAsync(_editSketchBackup); // This puts back the edit operations in the undo stack, but when clicking on the top one, the sketch // is cleared and undoing any previous operation has no effect any more. ActiveMapView.Map.OperationManager.ClearUndoCategory("SketchOperations"); if (_sketchOperations != null) { foreach (Operation operation in _sketchOperations) { ActiveMapView.Map.OperationManager.AddUndoOperation(operation); } } } } _editSketchBackup = null; } if (k.Key == _keyRestorePrevious) { RestorePreviousSketch(); } }
protected override Task <bool> OnSketchCompleteAsync(Geometry geometry) { return(QueuedTask.Run(() => { try { ActiveMapView.SelectFeatures(geometry, SelectionCombinationMethod.Subtract); } catch (Exception ex) { string caption = "Failed to de-select features!"; string message = "Process failed. \n\nSave and restart ArcGIS Pro and try process again.\n\n" + $"If problem persist, contact your local GIS nerd.\n\n{ex}"; //Using the ArcGIS Pro SDK MessageBox class MessageBox.Show(message, caption); } return true; })); }
/// <summary> /// Happens if the tool is activated. /// </summary> /// <param name="active"></param> /// <returns></returns> protected async override Task OnToolActivateAsync(bool active) { // get the first selected raster layer var selectedRasterLayer = ActiveMapView.GetSelectedLayers().OfType <BasicRasterLayer>().FirstOrDefault(); _bandindex = await QueuedTask.Run(() => { // get the raster from layer _selectedRaster = selectedRasterLayer?.GetRaster(); var colorizer = selectedRasterLayer?.GetColorizer(); var str = colorizer.ToJson(); if (selectedRasterLayer?.GetColorizer() is CIMRasterRGBColorizer) { // if the rgb renderer is used get the index of the band used to render the reb color component var rgbColorizer = selectedRasterLayer?.GetColorizer() as CIMRasterRGBColorizer; return(rgbColorizer.RedBandIndex); } else if (selectedRasterLayer?.GetColorizer() is CIMRasterStretchColorizer) { // if the stretch renderer is used get the selected band index var stretchColorizer = selectedRasterLayer?.GetColorizer() as CIMRasterStretchColorizer; return(stretchColorizer.BandIndex); } return(-1); }); if (_bandindex > -1) { RasterValuesPaneViewModel.Show(); } else { MessageBox.Show("For pixel insp. sample, please use either a stretch or RGB colorizer", "Pixel Inspector"); } }
protected override Task <bool> OnSketchCompleteAsync(Geometry geometry) { return(QueuedTask.Run(() => { try { ActiveMapView.SelectFeatures(geometry, SelectionCombinationMethod.Add); } catch (Exception ex) { SysModule.LogError(ex.Message, ex.StackTrace); string caption = "Failed to Select Features"; string message = "Process failed. \nSave and restart ArcGIS Pro and try process again.\n" + "If problem persist, contact your GIS Admin."; //Using the ArcGIS Pro SDK MessageBox class MessageBox.Show(message, caption); } return true; })); }
protected override async Task <bool> OnSketchCompleteAsync(Geometry geometry) { try { var standaloneTable = await QueuedTask.Run(() => { ActiveMapView.SelectFeatures(geometry, SelectionCombinationMethod.New); slComp = Module1.GetCompkey(); if (!string.IsNullOrEmpty(slComp)) { Uri path = new Uri("O:\\SHARE\\405 - INFORMATION SERVICES\\GIS_Layers\\[email protected]"); // Set up Geodatabase Object) using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(path))) { string queryString = $"COMPKEY = {slComp}"; QueryDef queryDef = new QueryDef() { Tables = "SDE.sewerman.tblV8PMTOOL", WhereClause = queryString, }; QueryTableDescription queryTableDescription = new QueryTableDescription(queryDef) { MakeCopy = true, Name = $"Preventive Maintenance: {slComp}", PrimaryKeys = geodatabase.GetSQLSyntax().QualifyColumnName("SDE.sewerman.tblV8PMTOOL", "COMPKEY") }; var queryTable = geodatabase.OpenQueryTable(queryTableDescription); int count = queryTable.GetCount(); if (count == 0) { MessageBox.Show("Sewer line selected has no preventive maintenance scheduled."); } else { // Create a standalone table from the queryTable Table IStandaloneTableFactory tableFactory = StandaloneTableFactory.Instance; StandaloneTable pmTable = tableFactory.CreateStandaloneTable(queryTable, MapView.Active.Map); return(pmTable); } } } ; //return base.OnSketchCompleteAsync(geometry); return(null); }); // Open the standalone table pane FrameworkApplication.Panes.OpenTablePane(standaloneTable, TableViewMode.eAllRecords); } catch (Exception) { string caption = "Error Occured"; string message = "Process failed! \nSave and restart ArcGIS Pro and try process again.\n" + "If problem persist, contact your local GIS nerd."; //Using the ArcGIS Pro SDK MessageBox class MessageBox.Show(message, caption); } return(true); }
protected override Task OnToolActivateAsync(bool active) { var hasSelection = QueuedTask.Run(() => { ProWindowConfig objCfg = new ProWindowConfig(); objCfg = IdentityConfigWindow.promdl; var feat_lyrnames = new List <string>() { }; var mosic_lyrnames = new List <string>() { }; string filtername = "LiquidsHCAFilter"; //Assign defaul layernames if the object is empty if (objCfg is null) { feat_lyrnames = new List <string> { "HydrographicTransportPaths", "WaterbodySpreadPolygons" }; mosic_lyrnames = new List <string> { "MultiDimRasterMosaic" }; } //Assign layer names from the config object else { if (!string.IsNullOrEmpty(objCfg.LSName)) { mosic_lyrnames.Add(objCfg.LSName); } if (!string.IsNullOrEmpty(objCfg.NHDIntName)) { feat_lyrnames.Add(objCfg.NHDIntName); } if (!string.IsNullOrEmpty(objCfg.HTPathName)) { feat_lyrnames.Add(objCfg.HTPathName); } if (!string.IsNullOrEmpty(objCfg.HTSpreadName)) { feat_lyrnames.Add(objCfg.HTSpreadName); } } //Remove the Defination query for the feature layers foreach (string lyrname in feat_lyrnames) { FeatureLayer fl = ActiveMapView.Map.FindLayers(lyrname).First() as FeatureLayer; fl.RemoveDefinitionFilter(filtername); } // Remove the defination query for hte Mosic dataset foreach (string lyrname in mosic_lyrnames) { MosaicLayer fl = ActiveMapView.Map.FindLayers(lyrname).First() as MosaicLayer; fl.RemoveDefinitionFilter(filtername); } ActiveMapView.RedrawAsync(true); return(true); }); return(base.OnToolActivateAsync(active)); }
protected override void OnToolMouseMove(MapViewMouseEventArgs e) { if (_selectedRaster == null) { return; } // bIsMouseMoveActive is preventing the creation of too many threads via QueuedTask.Run // especially if imagery is via a remote service if (bIsMouseMoveActive) { return; } bIsMouseMoveActive = true; System.Diagnostics.Debug.WriteLine($@"{DateTime.Now} OnToolMouseMove"); QueuedTask.Run(() => { try { // create a pixelblock representing a 3x3 window to hold the raster values var pixelBlock = _selectedRaster.CreatePixelBlock(3, 3); // determine the cursor position in mapping coordinates var clientCoords = new System.Windows.Point(e.ClientPoint.X, e.ClientPoint.Y); if (clientCoords == null || ActiveMapView == null) { return; } var mapPointAtCursor = ActiveMapView.ClientToMap(clientCoords); if (mapPointAtCursor == null) { return; } // create a container to hold the pixel values Array pixelArray = new object[pixelBlock.GetWidth(), pixelBlock.GetHeight()]; // reproject the raster envelope to match the map spatial reference var rasterEnvelope = GeometryEngine.Instance.Project(_selectedRaster.GetExtent(), mapPointAtCursor.SpatialReference); // if the cursor is within the extent of the raster if (GeometryEngine.Instance.Contains(rasterEnvelope, mapPointAtCursor)) { // find the map location expressed in row,column of the raster var pixelLocationAtRaster = _selectedRaster.MapToPixel(mapPointAtCursor.X, mapPointAtCursor.Y); // fill the pixelblock with the pointer location _selectedRaster.Read(pixelLocationAtRaster.Item1, pixelLocationAtRaster.Item2, pixelBlock); if (_bandindex != -1) { // retrieve the actual pixel values from the pixelblock representing the red raster band pixelArray = pixelBlock.GetPixelData(_bandindex, false); } } else { // fill the container with 0s Array.Clear(pixelArray, 0, pixelArray.Length); } // pass the pass the raster values to the view model RasterValuesPaneViewModel.Current.RasterValues = ConvertArray(pixelArray); } finally { bIsMouseMoveActive = false; } }); }
protected override async Task <bool> OnSketchCompleteAsync(Geometry geometry) { var bottomRight = new Point(); IList <Tuple <string, string, long> > tripleTuplePoints = new List <Tuple <string, string, long> >(); var hasSelection = await QueuedTask.Run(() => { // geometry is a point var clickedPnt = geometry as MapPoint; if (clickedPnt == null) { return(false); } // pixel tolerance var tolerance = 3; //Get the client point edges var topLeft = new Point(clickedPnt.X - tolerance, clickedPnt.Y + tolerance); bottomRight = new Point(clickedPnt.X + tolerance, clickedPnt.Y - tolerance); //convert the client points to Map points var mapTopLeft = MapView.Active.ClientToMap(topLeft); var mapBottomRight = MapView.Active.ClientToMap(bottomRight); //create a geometry using these points Geometry envelopeGeometry = EnvelopeBuilder.CreateEnvelope(mapTopLeft, mapBottomRight); if (envelopeGeometry == null) { return(false); } //Get the features that intersect the sketch geometry. var result = ActiveMapView.GetFeatures(geometry); ProWindowConfig objCfg = new ProWindowConfig(); objCfg = IdentityConfigWindow.promdl; //string[] feat_lyrnames = { }; var feat_lyrnames = new List <string>() { }; //string[] mosic_lyrnames = { }; var mosic_lyrnames = new List <string>() { }; string filtername = "LiquidsHCAFilter"; string strOSPointlayername = "NHD_Intersections"; //Assign defaul layernames if the object is empty if (objCfg is null) { feat_lyrnames = new List <string> { "HydrographicTransportPaths", "WaterbodySpreadPolygons" }; mosic_lyrnames = new List <string> { "MultiDimRasterMosaic" }; } //Assign layer names from the config object else { //Check the values are null or not if (!string.IsNullOrEmpty(objCfg.OSPointName)) { strOSPointlayername = objCfg.OSPointName; } if (!string.IsNullOrEmpty(objCfg.LSName)) { mosic_lyrnames.Add(objCfg.LSName); } if (!string.IsNullOrEmpty(objCfg.NHDIntName)) { feat_lyrnames.Add(objCfg.NHDIntName); } if (!string.IsNullOrEmpty(objCfg.HTPathName)) { feat_lyrnames.Add(objCfg.HTPathName); } if (!string.IsNullOrEmpty(objCfg.HTSpreadName)) { feat_lyrnames.Add(objCfg.HTSpreadName); } } var ospointlyr = ActiveMapView.Map.FindLayers(strOSPointlayername).First() as FeatureLayer; foreach (var kvp in result) { var bfl = kvp.Key; // only look at points if (kvp.Key.ShapeType != esriGeometryType.esriGeometryPoint) { continue; } var layerName = bfl.Name; var oidName = bfl.GetTable().GetDefinition().GetObjectIDField(); foreach (var oid in kvp.Value) { //Select a single state polygon FeatureLayer fl1 = ActiveMapView.Map.FindLayers(strOSPointlayername).First() as FeatureLayer; QueryFilter queryFilter = new QueryFilter(); string whereClause = String.Format("{0} = {1}", oidName, oid); queryFilter.WhereClause = whereClause; //Use a cursor to get to a feature's geometry using (ArcGIS.Core.Data.RowCursor rowCursor = fl1.Search(queryFilter)) { //Grab the first record (and hopefully only record) while (rowCursor.MoveNext()) { //Grab the features geometry Feature feature = rowCursor.Current as Feature; //Geometry geo = feature.GetShape(); string pintid_field = "POINT_ID"; var pointidval = feature[pintid_field]; foreach (string lyrname in feat_lyrnames) { FeatureLayer fl = ActiveMapView.Map.FindLayers(lyrname).First() as FeatureLayer; var lyrfilter = new CIMDefinitionFilter(); lyrfilter.Name = filtername; lyrfilter.DefinitionExpression = String.Format("{0} = '{1}'", pintid_field, pointidval); fl.SetDefinitionFilter(lyrfilter); } foreach (string lyrname in mosic_lyrnames) { MosaicLayer fl = ActiveMapView.Map.FindLayers(lyrname).First() as MosaicLayer; //RasterLayer rl = ActiveMapView.Map.FindLayers(lyrname).First() as RasterLayer; //rl.SetDefinition(); var lyrfilter = new CIMDefinitionFilter(); lyrfilter.Name = filtername; lyrfilter.DefinitionExpression = String.Format("Name LIKE '{0}%'", pointidval); fl.SetDefinitionFilter(lyrfilter); } ActiveMapView.RedrawAsync(true); } } } } return(true); }); return(true); }
protected override async Task <bool> OnSketchCompleteAsync(Geometry geometry) { try { StandaloneTable standaloneTable = await QueuedTask.Run(() => { ActiveMapView.SelectFeatures(geometry, SelectionCombinationMethod.New); var map = MapView.Active.Map; var linesLayer = map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault((m => m.Name == "Sewer Lines")); // Get the currently selected features in the map var selectedFeatures = map.GetSelection(); var selectCount = linesLayer.SelectionCount; if (selectCount == 0) { MessageBox.Show("No Sewer Line was selected.\n\nTry selection again."); } else if (selectCount > 1) { MessageBox.Show("More than one sewer line was selected.\n" + "Try selecting sewer line again.\nZooming in may help."); } else { pipeID = SysModule.GetPipeID(); if (!string.IsNullOrEmpty(pipeID)) { Uri path = new Uri("O:\\SHARE\\405 - INFORMATION SERVICES\\GIS_Layers\\[email protected]"); // Set up Geodatabase Object) using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(path))) { string queryString = $"PIPE_ID = '{pipeID}'"; QueryDef queryDef = new QueryDef() { Tables = "SDE.sewerman.tblEAM_PM", WhereClause = queryString, SubFields = "PIPE_ID, TASK, PREVDATE, NEXTDATE, INTERVAL, UNIT, OBJECTID", }; QueryTableDescription queryTableDescription = new QueryTableDescription(queryDef) { MakeCopy = true, Name = $"Preventive Maintenance: {pipeID}", PrimaryKeys = geodatabase.GetSQLSyntax().QualifyColumnName("SDE.sewerman.tblEAM_PM", "PIPE_ID") }; Table queryTable = geodatabase.OpenQueryTable(queryTableDescription); int count = queryTable.GetCount(); if (count == 0) { MessageBox.Show("Sewer line selected has no preventive maintenance scheduled."); } else { // Create a standalone table from the queryTable Table IStandaloneTableFactory tableFactory = StandaloneTableFactory.Instance; StandaloneTable pmTable = tableFactory.CreateStandaloneTable(queryTable, MapView.Active.Map); return(pmTable); } } } ; } return(null); }); // Open the standalone table pane FrameworkApplication.Panes.OpenTablePane(standaloneTable, TableViewMode.eAllRecords); } catch (Exception ex) { SysModule.LogError(ex.Message, ex.StackTrace); string caption = "Error Occured"; string message = "Process failed.\nSave and restart ArcGIS Pro and try process again.\n" + "If problem persist, contact your GIS Admin."; //Using the ArcGIS Pro SDK MessageBox class MessageBox.Show(message, caption); } return(true); }
protected override async Task HandleMouseDownAsync(MapViewMouseButtonEventArgs e) { await QueuedTask.Run(() => { var mapPoint = MapPointBuilder.CreateMapPoint(e.ClientPoint.X, e.ClientPoint.Y); var result = ActiveMapView.GetFeatures(mapPoint); List <PopupContent> popups = new List <PopupContent>(); foreach (var kvp in result) { var layer = kvp.Key as BasicFeatureLayer; if (layer == null) { continue; } var fields = layer.GetFieldDescriptions().Where(f => f.Name == "DI_JI_HAO"); var tableDef = layer.GetTable().GetDefinition(); var oidField = tableDef.GetObjectIDField(); foreach (var id in kvp.Value) { //获取地级编号 //DI_JI_HAO var qf = new QueryFilter() { WhereClause = $"{oidField} = {id}", SubFields = string.Join(",", fields.Select(f => f.Name)) }; var rows = layer.Search(qf); if (!rows.MoveNext()) { continue; } using (var row = rows.Current) { foreach (var field in fields) { var val = row[field.Name]; if (field.Name == "DI_JI_HAO") { PopupContent pc = new PopupContent(new Uri("http://59.42.105.34:5001/client/?id=" + val), "林业"); popups.Add(pc); } } } } } //Flash the features that intersected the sketch geometry. MessageBox.Show(popups.ToString()); ActiveMapView.FlashFeature(result); var height = System.Windows.SystemParameters.WorkArea.Height / 2; var width = System.Windows.SystemParameters.WorkArea.Width / 2; var topLeftCornerPoint = new System.Windows.Point(0, 0); var popupDef = new PopupDefinition() { Append = true, // if true new record is appended to existing (if any) Dockable = true, // if true popup is dockable - if false Append is not applicable Position = topLeftCornerPoint, // Position of top left corner of the popup (in pixels) Size = new System.Windows.Size(width, height) // size of the popup (in pixels) }; //Show the custom pop-up with the custom commands and the default pop-up commands. try { ActiveMapView.ShowCustomPopup(popups, null, true, popupDef); } catch (System.Exception e1) { MessageBox.Show(string.Format("{0}", e1)); } //return the collection of pop-up content object. }); }
protected override Task <bool> OnSketchCompleteAsync(Geometry geometry) { return(QueuedTask.Run(() => { try { ActiveMapView.SelectFeatures(geometry, SelectionCombinationMethod.New); var map = MapView.Active.Map; var mhLayer = map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault((m => m.Name == "Manholes")); // Get the currently selected features in the map var selectedFeatures = map.GetSelection(); var selectCount = mhLayer.SelectionCount; if (selectCount == 0) { MessageBox.Show("No manhole was selected." + "\n\nTry selecting a manhole again."); } else if (selectCount > 1) { MessageBox.Show("More than one manhole selected." + "\n\nTry selecting manholes again. Zooming in may help."); } else { progDial.Show(); // get the first layer and its corresponding selected feature OIDs var firstSelectionSet = selectedFeatures.First(); // create an instance of the inspector class var inspector = new Inspector(); // load the selected features into the inspector using a list of object IDs inspector.Load(firstSelectionSet.Key, firstSelectionSet.Value); //get the value of string mhNum = inspector["MH_NO"].ToString(); // Create the workArcList to store the Arcs(VALUES as int) from the nodeArcListDict // for the selected mhNum(KEY as string) List <int> workArcList = new List <int>(); // Output the Arc ObjectID (VALUES) as List<int> for the selected mhNum (KEY) nodeArcListDict.TryGetValue(mhNum, out List <int> arcValues); // Loop through Output List<int> and add VALUE to workArcList foreach (var arcValue in arcValues) { workArcList.Add(arcValue); } // Create the removeArcsList to store the Arcs(VALUES as int) List <int> removeArcsList = new List <int>(); // loop through workArcList check if it contains downstream node = mhNum selected by user foreach (var workArc in workArcList) { // Get the list of Values from the arcNodeListDict for the current arc KEY (workArc) in workArcList. arcNodeListDict.TryGetValue(workArc, out List <string> nodeWorkVals); //Get the downstream manhole [0] from list. string downMH = nodeWorkVals[1]; // Check if downstream manhole and selected manhole are the same. if (downMH == mhNum) { // Add to removeArcList removeArcsList.Add(workArc); } } // Loop through removeArcsList remove each removeArc in list from workArcList (this is getting confusing) foreach (var removeArc in removeArcsList) { // Remove from workArcList workArcList.Remove(removeArc); } if (workArcList.Count() == 0) { MessageBox.Show("No downstream sewer lines found.", "Warning!"); } // Create dictionary to store downstream arcs that will be used to create query string. // Only reason dictionary is used is because it's a quick way to prevent duplicate KEYS. Dictionary <string, string> downStreamArcDict = new Dictionary <string, string>(); //string downStreamNode = ""; List <string> workManholeList = new List <string>(); int loopCount = 0; // At start of loop, workArcList has >0 arcs from initial selection. do { loopCount++; workManholeList.Clear(); removeArcsList.Clear(); foreach (var arc in workArcList) { if (downStreamArcDict.ContainsKey(arc.ToString()) == false) { // Add arc to downstream arc dictionary downStreamArcDict.Add(arc.ToString(), "TRUE"); } } foreach (var dwnArc in workArcList) { arcNodeListDict.TryGetValue(dwnArc, out List <string> nodeWorkVals); //Get the downstream manhole [1] from list. string downMH = nodeWorkVals[1]; // Add downstream manhole for selected downstream arc to workManholeList. // This will be used to get more more downstream arcs later. workManholeList.Add(downMH); } // Clear workArcList to add new arcs later. workArcList.Clear(); // Get all the arcs connected to all the manholes in the workManholeList using nodeArcListDict dictionary. // Add these arcs to workArcList. foreach (var mh in workManholeList) { // Get all the arcs attached to manhole/node. nodeArcListDict.TryGetValue(mh, out List <int> arcVals); // Add list of arcs to workArcList list. workArcList.AddRange(arcVals); } // Loop through all the arcs in workArcList and for arcs that have downstream manholes in the workManholeList, // add that arc to removeArcsList. foreach (var arc2 in workArcList) { // get list of nodes for arcs in workArcList. arcNodeListDict.TryGetValue(arc2, out List <string> nodeWorkVals2); // Get the downstream manhole [0] from list. string downMH = nodeWorkVals2[1]; // Check workManholeList for downMH and remove from removeArcList if TRUE. if (workManholeList.Contains(downMH)) { removeArcsList.Add(arc2); } } // Remove arcs in removeArcsList from workArcsList foreach (var arc3 in removeArcsList) { workArcList.Remove(arc3); } // Loop through again if condition is met. } while (workArcList.Count > 0); // Build the query string from the downStreamArcDict KEYS to select the downstream sewer lines. int count = 0; var stringBuilder = new StringBuilder(); foreach (var key in downStreamArcDict.Keys) { if (count == 0) { stringBuilder.Append($"OBJECTID IN ({key}"); } else if (count < downStreamArcDict.Keys.Count) { stringBuilder.Append($",{key}"); } count++; } stringBuilder.Append($")"); // Select sewers using StringBuilder object above for the WhereClause. QueryFilter queryFilter = new QueryFilter { WhereClause = stringBuilder.ToString() }; var sewerLines = map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(s => s.Name == "Sewer Lines"); var manholes = map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(s => s.Name == "Manholes"); sewerLines.Select(queryFilter, SelectionCombinationMethod.New); progDial.Hide(); } } catch (Exception ex) { SysModule.LogError(ex.Message, ex.StackTrace); string caption = "Trace Failed"; string message = "Downstream trace failed! \nSave and restart ArcGIS Pro and try process again.\n" + "If problem persist, contact your GIS Admin."; progDial.Hide(); //Using the ArcGIS Pro SDK MessageBox class MessageBox.Show(message, caption); } return true; })); }
/// <summary> /// Called when a sketch is completed. /// </summary> protected override async Task <bool> OnSketchCompleteAsync(ArcGIS.Core.Geometry.Geometry geometry) { List <PopupContent> popupContent = await QueuedTask.Run(() => { //Get the features that intersect the sketch geometry. var mapPoint = geometry as MapPoint; var sb = new StringBuilder(); sb.AppendLine(string.Format("OnSketchCompleteAsync X: {0}", mapPoint.X)); sb.Append(string.Format("Y: {0}", mapPoint.Y)); if (mapPoint.HasZ) { sb.AppendLine(); sb.Append(string.Format("Z: {0}", mapPoint.Z)); } MessageBox.Show(sb.ToString()); var result = ActiveMapView.GetFeatures(geometry); //For each feature in the result create a new instance of our custom pop-up content class. List <PopupContent> popups = new List <PopupContent>(); foreach (var kvp in result) { //kvp.Value.ForEach(id => popups.Add(new DynamicPopupContent(kvp.Key, id))); //kvp.Value.ForEach(id => popups.Add(new PopupContent(new Uri("https://www.google.com/webhp?ie=UTF-8&rct=j"), "xxxx"))); //popups.Add(new PopupContent("<b>This text is bold.</b>", "Custom tooltip from HTML string")); var layer = kvp.Key as BasicFeatureLayer; if (layer == null) { continue; } var fields = layer.GetFieldDescriptions().Where(f => f.Name == "DI_JI_HAO"); var tableDef = layer.GetTable().GetDefinition(); var oidField = tableDef.GetObjectIDField(); foreach (var id in kvp.Value) { //获取地级编号 //DI_JI_HAO var qf = new QueryFilter() { WhereClause = $"{oidField} = {id}", SubFields = string.Join(",", fields.Select(f => f.Name)) }; var rows = layer.Search(qf); if (!rows.MoveNext()) { continue; } using (var row = rows.Current) { foreach (var field in fields) { var val = row[field.Name]; if (field.Name == "DI_JI_HAO") { PopupContent pc = new PopupContent(new Uri("http://59.42.105.34:5001/client/?id=" + val), "林业"); popups.Add(pc); } } } } } //Flash the features that intersected the sketch geometry. ActiveMapView.FlashFeature(result); //return the collection of pop-up content object. return(popups); }); var height = System.Windows.SystemParameters.WorkArea.Height / 2; var width = System.Windows.SystemParameters.WorkArea.Width / 2; var topLeftCornerPoint = new System.Windows.Point(0, 0); var popupDef = new PopupDefinition() { Append = true, // if true new record is appended to existing (if any) Dockable = true, // if true popup is dockable - if false Append is not applicable Position = topLeftCornerPoint, // Position of top left corner of the popup (in pixels) Size = new System.Windows.Size(width, height) // size of the popup (in pixels) }; //Show the custom pop-up with the custom commands and the default pop-up commands. ActiveMapView.ShowCustomPopup(popupContent, null, true, popupDef); return(true); }
protected override async Task <bool> OnSketchCompleteAsync(Geometry geometry) { try { var standaloneTable = await QueuedTask.Run(() => { ActiveMapView.SelectFeatures(geometry, SelectionCombinationMethod.New); var map = MapView.Active.Map; var mh = map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(m => m.Name == "Manholes"); var lines = map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(s => s.Name == "Sewer Lines"); // Get the number of selections for manholes layer var selectedFeatures = map.GetSelection(); var mhSelectCount = mh.SelectionCount; var linesSelectCount = lines.SelectionCount; Uri path = new Uri("O:\\SHARE\\405 - INFORMATION SERVICES\\GIS_Layers\\[email protected]"); // If Manholes layer has selection, remove lines selection and query work history for manhole selected. if (mhSelectCount == 1) { lines.ClearSelection(); mhID = SysModule.GetManholeID(); //Uri path = new Uri("O:\\SHARE\\405 - INFORMATION SERVICES\\GIS_Layers\\[email protected]"); // Set up Geodatabase Object) using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(path))) { string queryString = $"MH_ID = '{mhID}'"; QueryDef queryDef = new QueryDef() { Tables = "SDE.sewerman.tblEAM_Manhole_Work", WhereClause = queryString, }; QueryTableDescription queryTableDescription = new QueryTableDescription(queryDef) { MakeCopy = true, Name = $"Manhole work history: {mhID}", PrimaryKeys = geodatabase.GetSQLSyntax().QualifyColumnName("SDE.sewerman.tblEAM_Manhole_Work", "MH_ID") }; var queryTable = geodatabase.OpenQueryTable(queryTableDescription); int count = queryTable.GetCount(); if (count == 0) { MessageBox.Show("Manhole selected has no work history."); return(null); } else { // Create a standalone table from the queryTable Table IStandaloneTableFactory tableFactory = StandaloneTableFactory.Instance; StandaloneTable whTable = tableFactory.CreateStandaloneTable(queryTable, MapView.Active.Map); return(whTable); } } } // Query work history forSewer Lines selection else if (linesSelectCount == 1) { pipeID = SysModule.GetPipeID(); //Uri path = new Uri("O:\\SHARE\\405 - INFORMATION SERVICES\\GIS_Layers\\[email protected]"); // Set up Geodatabase Object) using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(path))) { string queryString = $"PIPE_ID = '{pipeID}'"; QueryDef queryDef = new QueryDef() { Tables = "SDE.sewerman.tblEAM_Sewer_Work", WhereClause = queryString, }; QueryTableDescription queryTableDescription = new QueryTableDescription(queryDef) { MakeCopy = true, Name = $"Sewer line work history: {pipeID}", PrimaryKeys = geodatabase.GetSQLSyntax().QualifyColumnName("SDE.sewerman.tblEAM_Sewer_Work", "PIPE_ID") }; var queryTable = geodatabase.OpenQueryTable(queryTableDescription); int count = queryTable.GetCount(); if (count == 0) { MessageBox.Show("Sewer line selected has no work history."); return(null); } else { // Create a standalone table from the queryTable Table IStandaloneTableFactory tableFactory = StandaloneTableFactory.Instance; StandaloneTable whTable = tableFactory.CreateStandaloneTable(queryTable, MapView.Active.Map); return(whTable); } } } else if (linesSelectCount == 0 && mhSelectCount == 0) { MessageBox.Show("No manhole or sewer line was selected.\n\nTry selection again."); } else if (linesSelectCount > 1 && mhSelectCount == 0) { MessageBox.Show("More than one sewer line was selected. " + "\nPlease select a single sewer. " + "\nZooming in may help."); } else if (mhSelectCount > 1 && linesSelectCount == 0) { MessageBox.Show("More than one manhole was selected. " + "\nPlease select a single manhole. " + "\nZooming in may help."); } else if (mhSelectCount > 1 && linesSelectCount > 1) { MessageBox.Show("More than one sewer feature was selected. " + "\nPlease select a single feature. " + "\nZooming in may help."); } return(null); }); // Open the standalone table pane FrameworkApplication.Panes.OpenTablePane(standaloneTable, TableViewMode.eAllRecords); } catch (Exception ex) { SysModule.LogError(ex.Message, ex.StackTrace); string caption = "Error Occured"; string message = "Process failed.\nSave and restart ArcGIS Pro and try process again.\n" + "If problem persist, contact your GIS Admin."; //Using the ArcGIS Pro SDK MessageBox class MessageBox.Show(message, caption); } return(true); //return base.OnSketchCompleteAsync(geometry); }