/// <summary>Обработка выборки в документе _document</summary> /// <param name="_document"></param> internal static void HandleSelectedFDO(Document _document) { PromptSelectionResult sel_result; // для обработки случая, когда Editor.SelectImplied() вызывает сбой во время операции _PASTECLIP // AutoCAD меняет акт.документ на тот откуда берется копия. try { sel_result = _document.Editor.SelectImplied(); } catch (System.Exception) { return; } if (sel_result.Status != PromptStatus.OK) { Core.ClearDataGridView(); return; } MgSelectionBase selection_base = AcMapFeatureEntityService.GetSelection(sel_result.Value); if (selection_base.GetLayers() == null) { Core.ClearDataGridView(); } else { Core.SelectionToDataGridView(selection_base); } }
void CheckSelectionState() { MgSelectionBase selection = _viewer.GetSelection(); MgReadOnlyLayerCollection layers = selection.GetLayers(); btnListSelected.Enabled = (layers != null); }
/// <summary> /// Установка зумирования и активной выборки (запуск через командную строку - отсюда название) /// </summary> /// <param name="sel_base">выборка, которую следует отобразить</param> internal static void ThroughAssZoomAndSelection(MgSelectionBase sel_base) { internal_saved_selection = AcMapFeatureEntityService.AddFeaturesToSelectionSet(null, sel_base); // преобразование в SelectionSet и обратно, sel_base = AcMapFeatureEntityService.GetSelection(internal_saved_selection); // иначе дает сбой метод GetSelectedFeatures() MgEnvelope extents = new MgEnvelope(); MgReadOnlyLayerCollection layers = sel_base.GetLayers(); foreach (MgLayerBase layer in layers) { MgFeatureReader ftr_reader = sel_base.GetSelectedFeatures(layer, layer.FeatureClassName, false); string geom_prop_name = ftr_reader.GetClassDefinition().DefaultGeometryPropertyName; while (ftr_reader.ReadNext()) { MgByteReader byte_reader = ftr_reader.GetGeometry(geom_prop_name); MgAgfReaderWriter agf_reader_writer = new MgAgfReaderWriter(); MgGeometry curr_geom = agf_reader_writer.Read(byte_reader); extents.ExpandToInclude(curr_geom.Envelope()); } } // зумирование и вызов функции выбора через командную строку Core.no_handle_selection = true; // чтобы изменение выборки не обрабатывалось string zoom_str; if ((extents.Width == 0) && (extents.Width == extents.Height)) { zoom_str = "'_zoom _c " + extents.LowerLeftCoordinate.X.ToString() + "," + extents.LowerLeftCoordinate.Y.ToString() + " "; } else { zoom_str = "'_zoom _w " + (extents.LowerLeftCoordinate.X - extents.Width / 2).ToString() + "," + (extents.LowerLeftCoordinate.Y - extents.Height / 2).ToString() + " " + (extents.UpperRightCoordinate.X + extents.Width / 2).ToString() + "," + (extents.UpperRightCoordinate.Y + extents.Height / 2).ToString(); } Core.SendStringToExecute(zoom_str + "\n" + "ThroughAssZoomAndSelectionHelperFunction\n" , true, false, false); }
private void CheckSelectionState() { MgSelectionBase selection = _viewer.GetSelection(); MgReadOnlyLayerCollection layers = selection.GetLayers(); if (layers != null) { btnClearSelection.Enabled = true; } else { btnClearSelection.Enabled = false; } }
private void mgMapViewer1_SelectionChanged(object sender, EventArgs e) { MgSelectionBase selection = mgMapViewer1.GetSelection(); MgReadOnlyLayerCollection layers = selection.GetLayers(); if (layers != null) { for (int i = 0; i < layers.GetCount(); i++) { MgLayerBase layer = layers.GetItem(i); if (layer.Name == "Parcels") //The selected layer is parcels { //Check that we only have one selected object int count = selection.GetSelectedFeaturesCount(layer, layer.FeatureClassName); if (count == 1) { MgFeatureReader reader = null; try { reader = selection.GetSelectedFeatures(layer, layer.FeatureClassName, false); if (reader.ReadNext()) { //Address is in the RPROPAD property if (reader.IsNull("RPROPAD")) { MessageBox.Show("Selected parcel has no address"); } else { MessageBox.Show("Address: " + reader.GetString("RPROPAD")); } } } finally //Must close all readers, otherwise connections will leak { reader.Close(); } } else { MessageBox.Show("Please select only one parcel"); } break; } } } }
internal MgSelectionSet(MgSelectionBase selection, MgMapViewerProvider provider) { _agfRw = new MgAgfReaderWriter(); _features = new Dictionary <string, List <MgFeature> >(); var selLayers = selection.GetLayers(); if (selLayers != null) { for (int i = 0; i < selLayers.GetCount(); i++) { var layer = selLayers.GetItem(i); var clsName = layer.GetFeatureClassName(); int selCount = selection.GetSelectedFeaturesCount(layer, clsName); if (selCount == 0) { System.Diagnostics.Trace.TraceWarning("No items in selection set for this layer (" + layer.GetName() + "). Layer shouldn't be here then"); continue; } NameValueCollection mappings = (provider != null) ? provider.GetPropertyMappings(layer) : null; _features[layer.Name] = new List <MgFeature>(); var reader = selection.GetSelectedFeatures(layer, layer.GetFeatureClassName(), false); while (reader.ReadNext()) { var feature = CreateFeatureFromReader(reader); if (mappings != null) { PerformDisplayNameSubstitution(feature, mappings); } _features[layer.Name].Add(feature); } reader.Close(); } } }
private void btnCreateBuffer_Click(object sender, EventArgs e) { MgSelectionBase selection = _viewer.GetSelection(); MgReadOnlyLayerCollection layers = selection.GetLayers(); if (layers == null) { MessageBox.Show("Select a parcel"); return; } MgLayerBase parcels = null; for (int i = 0; i < layers.GetCount(); i++) { MgLayerBase layer = layers.GetItem(i); if (layer.Name == "Parcels") { parcels = layer; break; } } if (parcels == null) { MessageBox.Show("Select a parcel"); return; } int bufferRingSize = 100; // measured in metres int bufferRingCount = 5; // Set up some objects for coordinate conversion MgMapBase map = _viewer.GetMap(); MgLayerCollection mapLayers = map.GetLayers(); MgMapViewerProvider provider = _viewer.GetProvider(); MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService); //Casting to MgdFeatureService because we want to use convenience APIs MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService); String mapWktSrs = map.GetMapSRS(); MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter(); MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter(); MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory(); MgCoordinateSystem srs = coordinateSystemFactory.Create(mapWktSrs); MgMeasure srsMeasure = srs.GetMeasure(); string sessionId = Guid.NewGuid().ToString(); BufferHelper helper = new BufferHelper(); // Check for a buffer layer. If it exists, delete // the current features. // If it does not exist, create a feature source and // a layer to hold the buffer. MgdLayer bufferLayer = null; int layerIndex = mapLayers.IndexOf("Buffer"); if (layerIndex < 0) { // The layer does not exist and must be created. MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource"); helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId); bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId); mapLayers.Insert(0, bufferLayer); } else { bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex); bufferLayer.DeleteFeatures("ID like '%'"); } // Get the selected features from the MgSelection object MgFeatureReader featureReader = selection.GetSelectedFeatures(parcels, parcels.GetFeatureClassName(), false); // Process each item in the MgFeatureReader. Get the // geometries from all the selected features and // merge them into a single geometry. MgGeometryCollection inputGeometries = new MgGeometryCollection(); while (featureReader.ReadNext()) { MgByteReader featureGeometryData = featureReader.GetGeometry(parcels.GetFeatureGeometryName()); MgGeometry featureGeometry = agfReaderWriter.Read(featureGeometryData); inputGeometries.Add(featureGeometry); } MgGeometryFactory geometryFactory = new MgGeometryFactory(); MgGeometry mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries); // Add buffer features to the temporary feature source. // Create multiple concentric buffers to show area. // If the stylization for the layer draws the features // partially transparent, the concentric rings will be // progressively darker towards the center. // The stylization is set in the layer template file, which // is used in function CreateBufferLayer(). for (int bufferRing = 0; bufferRing < bufferRingCount; bufferRing++) { double bufferDist = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize * (bufferRing + 1)); MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure); MgPropertyCollection properties = new MgPropertyCollection(); properties.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry))); MgFeatureReader fr = bufferLayer.InsertFeatures(properties); fr.Close(); } bufferLayer.SetVisible(true); bufferLayer.ForceRefresh(); bufferLayer.SetDisplayInLegend(true); MessageBox.Show("Buffer created"); _viewer.RefreshMap(); IMapLegend legend = Shell.Instance.Legend; if (legend != null) { legend.RefreshLegend(); } }
private void btnFindFeaturesInBuffer_Click(object sender, EventArgs e) { MgSelectionBase selection = _viewer.GetSelection(); MgReadOnlyLayerCollection selectedLayers = selection.GetLayers(); if (selectedLayers == null) { MessageBox.Show("Select a parcel"); return; } MgLayerBase parcels = null; for (int i = 0; i < selectedLayers.GetCount(); i++) { MgLayerBase layer = selectedLayers.GetItem(i); if (layer.Name == "Parcels") { parcels = layer; break; } } if (parcels == null) { MessageBox.Show("Select a parcel"); return; } int bufferRingSize = 500; // measured in metres // Set up some objects for coordinate conversion MgMapBase map = _viewer.GetMap(); MgLayerCollection mapLayers = map.GetLayers(); MgMapViewerProvider provider = _viewer.GetProvider(); MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService); //Casting to MgdFeatureService because we want to use convenience APIs MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService); string sessionId = Guid.NewGuid().ToString(); String mapWktSrs = map.GetMapSRS(); MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter(); MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter(); MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory(); MgCoordinateSystem srs = coordinateSystemFactory.Create(mapWktSrs); MgMeasure srsMeasure = srs.GetMeasure(); // Check for a buffer layer. If it exists, delete // the current features. // If it does not exist, create a feature source and // a layer to hold the buffer. BufferHelper helper = new BufferHelper(); MgdLayer bufferLayer = null; int layerIndex = map.GetLayers().IndexOf("Buffer"); if (layerIndex < 0) { // The layer does not exist and must be created. MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource"); helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId); bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId); map.GetLayers().Insert(0, bufferLayer); } else { bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex); bufferLayer.DeleteFeatures("ID like '%'"); } // Check for a parcel marker layer. If it exists, delete // the current features. // If it does not exist, create a feature source and // a layer to hold the parcel markers. MgdLayer parcelMarkerLayer = null; layerIndex = map.GetLayers().IndexOf("ParcelMarker"); if (layerIndex < 0) { MgResourceIdentifier parcelFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//ParcelMarker.FeatureSource"); helper.CreateParcelMarkerFeatureSource(featureService, mapWktSrs, parcelFeatureResId); parcelMarkerLayer = helper.CreateParcelMarkerLayer(resourceService, parcelFeatureResId, sessionId); map.GetLayers().Insert(0, parcelMarkerLayer); } else { parcelMarkerLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex); parcelMarkerLayer.DeleteFeatures("ID like '%'"); } // Check each layer in the selection. for (int i = 0; i < selectedLayers.GetCount(); i++) { // Only check selected features in the Parcels layer. MgdLayer layer = (MgdLayer)selectedLayers.GetItem(i); if (layer.GetName() == "Parcels") { string geomName = layer.GetFeatureGeometryName(); System.Diagnostics.Trace.TraceInformation("Marking all parcels inside the buffer that are of type 'MFG'"); MgFeatureReader featureReader = selection.GetSelectedFeatures(layer, layer.GetFeatureClassName(), false); // Process each item in the MgFeatureReader. Get the // geometries from all the selected features and // merge them into a single geometry. MgGeometryCollection inputGeometries = new MgGeometryCollection(); while (featureReader.ReadNext()) { MgByteReader featureGeometryData = featureReader.GetGeometry(geomName); MgGeometry featureGeometry = agfReaderWriter.Read(featureGeometryData); inputGeometries.Add(featureGeometry); } MgGeometryFactory geometryFactory = new MgGeometryFactory(); MgGeometry mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries); // Create a buffer from the merged geometries double bufferDist = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize); MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure); // Create a filter to select parcels within the buffer. Combine // a basic filter and a spatial filter to select all parcels // within the buffer that are of type "MFG". MgFeatureQueryOptions queryOptions = new MgFeatureQueryOptions(); queryOptions.SetFilter("RTYPE = 'MFG'"); queryOptions.SetSpatialFilter(geomName, bufferGeometry, MgFeatureSpatialOperations.Inside); featureReader = layer.SelectFeatures(queryOptions); // Get the features from the feature source, // determine the centroid of each selected feature, and // add a point to the ParcelMarker layer to mark the // centroid. // Collect all the points into an MgFeatureCommandCollection, // so they can all be added in one operation. MgFeatureCommandCollection parcelMarkerCommands = new MgFeatureCommandCollection(); int inserted = 0; while (featureReader.ReadNext()) { MgByteReader byteReader = featureReader.GetGeometry(geomName); MgGeometry geometry = agfReaderWriter.Read(byteReader); MgPoint point = geometry.GetCentroid(); // Create an insert command for this parcel. MgPropertyCollection properties = new MgPropertyCollection(); properties.Add(new MgGeometryProperty("ParcelLocation", agfReaderWriter.Write(point))); //parcelMarkerCommands.Add(new MgInsertFeatures("ParcelMarkerClass", properties)); MgFeatureReader fr = parcelMarkerLayer.InsertFeatures(properties); fr.Close(); inserted++; } featureReader.Close(); if (inserted == 0) { MessageBox.Show("No parcels within the buffer area match."); return; } // Create a feature in the buffer feature source to show the area covered by the buffer. MgPropertyCollection props = new MgPropertyCollection(); props.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry))); bufferLayer.InsertFeatures(props); // Ensure that the buffer layer is visible and in the legend. bufferLayer.SetVisible(true); bufferLayer.ForceRefresh(); bufferLayer.SetDisplayInLegend(true); parcelMarkerLayer.SetVisible(true); parcelMarkerLayer.ForceRefresh(); MessageBox.Show("Done"); _viewer.RefreshMap(); IMapLegend legend = Shell.Instance.Legend; if (legend != null) { legend.RefreshLegend(); } } } }
internal MgSelectionSet(MgSelectionBase selection, MgMapViewerProvider provider) { _agfRw = new MgAgfReaderWriter(); _features = new Dictionary<string, List<MgFeature>>(); var selLayers = selection.GetLayers(); if (selLayers != null) { for (int i = 0; i < selLayers.GetCount(); i++) { var layer = selLayers.GetItem(i); var clsName = layer.GetFeatureClassName(); int selCount = selection.GetSelectedFeaturesCount(layer, clsName); if (selCount == 0) { System.Diagnostics.Trace.TraceWarning("No items in selection set for this layer (" + layer.GetName() + "). Layer shouldn't be here then"); continue; } NameValueCollection mappings = (provider != null) ? provider.GetPropertyMappings(layer) : null; _features[layer.Name] = new List<MgFeature>(); var reader = selection.GetSelectedFeatures(layer, layer.GetFeatureClassName(), false); while (reader.ReadNext()) { var feature = CreateFeatureFromReader(reader); if (mappings != null) PerformDisplayNameSubstitution(feature, mappings); _features[layer.Name].Add(feature); } reader.Close(); } } }
} //method internal static void SelectionToDataGridView(MgSelectionBase _selection_base) { palette_window.links_control.is_suspended = true; // информируем о заморозке palette_window.links_control.SuspendLayout(); // замораживаем логику palette_window.links_control.data_grid.Enabled = false; palette_window.links_control.data_grid.SuspendLayout(); // замораживаем логику DataGridView palette_window.links_control.layers_list.Enabled = false; palette_window.links_control.progressbar_in_status.Visible = true; // включение ProgressBar palette_window.links_control.status_strip.Refresh(); MgReadOnlyLayerCollection layers = _selection_base.GetLayers(); int curr_features_count = 0, features_count = 0; // подсчет количества выбранных объектов foreach (MgLayerBase layer in layers) { features_count += _selection_base.GetSelectedFeaturesCount(layer, layer.FeatureClassName); } if (features_count == 0) { return; } // заполнение списка слоев palette_window.links_control.layers_list.Items.Clear(); // очищаем список if (layers.Count > 1) { palette_window.links_control.layers_list.Items.Add("(Все выбранные)"); } foreach (MgLayerBase layer in layers) { palette_window.links_control.layers_list.Items.Add(layer.Name); } palette_window.links_control.layers_list.SelectedIndex = 0; // заполнение DataGridView palette_window.links_control.data_grid.Rows.Clear(); // очищаем строки foreach (MgLayerBase layer in layers) { int curr_ftr_class_idx = config.IndexOf(layer.FeatureClassName); if (curr_ftr_class_idx == -1) { curr_features_count += _selection_base.GetSelectedFeaturesCount(layer, layer.FeatureClassName);; palette_window.links_control.UpdateStatusRowCounterLabelAndProgressBar(curr_features_count, features_count); continue; } FeatureClassLinkInfo curr_link_info = config.link_info_array[curr_ftr_class_idx]; MgFeatureReader ftr_rdr = _selection_base.GetSelectedFeatures(layer, layer.FeatureClassName, false); MgPropertyDefinitionCollection identity_prop_defs = ftr_rdr.GetClassDefinition().GetIdentityProperties(); // получаем набор идентификационных полей while (ftr_rdr.ReadNext()) { curr_features_count++; DataGridViewRow link_row = new DataGridViewRow(); // новая строка DataGridViewLinkCell link_cell; // ячейка // формирование URL link_cell = new DataGridViewLinkCell(); string title_str = ResolveLinkStringByValueFromReader(ftr_rdr, curr_link_info.LinkTitle); link_cell.Value = String.IsNullOrEmpty(title_str)? "<Null>": title_str; link_cell.ToolTipText = curr_link_info.LinkCommandPath + command_splitter + ResolveLinkStringByValueFromReader(ftr_rdr, curr_link_info.LinkURL); link_row.Cells.Add(link_cell); // вставка ячейки // формирование ID MgPropertyCollection curr_identity_props = GetPropertiesFromReader(ftr_rdr, identity_prop_defs); SelectedFeatureInfo sel_info = new SelectedFeatureInfo(layer, curr_identity_props); link_cell = new DataGridViewLinkCell(); link_cell.Value = sel_info; link_row.Cells.Add(link_cell); // вставка ячейки // добавлени строки в DataGridView palette_window.links_control.data_grid.Rows.Add(link_row); // обновление ProgressBar'а и счетчика строк palette_window.links_control.UpdateStatusRowCounterLabelAndProgressBar(curr_features_count, features_count); } /// while (ftr_rdr.ReadNext()) } /// foreach (MgLayerBase layer in layers) palette_window.links_control.URL.SortMode = DataGridViewColumnSortMode.NotSortable; // сброс сортировки palette_window.links_control.URL.SortMode = DataGridViewColumnSortMode.Automatic; // на исходную автоматическую palette_window.links_control.data_grid.SelectAll(); // выбираем все строки palette_window.links_control.progressbar_in_status.Visible = false; palette_window.links_control.layers_list.Enabled = true; palette_window.links_control.data_grid.Enabled = true; palette_window.links_control.data_grid.ResumeLayout(); // размораживаем логику DataGridView palette_window.links_control.ResumeLayout(); // размораживаем логику palette_window.links_control.is_suspended = false; palette_window.links_control.UpdateStatusRowCounterLabel(); // обновляем строку статуса }
private static int GetSelectionTotal(MgSelectionBase sel) { int total = 0; var layers = sel.GetLayers(); if (layers != null) { for (int i = 0; i < layers.GetCount(); i++) { var layer = layers.GetItem(i); total += sel.GetSelectedFeaturesCount(layer, layer.FeatureClassName); } } return total; }