protected override Task<bool> OnSketchCompleteAsync(ArcGIS.Core.Geometry.Geometry geometry) { //Check we only have one feature to extend to if (MapView.Active.Map.SelectionCount != 1) { MessageBox.Show("Please select one polyline or polygon feature to extend to", "Extend"); return Task.FromResult(true); } //Run on MCT return QueuedTask.Run(() => { //get selected feature geometry var selectedFeatures = MapView.Active.Map.GetSelection(); var insp = new Inspector(); insp.Load(selectedFeatures.Keys.First(), selectedFeatures.Values.First()); var selGeom = insp.Shape; if (!(selGeom.GeometryType == GeometryType.Polygon || selGeom.GeometryType == GeometryType.Polyline)) { MessageBox.Show("Please choose as the selected feature either a polyline or polygon feature to extend to"); return false; } //find feature at the click var clickFeatures = MapView.Active.GetFeatures(geometry); insp.Load(clickFeatures.First().Key, clickFeatures.First().Value); var clickGeom = insp.Shape as Polyline; if (clickGeom == null) { MessageBox.Show("Please select a polyline feature to extend"); return false; } //extend the line to the poly? ArcGIS.Core.Geometry.Polyline extPolyline; extPolyline = GeometryEngine.Extend(clickGeom, (selGeom.GeometryType == GeometryType.Polygon ? GeometryEngine.Boundary(selGeom) as Polyline : selGeom as Polyline), ExtendFlags.Default); if (extPolyline == null) { MessageBox.Show(string.Format("Unable to extend the clicked {0} to the selected {1}", clickGeom.GeometryType, selGeom.GeometryType)); return false; } //set the new geometry back on the feature insp.Shape = extPolyline; //create and execute the edit operation var op = new EditOperation(); op.Name = "Extend"; op.SelectModifiedFeatures = false; op.SelectNewFeatures = false; op.Modify(insp); return op.Execute(); }); }
protected override Task <bool> OnSketchCompleteAsync(Geometry geometry) { var mv = MapView.Active; _sketchStarted = false; return(QueuedTask.Run(() => { //filter out non-polygons var sel_set = Module1.Current.FilterSelection(mv.Map.GetSelection()); if (sel_set.Count() == 0) { return false; } //do the difference var editOp = new EditOperation() { Name = "Difference", ErrorMessage = "Difference failed" }; foreach (var kvp in sel_set) { var diffGeom = GeometryEngine.Instance.Project(geometry, kvp.Key.GetSpatialReference()); editOp.Difference(kvp.Key, kvp.Value, diffGeom); } return editOp.Execute(); })); }
/// <summary> /// Called when the sketch finishes. This is where we will create the sketch operation and then execute it. /// </summary> /// <param name="geometry">The geometry created by the sketch.</param> /// <returns>A Task returning a Boolean indicating if the sketch complete event was successfully handled.</returns> protected override Task <bool> OnSketchCompleteAsync(Geometry geometry) { if (CurrentTemplate == null || geometry == null) { return(Task.FromResult(false)); } return(QueuedTask.Run(() => { //apply overrides if (UseSubtypeChoiceOverride) { var choice = Module1.Current.SelectedSubtypeChoice; this.CurrentTemplate.Inspector["SUBTYPEFIELD"] = choice.SubtypefieldValue; this.CurrentTemplate.Inspector["FEATURECODE"] = choice.FeatureCodeValue; } else { this.CurrentTemplate.Inspector.Cancel(); } // Create an edit operation var createOperation = new EditOperation(); createOperation.Name = string.Format("Create {0}", CurrentTemplate.Layer.Name); createOperation.SelectNewFeatures = true; // Queue feature creation createOperation.Create(CurrentTemplate, geometry); return createOperation.Execute(); })); }
public static void ReadWriteBlobRow() { #region Read and Write blob fields with a row cursor in a callback QueuedTask.Run(() => { var editOp = new EditOperation(); editOp.Name = "Blob Cursor"; var featLayer = MapView.Active.Map.FindLayers("Hydrant").First() as FeatureLayer; editOp.Callback((context) => { using (var rc = featLayer.GetTable().Search(null, false)) { while (rc.MoveNext()) { //read file into memory stream var msr = new MemoryStream(); using (FileStream file = new FileStream(@"d:\images\Hydrant.jpg", FileMode.Open, FileAccess.Read)) { file.CopyTo(msr); } rc.Current["BlobField"] = msr; rc.Current.Store(); //read the blob field to a file var msw = new MemoryStream(); msw = rc.Current["BlobField"] as MemoryStream; using (FileStream file = new FileStream(@"d:\temp\blob.jpg", FileMode.Create, FileAccess.Write)) { msw.WriteTo(file); } } } }, featLayer.GetTable()); editOp.Execute(); }); #endregion }
protected override Task <bool> OnSketchCompleteAsync(ArcGIS.Core.Geometry.Geometry geometry) { //Simple check for selected layer if (MapView.Active.GetSelectedLayers().Count == 0) { MessageBox.Show("Please select a layer in the toc", "Update attributes with sketch"); return(Task.FromResult(true)); } //Run on MCT return(QueuedTask.Run(() => { //Get the selected layer in toc var featLayer = MapView.Active.GetSelectedLayers().First() as FeatureLayer; //find feature oids under the sketch for the selected layer var features = MapView.Active.GetFeatures(geometry); var featOids = features[featLayer]; //update the attributes of those features var insp = new Inspector(); insp.Load(featLayer, featOids); insp["PARCEL_ID"] = 42; //create and execute the edit operation var op = new EditOperation(); op.Name = "Update parcel"; op.SelectModifiedFeatures = true; op.SelectNewFeatures = false; op.Modify(insp); return op.Execute(); })); }
protected void inspectorclass() { var featLayer = MapView.Active.GetSelectedLayers().First() as FeatureLayer; Int64 oid = 42; #region inspectorclass QueuedTask.Run(() => { var insp = new Inspector(); insp.Load(featLayer, oid); //get the shape of the feature var myGeometry = insp.Shape; //get an attribue value by name var propValue = insp["Prop_value"]; //set an attribute value by name insp["Parcel_no"] = 42; //perform the edit var op = new EditOperation(); op.Name = "Update parcel"; op.Modify(insp); op.Execute(); }); #endregion }
/// <summary> /// Applys the domain code to the currenly selected feature /// </summary> /// <param name="code"></param> internal async void ApplyDomain(DomainCode code) { if (await CheckRequirements()) { await QueuedTask.Run(() => { try { Selection selection = _selectedLayer.GetSelection(); var oidset = selection.GetObjectIDs(); var insp = new ArcGIS.Desktop.Editing.Attributes.Inspector(); insp.Load(_selectedLayer, oidset); insp[_selectedField] = (int)code; var op = new EditOperation(); op.Name = "Set Domain to " + ((int)code).ToString(); op.Modify(insp); op.Execute(); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } }); } }
public async void Examples3() { var oid = 1; #region Edit the attributes of a FeatureSceneLayer //must support editing! var featSceneLayer = MapView.Active.Map.GetLayersAsFlattenedList() .OfType <FeatureSceneLayer>().FirstOrDefault(); if (!featSceneLayer.HasAssociatedFeatureService || !featSceneLayer.IsEditable) { return; } var ok = await QueuedTask.Run(() => { var editOp = new EditOperation() { Name = "Edit FeatureSceneLayer Attributes", SelectModifiedFeatures = true }; //make an inspector var inspector = new Inspector(); //get the attributes for the specified oid inspector.Load(featSceneLayer, oid); inspector["PermitNotes"] = "test"; //modify editOp.Modify(inspector); return(editOp.Execute()); //synchronous flavor }); #endregion }
protected override void OnClick() { var polyLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().First(); QueuedTask.Run(() => { var fc = polyLayer.GetTable() as FeatureClass; var fcDefinition = fc.GetDefinition(); Polygon outerRings = null; var editOperation = new EditOperation(); editOperation.Name = "Create outer ring"; using (var cursor = fc.Search()) { while (cursor.MoveNext()) { Feature feature = cursor.Current as Feature; outerRings = Module1.Current.GetOutermostRings(feature.GetShape() as Polygon); editOperation.Create(polyLayer, outerRings); } } editOperation.Execute(); }); }
public void EditOperation2(FeatureLayer transformerBankLayer, Dictionary <string, object> transformerBankAttributes, FeatureLayer poleLayer, Dictionary <string, object> poleAttributes) { #region Create utility network features and associations in a single edit operation // Create an EditOperation EditOperation editOperation = new EditOperation(); editOperation.Name = "Create pole; create transformer bank; attach transformer bank to pole"; // Create the transformer bank RowToken transformerBankToken = editOperation.CreateEx(transformerBankLayer, transformerBankAttributes); // Create a pole RowToken poleToken = editOperation.CreateEx(poleLayer, poleAttributes); // Create a structural attachment association between the pole and the transformer bank RowHandle poleHandle = new RowHandle(poleToken); RowHandle transformerBankHandle = new RowHandle(transformerBankToken); StructuralAttachmentAssociationDescription poleAttachment = new StructuralAttachmentAssociationDescription(poleHandle, transformerBankHandle); editOperation.Create(poleAttachment); // Execute the EditOperation editOperation.Execute(); #endregion }
protected override Task<bool> OnSketchCompleteAsync(ArcGIS.Core.Geometry.Geometry geometry) { //Simple check for selected layer if (MapView.Active.GetSelectedLayers().Count == 0) { MessageBox.Show("Please select a layer in the toc","Update attributes with sketch"); return Task.FromResult(true); } //Run on MCT return QueuedTask.Run(() => { //Get the selected layer in toc var featLayer = MapView.Active.GetSelectedLayers().First() as FeatureLayer; //find feature oids under the sketch for the selected layer var features = MapView.Active.GetFeatures(geometry); var featOids = features[featLayer]; //update the attributes of those features var insp = new Inspector(); insp.Load(featLayer, featOids); insp["PARCEL_ID"] = 42; //create and execute the edit operation var op = new EditOperation(); op.Name = "Update parcel"; op.SelectModifiedFeatures = true; op.SelectNewFeatures = false; op.Modify(insp); return op.Execute(); }); }
/// <summary> /// Update the field with a given value (int) /// </summary> /// <param name="status"></param> /// <param name="editName"></param> public void Update(int status, string editName) { QueuedTask.Run(() => { try { var basicfeaturelayer = _selectedLayer as BasicFeatureLayer; var selection = basicfeaturelayer.GetSelection(); var oidset = selection.GetObjectIDs(); var insp = new ArcGIS.Desktop.Editing.Attributes.Inspector(); insp.Load(basicfeaturelayer, oidset); insp[InpsectorFieldName] = 1; var op = new EditOperation(); op.Name = editName; op.Modify(insp); op.Execute(); basicfeaturelayer.ClearSelection(); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } }); }
protected override void OnClick() { if (Module1.Current.SelectedItems == null) { return; } int aantalVerdiepingen; double verdiepingsHoogte; QueuedTask.Run(() => { var editOperation = new EditOperation(); foreach (KeyValuePair <MapMember, List <long> > item in Module1.Current.SelectedItems) { var layer = item.Key as BasicFeatureLayer; foreach (long oid in item.Value) { var feature = layer.Inspect(oid); aantalVerdiepingen = new Random().Next(3, 10); verdiepingsHoogte = double.Parse(feature["PandHoogte"].ToString()) / aantalVerdiepingen; feature["PandHoogte"] = verdiepingsHoogte; editOperation.Modify(feature); for (int i = 1; i < aantalVerdiepingen; i++) { editOperation.Create(layer, GeometryEngine.Move(feature.Shape, 0, 0, (i * (verdiepingsHoogte * 2))), new Action <long>(x => newFloorCreated(x, layer, verdiepingsHoogte, feature.Shape.Extent.ZMin))); } } } bool succeded = editOperation.Execute(); }); }
protected async void BuildParcels() { await QueuedTask.Run(() => { var myParcelFabricLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <ParcelLayer>().FirstOrDefault(); var theActiveRecord = myParcelFabricLayer.GetActiveRecord(); myParcelFabricLayer.SetActiveRecord(theActiveRecord); var guid = theActiveRecord.Guid; if (myParcelFabricLayer == null) { return; } #region Build parcels var editOper = new EditOperation() { Name = "Build Parcels", ProgressMessage = "Build Parcels...", ShowModalMessageAfterFailure = true, SelectNewFeatures = true, SelectModifiedFeatures = true }; editOper.BuildParcelsByRecord(myParcelFabricLayer, guid); editOper.Execute(); #endregion }); }
private void CutBuilding(MapViewMouseButtonEventArgs e) { QueuedTask.Run(() => { Dictionary <MapMember, List <long> > selectedItems = GetSelectedItems(e); EditOperation editOperation = new EditOperation(); foreach (KeyValuePair <MapMember, List <long> > item in selectedItems) { BasicFeatureLayer layer = item.Key as BasicFeatureLayer; if (layer.ShapeType != ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolygon) { continue; } foreach (long oid in item.Value) { var feature = layer.Inspect(oid); Geometry geometry = feature.Shape.Clone(); Polyline polyLine = GetCutPolyLine(geometry); var splitItems = GeometryEngine.Cut(geometry, polyLine); feature.Shape = splitItems.First(); editOperation.Modify(feature); Layer pointLayer = MapView.Active.Map.Layers[0]; editOperation.Create(pointLayer, geometry.Extent.Center); } editOperation.Execute(); } MapView.Active.Map.SetSelection(null); }); }
private Task <bool> PerformShiftAndScaleEdit(double dx, double dy, double dz) { return(QueuedTask.Run(() => { #region Note //EditOperation scaleOperation = new EditOperation(); //scaleOperation.Name = "Shift and Scale features"; //scaleOperation.Scale(_attributeViewModel.SelectedFeatures, CurrentControlPoint, scale, scale, scale); //scaleOperation.Execute(); //var shiftOperation = scaleOperation.CreateChainedOperation(); #endregion var featuresToShift = _attributeViewModel.SelectedFeatures; var pivot = CurrentControlPoint; // must assign this to another variable since we will nullify it after this operation, where this operation is async and might not execute before nullifying. EditOperation shiftOperation = new EditOperation { Name = "Shift Features", ErrorMessage = "Error during shift", ProgressMessage = "Shifting in progress", // when we change this to true, it only selects features that moved (select == highlighted in blue), meaning those features will STAY highlighted. So change colour to red => not moved, even though they are selected SelectModifiedFeatures = true, ShowModalMessageAfterFailure = true }; //shiftOperation.Scale(featuresToShift, pivot, 2, 2); // get Incompatible Spatial Reference exception => screen vs. map coordinate? shiftOperation.Move(featuresToShift, dx, dy, dz); //shiftOperation.Delete(featuresToShift); // this works => selection must be correct? shiftOperation.Execute(); int countFeatures = 0; foreach (List <long> value in featuresToShift.Values) { countFeatures += value.Count; } ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(string.Format("dx = {0:0.000}\ndy = {1:0.000}\ndz = {2:0.000} \nNumber of features affected = {3}", dx, dy, dz, countFeatures), "Shifting and Scaling"); return shiftOperation.IsSucceeded; })); // end Run }
public static void ReadWriteBlobInspector() { #region Read and Write blob fields with the attribute inspector QueuedTask.Run(() => { //get selected feature into inspector var selectedFeatures = MapView.Active.Map.GetSelection(); var insp = new Inspector(); insp.Load(selectedFeatures.Keys.First(), selectedFeatures.Values.First()); //read file into memory stream var msr = new MemoryStream(); using (FileStream file = new FileStream(@"d:\images\Hydrant.jpg", FileMode.Open, FileAccess.Read)) { file.CopyTo(msr); } //put the memory stream in the blob field var op = new EditOperation(); op.Name = "Blob Inspector"; insp["Blobfield"] = msr; op.Modify(insp); op.Execute(); //read a blob field and save to a file //assume inspector has been loaded with a feature var msw = new MemoryStream(); msw = insp["Blobfield"] as MemoryStream; using (FileStream file = new FileStream(@"d:\temp\blob.jpg", FileMode.Create, FileAccess.Write)) { msw.WriteTo(file); } }); #endregion }
protected override void OnClick() { var polyLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First(); QueuedTask.Run(() => { var fc = polyLayer.GetTable() as FeatureClass; var fcDefinition = fc.GetDefinition(); Polygon outerRings = null; var editOperation = new EditOperation(); editOperation.Name = "Create outer ring"; using (var cursor = fc.Search()) { while (cursor.MoveNext()) { Feature feature = cursor.Current as Feature; outerRings = Module1.Current.GetOutermostRings(feature.GetShape() as Polygon); editOperation.Create(polyLayer, outerRings); } } editOperation.Execute(); }); }
public void EditOperation(UtilityNetwork utilityNetwork, AssetType poleAssetType, Guid poleGlobalID, AssetType transformerBankAssetType, Guid transformerBankGlobalID) { #region Create a utility network association // Create edit operation EditOperation editOperation = new EditOperation(); editOperation.Name = "Create structural attachment association"; // Create a RowHandle for the pole Element poleElement = utilityNetwork.CreateElement(poleAssetType, poleGlobalID); RowHandle poleRowHandle = new RowHandle(poleElement, utilityNetwork); // Create a RowHandle for the transformer bank Element transformerBankElement = utilityNetwork.CreateElement(transformerBankAssetType, transformerBankGlobalID); RowHandle transformerBankRowHandle = new RowHandle(transformerBankElement, utilityNetwork); // Attach the transformer bank to the pole StructuralAttachmentAssociationDescription structuralAttachmentAssociationDescription = new StructuralAttachmentAssociationDescription(poleRowHandle, transformerBankRowHandle); editOperation.Create(structuralAttachmentAssociationDescription); editOperation.Execute(); #endregion }
public void OpMgr() { var editOp = new EditOperation(); editOp.Name = "My Name"; editOp.Execute(); //elsewhere editOp.UndoAsync(); #region ProSnippet Group: Undo / Redo #endregion #region Undo/Redo the Most Recent Operation //undo if (MapView.Active.Map.OperationManager.CanUndo) { MapView.Active.Map.OperationManager.UndoAsync();//await as needed } //redo if (MapView.Active.Map.OperationManager.CanRedo) { MapView.Active.Map.OperationManager.RedoAsync();//await as needed } #endregion }
protected void UpdateAttrib() { QueuedTask.Run(() => { //get the geometry of the selected feature. var selectedFeatures = MapView.Active.Map.GetSelection(); var insp = new Inspector(); insp.Load(selectedFeatures.Keys.First(), selectedFeatures.Values.First()); var selGeom = insp.Shape; //var extPolyline = some geometry operation. var extPolyline = new MapPointBuilder(1.0, 1.0).ToGeometry(); //set the new geometry back on the feature insp.Shape = extPolyline; //update an attribute value insp["RouteNumber"] = 42; //create and execute the edit operation var op = new EditOperation() { Name = "Extend" }; op.Modify(insp); op.Execute(); }); }
private void MoveWalls(MapViewMouseButtonEventArgs e) { QueuedTask.Run(() => { Dictionary <MapMember, List <long> > selectedItems = GetSelectedItems(e); EditOperation editOperation = new EditOperation(); foreach (KeyValuePair <MapMember, List <long> > item in selectedItems) { BasicFeatureLayer layer = item.Key as BasicFeatureLayer; if (layer.ShapeType != ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolygon) { continue; } foreach (long oid in item.Value) { var feature = layer.Inspect(oid); double hoogte = double.Parse(feature["PandHoogte"].ToString()); int verdieping = int.Parse(feature["Verdieping"].ToString()); Geometry geom = feature.Shape.Clone(); Geometry removeGeometry = GeometryEngine.Scale(geom, geom.Extent.Center, 1.2, 1.2); Geometry wallGeometry = GeometryEngine.Scale(geom, geom.Extent.Center, 1.3, 1.3); editOperation.Scale(selectedItems, feature.Shape.Extent.Center, 0.9, 0.9); editOperation.Create(layer, wallGeometry, new Action <long>(x => OnExtractWalls(x, layer, removeGeometry, hoogte, verdieping))); } editOperation.Execute(); } MapView.Active.Map.SetSelection(null); }); }
protected override Task <bool> OnSketchCompleteAsync(ArcGIS.Core.Geometry.Geometry geometry) { //Check we only have one feature to extend to if (MapView.Active.Map.SelectionCount != 1) { MessageBox.Show("Please select one polyline or polygon feature to extend to", "Extend"); return(Task.FromResult(true)); } //Run on MCT return(QueuedTask.Run(() => { //get selected feature geometry var selectedFeatures = MapView.Active.Map.GetSelection(); var insp = new Inspector(); insp.Load(selectedFeatures.ToDictionary().Keys.First(), selectedFeatures.ToDictionary().Values.First()); var selGeom = GeometryEngine.Instance.Project(insp.Shape, MapView.Active.Map.SpatialReference); if (!(selGeom.GeometryType == GeometryType.Polygon || selGeom.GeometryType == GeometryType.Polyline)) { MessageBox.Show("Please choose as the selected feature either a polyline or polygon feature to extend to"); return false; } //find feature at the click var clickFeatures = MapView.Active.GetFeatures(geometry); var featuresOids = clickFeatures[clickFeatures.ToDictionary().Keys.First()]; insp.Load(clickFeatures.ToDictionary().First().Key, featuresOids.First()); var clickGeom = insp.Shape as Polyline; if (clickGeom == null) { MessageBox.Show("Please select a polyline feature to extend"); return false; } //extend the line to the poly? ArcGIS.Core.Geometry.Polyline extPolyline; extPolyline = GeometryEngine.Instance.Extend(clickGeom, (selGeom.GeometryType == GeometryType.Polygon ? GeometryEngine.Instance.Boundary(selGeom) as Polyline : selGeom as Polyline), ExtendFlags.Default); if (extPolyline == null) { MessageBox.Show(string.Format("Unable to extend the clicked {0} to the selected {1}", clickGeom.GeometryType, selGeom.GeometryType)); return false; } //set the new geometry back on the feature insp.Shape = extPolyline; //create and execute the edit operation var op = new EditOperation() { Name = "Extend", SelectModifiedFeatures = false, SelectNewFeatures = false }; op.Modify(insp); return op.Execute(); })); }
private void ExecuteRotateAnnotation() { var mapView = MapView.Active; if (mapView == null) { return; } try { QueuedTask.Run(() => { var selection = mapView.Map.GetSelection(); // 選択しているフィーチャクラスがある場合 if (selection.Count > 0) { var editOperation = new EditOperation(); // フィーチャクラスごとにループ foreach (var mapMember in selection) { var layer = mapMember.Key as BasicFeatureLayer; // アノテーションの場合 if (layer.GetType().Name == "AnnotationLayer") { using (var rowCursor = layer.GetSelection().Search(null)) { var inspector = new Inspector(); while (rowCursor.MoveNext()) { using (var row = rowCursor.Current) { // 角度更新 inspector.Load(layer, row.GetObjectID()); var annoProperties = inspector.GetAnnotationProperties(); annoProperties.Angle = _angle; inspector.SetAnnotationProperties(annoProperties); editOperation.Modify(inspector); } } } } } editOperation.Execute(); } }); } catch { MessageBox.Show("アノテーションの角度変更に失敗しました。"); } }
protected async void AssignFeaturesToRecord() { #region Assign features to active record string errorMessage = await QueuedTask.Run(() => { //check for selected layer if (MapView.Active.GetSelectedLayers().Count == 0) { return("Please select a source feature layer in the table of contents."); } //first get the feature layer that's selected in the table of contents var srcFeatLyr = MapView.Active.GetSelectedLayers().OfType <FeatureLayer>().FirstOrDefault(); var myParcelFabricLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <ParcelLayer>().FirstOrDefault(); if (myParcelFabricLayer == null) { return("No parcel layer found in the map."); } try { var theActiveRecord = myParcelFabricLayer.GetActiveRecord(); if (theActiveRecord == null) { return("There is no Active Record. Please set the active record and try again."); } var editOper = new EditOperation() { Name = "Assign Features to Record", ProgressMessage = "Assign Features to Record...", ShowModalMessageAfterFailure = true, SelectNewFeatures = true, SelectModifiedFeatures = false }; //add parcel type layers and their feature ids to a new KeyValuePair var ids = new List <long>(srcFeatLyr.GetSelection().GetObjectIDs()); var kvp = new KeyValuePair <MapMember, List <long> >(srcFeatLyr, ids); var sourceFeatures = new List <KeyValuePair <MapMember, List <long> > > { kvp }; editOper.AssignFeaturesToRecord(myParcelFabricLayer, sourceFeatures, theActiveRecord); if (!editOper.Execute()) { return(editOper.ErrorMessage); } } catch (Exception ex) { return(ex.Message); } return(""); }); if (!string.IsNullOrEmpty(errorMessage)) { MessageBox.Show(errorMessage, "Assign Features To Record."); } #endregion }
/// <summary> /// Illustrates how to use the HasValueChanged() method. /// </summary> /// <returns></returns> private static async Task FileGeodatabaseWorkFlow() { using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb")))) using (FeatureClass featureClass = fileGeodatabase.OpenDataset <FeatureClass>("PollingPlace")) { EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { QueryFilter queryFilter = new QueryFilter { WhereClause = "FULLADD LIKE '///%Lily Cache Ln///%'" }; using (RowCursor rowCursor = featureClass.Search(queryFilter, false)) { FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition(); int shapeFieldIndex = featureClassDefinition.FindField(featureClassDefinition.GetShapeField()); while (rowCursor.MoveNext()) { using (Feature feature = (Feature)rowCursor.Current) { MapPoint mapPoint = feature.GetShape() as MapPoint; // Will be false. bool beforeChange = feature.HasValueChanged(shapeFieldIndex); // In order to update the Map and/or the attribute table. // Has to be called before any changes are made to the row context.Invalidate(feature); MapPoint newShape = new MapPointBuilder(mapPoint.X + 10, mapPoint.Y, mapPoint.SpatialReference).ToGeometry(); feature.SetShape(newShape); // Will be true. bool afterChange = feature.HasValueChanged(shapeFieldIndex); feature.Store(); //Will be false. bool afterStore = feature.HasValueChanged(shapeFieldIndex); // Has to be called after the store too context.Invalidate(feature); } } } }, featureClass); bool editResult = editOperation.Execute(); //This is required to persist the changes to the disk. bool saveResult = await Project.Current.SaveEditsAsync(); } }
protected override Task <bool> OnSketchCompleteAsync(Geometry geometry) { //Run on MCT return(QueuedTask.Run(() => { //get the templates var map = MapView.Active.Map; IEnumerable <Layer> layers = map.GetLayersAsFlattenedList().AsEnumerable(); Layer mainLayer = layers.FirstOrDefault(l => l.Name == "main"); Layer mhLayer = layers.FirstOrDefault(l => l.Name == "manhole"); Layer conLayer = layers.FirstOrDefault(l => l.Name == "connector"); if ((mainLayer == null) || (mhLayer == null) || (conLayer == null)) { return false; } var mainTemplate = mainLayer.GetTemplate("main"); var mhTemplate = mhLayer.GetTemplate("manhole"); var conTemplate = conLayer.GetTemplate("connector"); if ((mainTemplate == null) || (mhTemplate == null) || (conTemplate == null)) { return false; } var op = new EditOperation() { Name = "Create main-connector-manhole", SelectModifiedFeatures = false, SelectNewFeatures = false }; //create the main geom var mainGeom = GeometryEngine.Instance.Move(geometry, 0, 0, -20); op.Create(mainTemplate, mainGeom); //create manhole points and connector foreach (var pnt in ((Polyline)geometry).Points) { //manhole point at sketch vertex op.Create(mhTemplate, pnt); //vertical connector between mahole and main var conPoints = new List <MapPoint> { pnt, //top of vertical connector GeometryEngine.Instance.Move(pnt, 0, 0, -20) as MapPoint //bottom of vertical connector }; var conPolyLine = PolylineBuilderEx.CreatePolyline(conPoints); op.Create(conTemplate, conPolyLine); } return op.Execute(); })); }
public Task <bool> ChangeAnnotationTextGraphicAsync(string xmlGraphic) { _lasterror = "";//reset if (string.IsNullOrEmpty(xmlGraphic)) { return(Task.FromResult(false)); } if (this.AnnotationLayer == null) { return(Task.FromResult(false)); } return(QueuedTask.Run(() => { if (!((AnnotationFeatureClass)AnnotationLayer.GetFeatureClass()).GetDefinition().AreSymbolOverridesAllowed()) { _lasterror = $"Overrides are not allowed on '{AnnotationLayer.GetFeatureClass().GetName()}'"; return false;//overrides are not allowed } EditOperation op = new EditOperation(); op.Name = $"Change annotation graphic [{count++}]"; op.SelectModifiedFeatures = true; var oid = this.AnnotationLayer.GetSelection().GetObjectIDs().First(); //At 2.1 we must use an edit operation Callback... op.Callback(context => { QueryFilter qf = new QueryFilter() { WhereClause = $"OBJECTID = {oid}" }; //Cursor must be non-recycling. Use the table ~not~ the layer..i.e. "GetTable().Search()" //annoLayer is ~your~ Annotation layer var rowCursor = this.AnnotationLayer.GetTable().Search(qf, false); rowCursor.MoveNext(); var annoFeature = rowCursor.Current as ArcGIS.Core.Data.Mapping.AnnotationFeature; // update the graphic CIMTextGraphic textGraphic = GraphicFromXml(xmlGraphic); annoFeature.SetGraphic(textGraphic); // store is required annoFeature.Store(); //refresh layer cache context.Invalidate(annoFeature); }, this.AnnotationLayer.GetTable()); var ok = op.Execute(); if (!ok) { _lasterror = op.ErrorMessage; } return ok; })); }
/// <summary> /// Illustrates deleting rows from a table in an enterprise geodatabase. /// </summary> /// <returns></returns> private static async Task EnterpriseGeodabaseWorkFlow() { // Opening a Non-Versioned SQL Server instance. DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer) { AuthenticationMode = AuthenticationMode.DBMS, // Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance. Instance = @"testMachine\testInstance", // Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database. Database = "LocalGovernment", // Provided that a login called gdb has been created and corresponding schema has been created with the required permissions. User = "******", Password = "******", Version = "dbo.DEFAULT" }; using (Geodatabase geodatabase = new Geodatabase((connectionProperties))) { using (Table enterpriseTable = geodatabase.OpenDataset <Table>("LocalGovernment.GDB.piCIPCost")) { EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { QueryFilter openCutFilter = new QueryFilter { WhereClause = "ACTION = 'Open Cut'" }; using (RowCursor rowCursor = enterpriseTable.Search(openCutFilter, false)) { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { // In order to update the Map and/or the attribute table. Has to be called before the delete context.Invalidate(row); row.Delete(); } } } }, enterpriseTable); bool editResult = editOperation.Execute(); // If the table is non-versioned this is a no-op. If it is versioned, we need the Save to be done for the edits to be persisted. bool saveResult = await Project.Current.SaveEditsAsync(); } } }
protected override async void OnClick() { // make sure there's an OID from a created feature if (Module1.CubeMultipatchObjectID == -1) { return; } //get the multipatch layer from the map var localSceneLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>() .FirstOrDefault(l => l.Name == "Cube" && l.ShapeType == esriGeometryType.esriGeometryMultiPatch); if (localSceneLayer == null) { return; } // get the multipatch shape using the Inspector var insp = new Inspector(); await insp.LoadAsync(localSceneLayer, Module1.CubeMultipatchObjectID); var multipatchFromScene = insp.Shape as Multipatch; // apply textures to the multipatch var multipatchWithTextures = ApplyTexturesToMultipatch(multipatchFromScene); // modify the multipatch geometry string msg = await QueuedTask.Run(() => { var op = new EditOperation(); op.Name = "Apply textures to multipatch"; // queue feature modification op.Modify(localSceneLayer, Module1.CubeMultipatchObjectID, multipatchWithTextures); // execute bool result = op.Execute(); // if successful if (result) { return(""); } // not successful, return any error message from the EditOperation return(op.ErrorMessage); }); // if there's an error, show it if (!string.IsNullOrEmpty(msg)) { MessageBox.Show($@"Multipatch update failed: " + msg); } }
private bool Execute(string description) { _editOperation.Name = description; bool result = _editOperation.Execute(); if (!result && _exception != null) { throw _exception; } return(result); }
internal void OnDeleteRouteButtonClick() { QueuedTask.Run(() => { using (var cursor = RoutesStandaloneTable.GetSelection().Search(null)) { var operation = new EditOperation(); cursor.MoveNext(); var routeRow = cursor.Current; string routeID = (string)routeRow[RouteID]; string routeName = (string)routeRow[RouteName]; operation.Name = $"Delete route: {routeName}"; operation.Delete(RoutesStandaloneTable, routeRow.GetObjectID()); var query = new QueryFilter() { WhereClause = $"{RouteID} = '{routeID}'" }; using (var segsCursor = RouteToTrailSegmentsTable.Search(query)) using (var headsCursor = RouteToTrailheadsTable.Search(query)) { while (segsCursor.MoveNext()) { operation.Delete(RouteToTrailSegmentsTable, segsCursor.Current.GetObjectID()); } while (headsCursor.MoveNext()) { operation.Delete(RouteToTrailheadsTable, headsCursor.Current.GetObjectID()); } } operation.Execute(); if (operation.IsSucceeded) { Notification notification = new Notification(); notification.Title = FrameworkApplication.Title; notification.Message = $"Route: \"{routeName}\" deleted successfully!"; FrameworkApplication.AddNotification(notification); RoutesStandaloneTable.ClearSelection(); } else { MessageBox.Show(operation.ErrorMessage); } } }); }
protected async void ChangeParcelType() { await QueuedTask.Run(() => { //check for selected layer if (MapView.Active.GetSelectedLayers().Count == 0) { System.Windows.MessageBox.Show("Please select a source layer in the table of contents", "Change Parcel Type"); return; } //first get the feature layer that's selected in the table of contents var sourcePolygonL = MapView.Active.GetSelectedLayers().OfType <FeatureLayer>().First(); var myParcelFabricLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <ParcelLayer>().FirstOrDefault(); string sTargetParcelType = "Tax"; //Microsoft.VisualBasic.Interaction.InputBox("Target Parcel Type:", "Copy Parcel Lines To", "Tax"); if (sTargetParcelType.Trim().Length == 0) { return; } #region Change parcel type var targetFeatLyr = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(l => l.Name == "Tax"); //the target parcel polygon feature layer if (myParcelFabricLayer == null || sourcePolygonL == null) { return; } //add polygon layers and the feature ids to change the type on to a new KeyValuePair var ids = new List <long>(sourcePolygonL.GetSelection().GetObjectIDs()); var kvp = new KeyValuePair <MapMember, List <long> >(sourcePolygonL, ids); var sourceFeatures = new List <KeyValuePair <MapMember, List <long> > > { kvp }; var editOper = new EditOperation() { Name = "Change Parcel Type", ProgressMessage = "Change Parcel Type...", ShowModalMessageAfterFailure = true, SelectNewFeatures = true, SelectModifiedFeatures = false }; editOper.ChangeParcelType(myParcelFabricLayer, sourceFeatures, targetFeatLyr, -1); editOper.Execute(); #endregion }); }
protected override Task<bool> OnSketchCompleteAsync(Geometry geometry) { //Run on MCT return QueuedTask.Run(() => { var op = new EditOperation(); op.Name = "Create main-connector-manhole"; op.SelectModifiedFeatures = false; op.SelectNewFeatures = false; //get the templates var map = MapView.Active.Map; var mainTemplate = map.FindLayers("main").First().GetTemplate("main"); var mhTemplate = map.FindLayers("Manhole").First().GetTemplate("Manhole"); var conTemplate = map.FindLayers("Connector").First().GetTemplate("Connector"); //create the main geom var mainGeom = GeometryEngine.Move(geometry, 0, 0, -20); op.Create(mainTemplate, mainGeom); //create manhole points and connector foreach (var pnt in ((Polyline)geometry).Points) { //manhole point at sketch vertex op.Create(mhTemplate, pnt); //vertical connector between mahole and main var conPoints = new List<MapPoint>(); conPoints.Add(pnt); //top of vertical connector conPoints.Add(GeometryEngine.Move(pnt, 0, 0, -20)); //bottom of vertical connector var conPolyLine = PolylineBuilder.CreatePolyline(conPoints); op.Create(conTemplate, conPolyLine); } return op.Execute(); }); }
/// <summary> /// Divide the first selected feature into equal parts or by map unit distance. /// </summary> /// <param name="numberOfParts">Number of parts to create.</param> /// <param name="value">Value for number or parts or distance.</param> /// <returns></returns> private static Task DivideLinesAsync(bool numberOfParts, double value) { //Run on MCT return QueuedTask.Run(() => { //get selected feature var selectedFeatures = MapView.Active.Map.GetSelection(); //get the layer of the selected feature var featLayer = selectedFeatures.Keys.First() as FeatureLayer; var oid = selectedFeatures.Values.First().First(); var feature = featLayer.Inspect(oid); //get geometry and length var origPolyLine = feature.Shape as Polyline; var origLength = GeometryEngine.Length(origPolyLine); //List of mappoint geometries for the split var splitPoints = new List<MapPoint>(); var enteredValue = (numberOfParts) ? origLength / value : value; var splitAtDistance = 0 + enteredValue; while (splitAtDistance < origLength) { //create a mapPoint at splitDistance and add to splitpoint list splitPoints.Add(GeometryEngine.MovePointAlongLine(origPolyLine, splitAtDistance, false, 0)); splitAtDistance += enteredValue; } //create and execute the edit operation var op = new EditOperation(); op.Name = "Divide Lines"; op.SelectModifiedFeatures = false; op.SelectNewFeatures = false; op.SplitAtPoints(featLayer, oid, splitPoints); op.Execute(); //clear selection //MapView.Active.Map.SetSelection(null); featLayer.ClearSelection(); }); }
/// <summary> /// Method to perform the cut operation on the geometry and change attributes /// </summary> /// <param name="geometry">Line geometry used to perform the cut against in the polygon features /// in the active map view.</param> /// <returns>If the cut operation was successful.</returns> protected Task<bool> ExecuteCut(Geometry geometry) { if (geometry == null) return Task.FromResult(false); // create an edit operation EditOperation cutOperation = new EditOperation(); cutOperation.Name = "Cut Elements"; cutOperation.ProgressMessage = "Working..."; cutOperation.CancelMessage = "Operation canceled."; cutOperation.ErrorMessage = "Error cutting polygons"; cutOperation.SelectModifiedFeatures = false; cutOperation.SelectNewFeatures = false; // create a collection of feature layers that can be edited var editableLayers = ActiveMapView.Map.GetLayersAsFlattenedList() .OfType<FeatureLayer>() .Where(lyr => lyr.CanEditData() == true).Where(lyr => lyr.ShapeType == esriGeometryType.esriGeometryPolygon); // ensure that there are target layers if (editableLayers.Count() == 0) return Task.FromResult(false); // initialize a list of ObjectIDs that need to be cut var cutOIDs = new List<long>(); // for each of the layers foreach (FeatureLayer editableFeatureLayer in editableLayers) { // find the features crossed by the sketch geometry var rowCursor = editableFeatureLayer.Search(geometry, SpatialRelationship.Crosses); // get the feature class associated with the layer Table fc = editableFeatureLayer.GetTable(); // find the field index for the 'Description' attribute int descriptionIndex = -1; descriptionIndex = fc.GetDefinition().FindField("Description"); // add the feature IDs into our prepared list while (rowCursor.MoveNext()) { var feature = rowCursor.Current as Feature; if (feature.GetShape() != null) { // we are looking for polygons are completely intersected by the cut line if (GeometryEngine.Relate(geometry, feature.GetShape(), "TT*F*****")) { // add the current feature to the overall list of features to cut cutOIDs.Add(rowCursor.Current.GetObjectID()); // adjust the attribute before the cut if (descriptionIndex != -1) cutOperation.Modify(rowCursor.Current, descriptionIndex, "Pro Sample"); } } } // add the elements to cut into the edit operation cutOperation.Cut(editableFeatureLayer, cutOIDs, geometry); } //execute the operation var operationResult = cutOperation.Execute(); return Task.FromResult(operationResult); }
/// <summary> /// Separate a selected multipart feature into individual features. /// </summary> protected override void OnClick() { //check for one selected feature if (MapView.Active.Map.SelectionCount != 1) { MessageBox.Show("Please select one multipart feature to explode", "Explode Multipart Feature"); return; } //run on MCT QueuedTask.Run(() => { //get selected feature geometry var selectedFeatures = MapView.Active.Map.GetSelection(); var insp = new Inspector(); insp.Load(selectedFeatures.Keys.First(), selectedFeatures.Values.First()); var selGeom = insp.Shape; var selGeomType = selGeom.GeometryType; //early checks for geometry type and single point in a multipoint if ( !(selGeomType == GeometryType.Multipoint || selGeomType == GeometryType.Polygon || selGeomType == GeometryType.Polyline) || selGeom.PointCount == 1) { MessageBox.Show("Please select a multipart feature to explode", "Explode Multipart Feature"); return; } //check if selected feature has multiple parts var mpGeom = selGeom as Multipart; if (mpGeom != null) if (mpGeom.PartCount < 2) { MessageBox.Show("Please select a multipart feature to explode","Explode Multipart Feature"); return; } //setup the edit operation var op = new EditOperation(); op.Name = "Explode Multipart Feature"; //handle geometry types switch(selGeomType) { case GeometryType.Multipoint: //create a new feature for each pointcount var mpoint = selGeom as Multipoint; for (var i = 0; i < mpoint.PointCount; i++) { //copy the original feature into a dictionary and update the shape. var newFeature = insp.ToDictionary(a => a.FieldName, a => a.CurrentValue); newFeature[insp.GeometryAttribute.FieldName] = new MultipointBuilder(mpoint.Points[i]).ToGeometry(); op.Create(insp.MapMember, newFeature); } break; case GeometryType.Polyline: //create a new feature for each polyline part for (var i = 0; i < mpGeom.PartCount; i++) { //copy the original feature into a dictionary and update the shape. var newFeature = insp.ToDictionary(a => a.FieldName, a => a.CurrentValue); newFeature[insp.GeometryAttribute.FieldName] = new PolylineBuilder(mpGeom.Parts[i]).ToGeometry(); op.Create(insp.MapMember, newFeature); } break; case GeometryType.Polygon: //ignore donut features for now //check if any part area is negative for (var i = 0; i < mpGeom.PartCount; i++) { if ((new PolygonBuilder(mpGeom.Parts[i]).ToGeometry()).Area < 0) { MessageBox.Show("Please select a non-donut polygon to explode", "Explode Mutltpart Feature"); return; } } //create a new feature for each polygon part for (var i = 0; i < mpGeom.PartCount; i++) { //copy the original feature into a dictionary and update the shape. var newFeature = insp.ToDictionary(a => a.FieldName, a => a.CurrentValue); newFeature[insp.GeometryAttribute.FieldName] = new PolygonBuilder(mpGeom.Parts[i]).ToGeometry(); op.Create(insp.MapMember, newFeature); } break; } //switch //delete the original feature and execute the creates //op.Delete(insp.MapMember, insp.ObjectID); //double cast to workaround 1.1 bug op.Delete(insp.MapMember, (long)(int)insp.ObjectIDAttribute.CurrentValue); op.Execute(); }); }