/// <summary> /// The on comboBox selection change event. /// </summary> /// <param name="item">The newly selected combo box item</param> protected async override void OnSelectionChange(ComboBoxItem item) { if (item == null) return; if (string.IsNullOrEmpty(item.Text)) return; string error = String.Empty; bool result = false; await QueuedTask.Run(async () => { var layer = MapView.Active.GetSelectedLayers()[0]; if (layer is FeatureLayer) { var featureLayer = layer as FeatureLayer; if (featureLayer.GetTable().GetDatastore() is UnknownDatastore) return; using (var table = featureLayer.GetTable()) { var subtypeField = table.GetDefinition().GetSubtypeField(); var code = table.GetDefinition().GetSubtypes().First(subtype => subtype.GetName().Equals(item.Text)).GetCode(); var queryFilter = new QueryFilter{WhereClause = string.Format("{0} = {1}", subtypeField, code)}; try { using (var rowCursor = table.Search(queryFilter, false)) { var editOperation = new EditOperation(); editOperation.Callback(context => { while (rowCursor.MoveNext()) { using (var row = rowCursor.Current) { context.Invalidate(row); row.Delete(); } } }, table); if (table.GetRegistrationType().Equals(RegistrationType.Nonversioned) && Project.Current.HasEdits) { error = "The FeatureClass is Non-Versioned and there are Unsaved Edits in the Project. Please save or discard the edits before attempting Non-Versioned Edits"; } else result = await editOperation.ExecuteAsync(); if (!result) error = editOperation.ErrorMessage; } } catch (Exception e) { error = e.Message; } } } }); if (!result) MessageBox.Show(String.Format("Could not delete features for subtype {0} : {1}", item.Text, error)); }
public bool Execute([NotNull] Action <EditOperation.IEditContext> action, [NotNull] string description, [NotNull] IEnumerable <Dataset> datasets) { _editOperation.Callback(GetWrappedAction(action), datasets); return(Execute(description)); }
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 }
/// <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(); } }
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(); } } }
private Task EditAnnotationSymbolAsync() { return(QueuedTask.Run(() => { EditOperation op = new EditOperation(); op.Name = "Change annotation graphic"; //At 2.1 we must use an edit operation Callback... op.Callback(context => { RowCursor rowCursor; if (SelectedLayer.GetSelection().GetCount() == 0) //The Selected layer has no selection { rowCursor = SelectedLayer.GetTable().Search(null, false); } else //Selection exists { var oidList = SelectedLayer.GetSelection().GetObjectIDs(); var oid = SelectedLayer.GetTable().GetDefinition().GetObjectIDField(); QueryFilter qf = new QueryFilter() { WhereClause = string.Format("({0} in ({1}))", oid, string.Join(",", oidList)) }; //Cursor must be non-recycling. Use the table ~not~ the layer..i.e. "GetTable().Search()" //SelectedLayer is ~your~ Annotation layer rowCursor = SelectedLayer.GetTable().Search(qf, false); } while (rowCursor.MoveNext()) { using (var af = rowCursor.Current as AnnotationFeature) { var graphic = af.GetGraphic() as CIMTextGraphic; graphic.Symbol = SelectedTextStyle.Symbol.MakeSymbolReference(); // update the graphic af.SetGraphic(graphic); // store is required af.Store(); //refresh layer cache context.Invalidate(af); } } }, SelectedLayer.GetTable()); op.Execute(); //set the label's visiblity if (IsLabelVisible) { (SelectedLayer as AnnotationLayer).SetVisibility(true); } })); }
//Illustrating updating a row in a File GDB private static async Task FileGeodatabaseWorkFlow() { using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb")))) using (Table table = fileGeodatabase.OpenDataset <Table>("EmployeeInfo")) { EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { QueryFilter queryFilter = new QueryFilter { WhereClause = "COSTCTRN = 'Information Technology'" }; using (RowCursor rowCursor = table.Search(queryFilter, false)) { const string newITBuilding = "RD"; while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { // 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(row); row["COSTCTR"] = 4900; row["COSTCTRN"] = "Research & Development"; // Rebrand It as R&D if you want to. row["LOCATION"] = Convert.ToString(row["LOCATION"]).Replace(Convert.ToString(row["BUILDING"]), newITBuilding); row["BUILDING"] = newITBuilding; row.Store(); // Has to be called after the store too context.Invalidate(row); } } } }, table); bool editResult = editOperation.Execute(); //This is required to persist the changes to the disk. bool saveResult = await Project.Current.SaveEditsAsync(); } }
private async Task AddResultFeatures(FeatureClass fc) { EditOperation featOp = new EditOperation(); featOp.Callback(context => { foreach (Result result in Results) { using (RowBuffer row = fc.CreateRowBuffer()) { row["VehicleYear"] = result.Vehicle.Year; row["VehicleMake"] = result.Vehicle.Make; row["VehicleModel"] = result.Vehicle.Model; row["Vehicletype"] = result.Vehicle.Type; row["VehicleMPG"] = result.Vehicle.Mpg; row["OriginalSymbolColor"] = result.Color; row["PADDZone"] = result.PaddZone; row["DOEGasPricePerGallon"] = result.DollarsPerGallon; row["MilesPerDollar"] = result.MilesPerDollar; row["DriveDistanceMiles"] = result.DriveDistMi; row["ResultDateTime"] = result.ResultDateTimeUTC; row[fc.GetDefinition().GetShapeField()] = result.DriveServiceArea; using (Feature feat = fc.CreateRow(row)) { context.Invalidate(feat); } } } }, fc); bool success = await featOp.ExecuteAsync(); if (!success) { throw new Exception("Error adding result features: " + featOp.ErrorMessage); } success = await Project.Current.SaveEditsAsync(); if (!success) { throw new Exception("Failure while saving result features"); } }
internal void OnCancelButtonClick() { Reset(); QueuedTask.Run(() => { EditOperation operation = new EditOperation(); operation.Name = "Cancel New Route"; FeatureClass featureClass = TempSegmentsLayer.GetFeatureClass(); operation.Callback(context => { featureClass.DeleteRows(new QueryFilter()); context.Invalidate(featureClass); }, featureClass); bool success = operation.Execute(); if (!success) { MessageBox.Show("Error cancelling new route!"); } }); }
// /// <summary> /// Illustrates deleting features from a feature class in a file geodatabase. /// </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)) { 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(); } } } }, featureClass); bool editResult = editOperation.Execute(); //This is required to persist the changes to the disk. bool saveResult = await Project.Current.SaveEditsAsync(); } } }
public void MainMethodCode() { using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb")))) using (Table table = fileGeodatabase.OpenDataset <Table>("EmployeeInfo")) { QueryFilter queryFilter = new QueryFilter { WhereClause = "COSTCTRN = 'Information Technology'" }; using (Selection selection = table.Select(queryFilter, SelectionType.ObjectID, SelectionOption.Normal)) { // The result is a mapping between those object ids which failed validation and the reason why the validation failed (a string message). IReadOnlyDictionary <long, string> validationResult = table.Validate(selection); RowCursor rowCursor = table.Search(queryFilter, false); List <Row> rows = new List <Row>(); try { while (rowCursor.MoveNext()) { rows.Add(rowCursor.Current); } // This is equivalent to the validation performed using the selection. IReadOnlyDictionary <long, string> equivalentValidationResult = table.Validate(rows); // Again this is equivalent to both the above results. IReadOnlyDictionary <long, string> anotherEquivalentResult = table.Validate(queryFilter); } finally { rowCursor.Dispose(); Dispose(rows); } } } // 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")) { QueryFilter openCutFilter = new QueryFilter { WhereClause = "ACTION = 'Open Cut'" }; using (Selection openCutSelection = enterpriseTable.Select(openCutFilter, SelectionType.ObjectID, SelectionOption.Normal)) { // Remember that validation cost is directly proprtional to the number of Rows validated. So, select the set of rows to be validated // judiciously. This will be empty because all the rows in the piCIPCost table are valid. IReadOnlyDictionary <long, string> emptyDictionary = enterpriseTable.Validate(openCutSelection); // We are adding an invalid row to illustrate a case where the validation result is not empty. long invalidRowObjectID = -1; EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { RowBuffer rowBuffer = null; Row row = null; try { TableDefinition tableDefinition = enterpriseTable.GetDefinition(); rowBuffer = enterpriseTable.CreateRowBuffer(); rowBuffer["ASSETNA"] = "wMain"; rowBuffer["COST"] = 700; rowBuffer["ACTION"] = "Open Cut"; // Note that this is an invalid subtype value. rowBuffer[tableDefinition.GetSubtypeField()] = 4; row = enterpriseTable.CreateRow(rowBuffer); //To Indicate that the attribute table has to be updated context.Invalidate(row); invalidRowObjectID = row.GetObjectID(); } catch (GeodatabaseException exObj) { Console.WriteLine(exObj); } finally { if (rowBuffer != null) { rowBuffer.Dispose(); } if (row != null) { row.Dispose(); } } }, enterpriseTable); editOperation.Execute(); // This will have one keypair value for the invalid row that was added. IReadOnlyDictionary <long, string> result = enterpriseTable.Validate(openCutFilter); // This will say "invalid subtype code". string errorMessage = result[invalidRowObjectID]; } } }
/// <summary> /// This method will /// 1. Make sure if a Feature Layer is selected. /// 2. The Workspace is not null /// 3. Make sure that the workspace is an Enterprise SQL Server Geodatabase Workspace /// /// and then create a new version (In a Queued Task) /// and Connect to the newly created version and delete all the features for the selected subtype (In a separate QueuedTask) /// </summary> /// <param name="item">The newly selected combo box item</param> protected override async void OnSelectionChange(ComboBoxItem item) { if (item == null) return; if (string.IsNullOrEmpty(item.Text)) return; Layer layer = MapView.Active.GetSelectedLayers()[0]; FeatureLayer featureLayer = null; if (layer is FeatureLayer) { featureLayer = layer as FeatureLayer; Geodatabase geodatabase = null; await QueuedTask.Run(() => geodatabase = (featureLayer.GetTable().GetDatastore() as Geodatabase)); using (geodatabase) { if (geodatabase == null) return; } } else return; EnterpriseDatabaseType enterpriseDatabaseType = EnterpriseDatabaseType.Unknown; await QueuedTask.Run(() => { using (Table table = (MapView.Active.GetSelectedLayers()[0] as FeatureLayer).GetTable()) { try { enterpriseDatabaseType = (table.GetDatastore() as Geodatabase).GetEnterpriseDatabaseType(); } catch (InvalidOperationException e) { } } }); if (enterpriseDatabaseType != EnterpriseDatabaseType.SQLServer) { Enabled = false; return; } string versionName = String.Empty; await QueuedTask.Run(async () => { using (Table table = featureLayer.GetTable()) { versionName = await CreateVersion(table); } }); if (versionName == null) return; await QueuedTask.Run(async () => { using (Table table = featureLayer.GetTable()) { if (table.GetRegistrationType().Equals(RegistrationType.Nonversioned)) return; } }); QueuedTask.Run(async () => { using (Table table = featureLayer.GetTable()) { string subtypeField = table.GetDefinition().GetSubtypeField(); int code = table.GetDefinition().GetSubtypes().First(subtype => subtype.GetName().Equals(item.Text)).GetCode(); QueryFilter queryFilter = new QueryFilter{WhereClause = string.Format("{0} = {1}", subtypeField, code)}; try { VersionManager versionManager = (table.GetDatastore() as Geodatabase).GetVersionManager(); Version newVersion = versionManager.GetVersions().First(version => version.GetName().Contains(versionName)); Geodatabase newVersionGeodatabase = newVersion.Connect(); using (Table newVersionTable = newVersionGeodatabase.OpenDataset<Table>(table.GetName())) { using (var rowCursor = newVersionTable.Search(queryFilter, false)) { EditOperation editOperation = new EditOperation { EditOperationType = EditOperationType.Long, Name = "Delete Based On Subtype" }; editOperation.Callback(context => { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { context.Invalidate(row); row.Delete(); } } }, newVersionTable); bool result = await editOperation.ExecuteAsync(); if (!result) MessageBox.Show(String.Format("Could not delete features for subtype {0} : {1}", item.Text, editOperation.ErrorMessage)); await Project.Current.SaveEditsAsync(); } } } catch (Exception e) { Console.WriteLine(e); } } }); }
// Illustrates creating a row in a File GDB. private static async Task FileGeodatabaseWorkFlow() { using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb")))) using (Table table = fileGeodatabase.OpenDataset <Table>("EmployeeInfo")) { EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { RowBuffer rowBuffer = null; Row row = null; try { TableDefinition tableDefinition = table.GetDefinition(); int firstNameIndex = tableDefinition.FindField("FIRSTNAME"); rowBuffer = table.CreateRowBuffer(); // Either the field index or the field name can be used in the indexer. rowBuffer[firstNameIndex] = "John"; rowBuffer["LASTNAME"] = "Doe"; rowBuffer["COSTCTR"] = 4470; rowBuffer["COSTCTRN"] = "Information Technology"; rowBuffer["EXTENSION"] = 12345; rowBuffer["EMAIL"] = "*****@*****.**"; rowBuffer["BUILDING"] = "MC"; rowBuffer["FLOOR"] = 1; rowBuffer["WING"] = "E"; rowBuffer["OFFICE"] = 58; rowBuffer["LOCATION"] = "MC1E58"; row = table.CreateRow(rowBuffer); //To Indicate that the attribute table has to be updated context.Invalidate(row); // Do some other processing with the row. } catch (GeodatabaseException exObj) { Console.WriteLine(exObj); } finally { if (rowBuffer != null) { rowBuffer.Dispose(); } if (row != null) { row.Dispose(); } } }, table); 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(); } }
/// <summary> /// Method used to create a mask for geoprocessing environment /// Will buffer around each observer at the max distance to create mask /// </summary> /// <param name="maskFeatureClassName"></param> /// <param name="bufferDistance"></param> /// <returns>Task</returns> private async Task CreateMask(string maskFeatureClassName, double bufferDistance, SpatialReference surfaceSR) { // create new await FeatureClassHelper.CreateLayer(maskFeatureClassName, "POLYGON", false, false); try { string message = String.Empty; bool creationResult = false; await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(async() => { using (Geodatabase geodatabase = new Geodatabase(CoreModule.CurrentProject.DefaultGeodatabasePath)) using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset <FeatureClass>(maskFeatureClassName)) using (FeatureClassDefinition fcDefinition = enterpriseFeatureClass.GetDefinition()) { EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { try { var shapeFieldName = fcDefinition.GetShapeField(); foreach (var observer in ObserverAddInPoints) { using (var rowBuffer = enterpriseFeatureClass.CreateRowBuffer()) { // Either the field index or the field name can be used in the indexer. // project the point here or the buffer tool may use an angular unit and run forever var point = GeometryEngine.Project(observer.Point, surfaceSR); var polygon = GeometryEngine.Buffer(point, bufferDistance); rowBuffer[shapeFieldName] = polygon; using (var feature = enterpriseFeatureClass.CreateRow(rowBuffer)) { //To Indicate that the attribute table has to be updated context.Invalidate(feature); } } } } catch (GeodatabaseException exObj) { message = exObj.Message; } }, enterpriseFeatureClass); creationResult = await editOperation.ExecuteAsync(); if (!creationResult) { message = editOperation.ErrorMessage; } await Project.Current.SaveEditsAsync(); } }); if (!creationResult) { MessageBox.Show(message); } } catch (Exception ex) { Debug.Print(ex.Message); } }
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 (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.FacilitySite")) { EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { RowBuffer rowBuffer = null; Feature feature = null; try { FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition(); int facilityIdIndex = facilitySiteDefinition.FindField("FACILITYID"); rowBuffer = enterpriseFeatureClass.CreateRowBuffer(); // Either the field index or the field name can be used in the indexer. rowBuffer[facilityIdIndex] = "FAC-400"; rowBuffer["NAME"] = "Griffith Park"; rowBuffer["OWNTYPE"] = "Municipal"; rowBuffer["FCODE"] = "Park"; // Add it to Public Attractions Subtype. rowBuffer[facilitySiteDefinition.GetSubtypeField()] = 820; List <Coordinate2D> newCoordinates = new List <Coordinate2D> { new Coordinate2D(1021570, 1880583), new Coordinate2D(1028730, 1880994), new Coordinate2D(1029718, 1875644), new Coordinate2D(1021405, 1875397) }; rowBuffer[facilitySiteDefinition.GetShapeField()] = new PolygonBuilder(newCoordinates).ToGeometry(); feature = enterpriseFeatureClass.CreateRow(rowBuffer); //To Indicate that the Map has to draw this feature and/or the attribute table to be updated context.Invalidate(feature); long objectID = feature.GetObjectID(); Polygon polygon = feature.GetShape() as Polygon; // Do some other processing with the newly-created feature. } catch (GeodatabaseException exObj) { Console.WriteLine(exObj); } finally { if (rowBuffer != null) { rowBuffer.Dispose(); } if (feature != null) { feature.Dispose(); } } }, enterpriseFeatureClass); 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(); } }
// Illustrates creating a feature in a File GDB. 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")) { RowBuffer rowBuffer = null; Feature feature = null; try { EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition(); int nameIndex = featureClassDefinition.FindField("NAME"); rowBuffer = featureClass.CreateRowBuffer(); // Either the field index or the field name can be used in the indexer. rowBuffer[nameIndex] = "New School"; rowBuffer["POLLINGID"] = "260"; rowBuffer["FULLADD"] = "100 New Street"; rowBuffer["CITY"] = "Naperville"; rowBuffer["STATE"] = "IL"; rowBuffer["OPERHOURS"] = "Yes"; rowBuffer["HANDICAP"] = "6.00am=7.00pm"; rowBuffer["NEXTELECT"] = "11/6/2012"; rowBuffer["REGDATE"] = "8/6/2012"; rowBuffer["PHONE"] = "815-740-4782"; rowBuffer["EMAIL"] = "*****@*****.**"; rowBuffer[featureClassDefinition.GetShapeField()] = new MapPointBuilder(1028367, 1809789).ToGeometry(); feature = featureClass.CreateRow(rowBuffer); //To Indicate that the Map has to draw this feature and/or the attribute table to be updated context.Invalidate(feature); // Do some other processing with the newly-created feature. }, featureClass); bool editResult = editOperation.Execute(); // At this point the changes are visible in the process, but not persisted/visible outside. long objectID = feature.GetObjectID(); MapPoint mapPoint = feature.GetShape() as MapPoint; // 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(); } catch (GeodatabaseException exObj) { Console.WriteLine(exObj); throw; } finally { if (rowBuffer != null) { rowBuffer.Dispose(); } if (feature != null) { feature.Dispose(); } } } }
private async void SaveEdits(object parameter) { string message = String.Empty; bool modificationResult = false; IEnumerable<GDBProjectItem> gdbProjectItems = Project.Current.GetItems<GDBProjectItem>(); await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { try { foreach (GDBProjectItem gdbProjectItem in gdbProjectItems) { using (Datastore datastore = gdbProjectItem.GetDatastore()) { //Unsupported datastores (non File GDB and non Enterprise GDB) will be of type UnknownDatastore if (datastore is UnknownDatastore) continue; Geodatabase geodatabase = datastore as Geodatabase; //Find the correct gdb for the one with the complete schema string geodatabasePath = geodatabase.GetPath(); if (geodatabasePath == ProSymbolEditorModule.Current.MilitaryOverlaySchema.DatabaseName) { EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { string oidFieldName = _selectedSelectedFeature.FeatureLayer.GetTable().GetDefinition().GetObjectIDField(); QueryFilter queryFilter = new QueryFilter(); queryFilter.WhereClause = string.Format("{0} = {1}", oidFieldName, _selectedSelectedFeature.ObjectId); using (RowCursor cursor = _selectedSelectedFeature.FeatureLayer.GetTable().Search(queryFilter, false)) { while (cursor.MoveNext()) { Feature feature = (Feature)cursor.Current; // 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); _symbolAttributeSet.PopulateFeatureWithAttributes(ref feature); feature.Store(); // Has to be called after the store too context.Invalidate(feature); } } }, _selectedSelectedFeature.FeatureLayer.GetTable()); var task = editOperation.ExecuteAsync(); modificationResult = task.Result; if (!modificationResult) message = editOperation.ErrorMessage; } } } } catch (Exception exception) { System.Console.WriteLine(exception.Message); } }); if (!modificationResult) { MessageBox.Show(message); } }
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 (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.FacilitySite")) { FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition(); int ownTypeIndex = facilitySiteDefinition.FindField("OWNTYPE"); int areaIndex = facilitySiteDefinition.FindField(facilitySiteDefinition.GetAreaField()); EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { QueryFilter queryFilter = new QueryFilter { WhereClause = "FCODE = 'Hazardous Materials Facility' AND OWNTYPE = 'Private'" }; using (RowCursor rowCursor = enterpriseFeatureClass.Search(queryFilter, false)) { while (rowCursor.MoveNext()) { using (Feature feature = (Feature)rowCursor.Current) { // 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); // Transfer all Hazardous Material Facilities to the City. feature[ownTypeIndex] = "Municipal"; if (Convert.ToDouble(feature[areaIndex]) > 50000) { // Set the Shape of the feature to whatever you need. List <Coordinate2D> newCoordinates = new List <Coordinate2D> { new Coordinate2D(1021570, 1880583), new Coordinate2D(1028730, 1880994), new Coordinate2D(1029718, 1875644), new Coordinate2D(1021405, 1875397) }; feature.SetShape(new PolygonBuilder(newCoordinates).ToGeometry()); } feature.Store(); // Has to be called after the store too context.Invalidate(feature); } } } }, enterpriseFeatureClass); 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(); } }
/// <summary> /// Method used to create a mask for geoprocessing environment /// Will buffer around each observer at the max distance to create mask /// </summary> /// <param name="maskFeatureClassName"></param> /// <param name="bufferDistance"></param> /// <returns>Task</returns> private async Task CreateMask(string maskFeatureClassName, double minDistanceInMapUnits, double maxDistanceInMapUnits, double horizontalStartAngleInDegrees, double horizontalEndAngleInDegrees, SpatialReference surfaceSR, ObservableCollection <AddInPoint> observerPoints, bool constructRangeFans = false) { // create new await FeatureClassHelper.CreateLayer(FeatureDatasetName, maskFeatureClassName, "POLYGON", false, false); try { string message = String.Empty; bool creationResult = false; await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(async() => { using (Geodatabase geodatabase = new Geodatabase(FeatureClassHelper.FgdbFileToConnectionPath(CoreModule.CurrentProject.DefaultGeodatabasePath))) using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset <FeatureClass>(maskFeatureClassName)) using (FeatureClassDefinition fcDefinition = enterpriseFeatureClass.GetDefinition()) { EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { try { var shapeFieldName = fcDefinition.GetShapeField(); foreach (var observer in observerPoints) { using (var rowBuffer = enterpriseFeatureClass.CreateRowBuffer()) { // Either the field index or the field name can be used in the indexer. // project the point here or the buffer tool may use an angular unit and run forever var point = GeometryEngine.Instance.Project(observer.Point, surfaceSR); Geometry polygon = null; if (constructRangeFans) { polygon = GeometryHelper.ConstructRangeFan(point as MapPoint, minDistanceInMapUnits, maxDistanceInMapUnits, horizontalStartAngleInDegrees, horizontalEndAngleInDegrees, surfaceSR); } else { polygon = GeometryEngine.Instance.Buffer(point, maxDistanceInMapUnits); } rowBuffer[shapeFieldName] = polygon; Feature feature = enterpriseFeatureClass.CreateRow(rowBuffer); feature.Store(); context.Invalidate(feature); } // using } // for each } catch (GeodatabaseException exObj) { message = exObj.Message; } }, enterpriseFeatureClass); creationResult = await editOperation.ExecuteAsync(); if (!creationResult) { message = editOperation.ErrorMessage; } await Project.Current.SaveEditsAsync(); } }); if (!creationResult) { MessageBox.Show(message); } } catch (Exception ex) { Debug.Print(ex.Message); } }
private async Task <string> AddFeatureToLayer(Geometry geom, RangeAttributes attributes) { string message = String.Empty; if (attributes == null) { message = "Attributes are Empty"; // For debug does not need to be resource return(message); } FeatureClass ringFeatureClass = await GetFeatureClass(addToMapIfNotPresent : true); if (ringFeatureClass == null) { message = DistanceAndDirectionLibrary.Properties.Resources.ErrorFeatureClassNotFound + this.GetLayerName(); return(message); } bool creationResult = false; FeatureClassDefinition ringDefinition = ringFeatureClass.GetDefinition(); EditOperation editOperation = new EditOperation(); editOperation.Name = "Ring Feature Insert"; editOperation.Callback(context => { try { RowBuffer rowBuffer = ringFeatureClass.CreateRowBuffer(); if (ringDefinition.FindField("Distance") >= 0) { rowBuffer["Distance"] = attributes.distance; // Double } if (ringDefinition.FindField("DistUnit") >= 0) { rowBuffer["DistUnit"] = attributes.distanceunit; // Text } if (ringDefinition.FindField("Rings") >= 0) { rowBuffer["Rings"] = attributes.numRings; // Double } if (ringDefinition.FindField("CenterX") >= 0) { rowBuffer["CenterX"] = attributes.centerx; // Double } if (ringDefinition.FindField("CenterY") >= 0) { rowBuffer["CenterY"] = attributes.centery; // Double } if (ringDefinition.FindField("RRType") >= 0) { rowBuffer["RRType"] = attributes.ringorradial; // Double } // Ensure Z removed (this feature class does not have Z) var geoNoZ = geom; if (geom.HasZ) { PolylineBuilder pb = new PolylineBuilder((Polyline)geom); pb.HasZ = false; geoNoZ = pb.ToGeometry(); } rowBuffer["Shape"] = GeometryEngine.Instance.Project(geoNoZ, ringDefinition.GetSpatialReference()); Feature feature = ringFeatureClass.CreateRow(rowBuffer); feature.Store(); //To Indicate that the attribute table has to be updated context.Invalidate(feature); } catch (GeodatabaseException geodatabaseException) { message = geodatabaseException.Message; } catch (Exception ex) { message = ex.Message; } }, ringFeatureClass); await QueuedTask.Run(async() => { creationResult = await editOperation.ExecuteAsync(); }); if (!creationResult) { message = editOperation.ErrorMessage; } return(message); }
// Reset Settings Based on Current Settings public async void ResetValues(string settingsValue) { // *** Check to ensure the densitysettings are set. If not, show a warning and deactivate tool. if (HighSetting == 0 || MediumSetting == 0 || LowSetting == 0 || TargetSetting == 0) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("An empty setting value exists. All settings are required to use this tool.", "Warning!"); // ** End if there are not complete settings return; } // else proceed with confirming a reset is desired. else { if (settingsValue == "current") { // Prompt for confirmation, and if answer is no, return. var result = ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Reset all values to CURRENT settings?", "RESET VALUES", MessageBoxButton.OKCancel, MessageBoxImage.Asterisk); // Return if cancel value is chosen if (Convert.ToString(result) == "Cancel") { return; } } else if (settingsValue == "default") { // Prompt for confirmation, and if answer is no, return. var result = ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Reset all values to DEFAULT settings?", "RESET VALUES", MessageBoxButton.OKCancel, MessageBoxImage.Asterisk); // Return if cancel value is chosen if (Convert.ToString(result) == "Cancel") { return; } } } FeatureLayer CrowdLayer = MapView.Active.Map.Layers.First(layer => layer.Name.Equals("CrowdPlanning")) as FeatureLayer; if (CrowdLayer == null) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("CrowdPlanning Layer is not found"); return; } ArcGIS.Core.Data.Table CrowdTable = await QueuedTask.Run(() => CrowdLayer.GetTable()); var editOperation = new EditOperation(); editOperation.Callback(context => { QueryFilter QF = new QueryFilter { WhereClause = "LOW > 0" }; RowCursor CrowdRow = CrowdTable.Search(QF, false); while (CrowdRow.MoveNext()) { using (Row currentRow = CrowdRow.Current) { var squarefeetValue = currentRow["Shape_Area"]; long squarefeetValueLong; squarefeetValueLong = Convert.ToInt64(squarefeetValue); if (settingsValue == "current") { currentRow["High"] = (squarefeetValueLong / HighSetting); currentRow["Medium"] = (squarefeetValueLong / MediumSetting); currentRow["Low"] = (squarefeetValueLong / LowSetting); currentRow["TargetSetting"] = TargetSetting; currentRow["HighSetting"] = HighSetting; currentRow["MediumSetting"] = MediumSetting; currentRow["LowSetting"] = LowSetting; } else if (settingsValue == "default") { currentRow["High"] = squarefeetValueLong / 2.5; currentRow["Medium"] = squarefeetValueLong / 4.5; currentRow["Low"] = squarefeetValueLong / 10; currentRow["TargetSetting"] = TargetSetting; currentRow["HighSetting"] = 2.5; currentRow["MediumSetting"] = 4.5; currentRow["LowSetting"] = 10; } // Store the values currentRow.Store(); // Has to be called after the store too. context.Invalidate(currentRow); } } CrowdTable.Dispose(); // close the editOperation.Callback(context }, CrowdTable); await editOperation.ExecuteAsync(); GetTotalValues(); }
/// <summary> /// The on comboBox selection change event. /// </summary> /// <param name="item">The newly selected combo box item</param> protected override void OnSelectionChange(ComboBoxItem item) { if (item == null) { return; } if (string.IsNullOrEmpty(item.Text)) { return; } QueuedTask.Run(async() => { var layer = MappingModule.ActiveTOC.SelectedLayers[0]; if (layer is FeatureLayer) { var featureLayer = layer as FeatureLayer; if (featureLayer.GetTable().GetWorkspace() == null) { return; } using (var table = featureLayer.GetTable()) { var subtypeField = table.GetDefinition().GetSubtypeField(); var code = table.GetDefinition().GetSubtypes().First(subtype => subtype.GetName().Equals(item.Text)).GetCode(); var queryFilter = new QueryFilter { WhereClause = string.Format("{0} = {1}", subtypeField, code) }; try { using (var rowCursor = table.Search(queryFilter, false)) { var editOperation = new EditOperation { Versioned = false }; editOperation.Callback(context => { while (rowCursor.MoveNext()) { using (var row = rowCursor.Current) { row.Delete(); } } context.invalidate(table); }, table.GetWorkspace()); var result = await editOperation.ExecuteAsync(); if (!result) { MessageBox.Show(String.Format("Could not delete features for subtype {0} : {1}", item.Text, editOperation.ErrorMessage)); } } } catch (Exception e) { Console.WriteLine(e); } } } }); }
/// <summary> /// This method will /// 1. Make sure if a Feature Layer is selected. /// 2. The Workspace is not null /// 3. Make sure that the workspace is an Enterprise SQL Server Geodatabase Workspace /// /// and then create a new version (In a Queued Task) /// and Connect to the newly created version and delete all the features for the selected subtype (In a separate QueuedTask) /// </summary> /// <param name="item">The newly selected combo box item</param> protected override async void OnSelectionChange(ComboBoxItem item) { await QueuedTask.Run(async() => { if (item == null) { return; } if (string.IsNullOrEmpty(item.Text)) { return; } Layer layer = MapView.Active.GetSelectedLayers()[0]; if (layer is FeatureLayer featureLayer) { using (Geodatabase geodatabase = featureLayer.GetTable().GetDatastore() as Geodatabase) using (Table table = featureLayer.GetTable()) { if (geodatabase == null) { return; } EnterpriseDatabaseType enterpriseDatabaseType = ((DatabaseConnectionProperties)geodatabase.GetConnector()).DBMS; if (enterpriseDatabaseType != EnterpriseDatabaseType.SQLServer) { Enabled = false; return; } if (table.GetRegistrationType().Equals(RegistrationType.Nonversioned)) { return; } using (Version newVersion = await CreateVersionAsync(table)) using (Geodatabase newVersionGeodatabase = newVersion.Connect()) using (Table newVersionTable = newVersionGeodatabase.OpenDataset <Table>(table.GetName())) { string subtypeField = table.GetDefinition().GetSubtypeField(); int code = table.GetDefinition().GetSubtypes().First(subtype => subtype.GetName().Equals(item.Text)).GetCode(); QueryFilter queryFilter = new QueryFilter { WhereClause = string.Format("{0}={1}", subtypeField, code) }; using (var rowCursor = newVersionTable.Search(queryFilter, false)) { EditOperation editOperation = new EditOperation { EditOperationType = EditOperationType.Long, Name = "Delete Based On Subtype" }; editOperation.Callback(context => { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { context.Invalidate(row); row.Delete(); } } }, newVersionTable); bool result = await editOperation.ExecuteAsync(); if (!result) { MessageBox.Show(String.Format("Could not delete features for subtype {0} : {1}", item.Text, editOperation.ErrorMessage)); } await Project.Current.SaveEditsAsync(); } } } } }); }
public static async Task <BA_ReturnCode> UpdateFeatureAttributesAsync(Uri gdbUri, string featureClassName, QueryFilter oQueryFilter, IDictionary <string, string> dictEdits) { bool modificationResult = false; string errorMsg = ""; await QueuedTask.Run(() => { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(gdbUri))) using (FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>(featureClassName)) { FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition(); EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { using (RowCursor rowCursor = featureClass.Search(oQueryFilter, false)) { while (rowCursor.MoveNext()) { using (Feature feature = (Feature)rowCursor.Current) { // In order to update the the attribute table has to be called before any changes are made to the row context.Invalidate(feature); // Loop through fields to update foreach (string strKey in dictEdits.Keys) { int idxRow = featureClassDefinition.FindField(strKey); if (idxRow > -1) { feature[idxRow] = dictEdits[strKey]; } } feature.Store(); // Has to be called after the store too context.Invalidate(feature); } } } }, featureClass); try { modificationResult = editOperation.Execute(); if (!modificationResult) { errorMsg = editOperation.ErrorMessage; } } catch (GeodatabaseException exObj) { errorMsg = exObj.Message; } } }); if (String.IsNullOrEmpty(errorMsg)) { await Project.Current.SaveEditsAsync(); return(BA_ReturnCode.Success); } else { if (Project.Current.HasEdits) { await Project.Current.DiscardEditsAsync(); } Module1.Current.ModuleLogManager.LogError(nameof(UpdateFeatureAttributesAsync), "Exception: " + errorMsg); return(BA_ReturnCode.UnknownError); } }
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 => { RowBuffer rowBuffer = null; Row row = null; try { TableDefinition tableDefinition = enterpriseTable.GetDefinition(); int assetNameIndex = tableDefinition.FindField("ASSETNA"); rowBuffer = enterpriseTable.CreateRowBuffer(); // Either the field index or the field name can be used in the indexer. rowBuffer[assetNameIndex] = "wMain"; rowBuffer["COST"] = 700; rowBuffer["ACTION"] = "Open Cut"; // subtype value for "Abandon". rowBuffer[tableDefinition.GetSubtypeField()] = 3; row = enterpriseTable.CreateRow(rowBuffer); //To Indicate that the attribute table has to be updated context.Invalidate(row); long objectID = row.GetObjectID(); // Do some other processing with the row. } catch (GeodatabaseException exObj) { Console.WriteLine(exObj); } finally { if (rowBuffer != null) { rowBuffer.Dispose(); } if (row != null) { row.Dispose(); } } }, 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(); } }
public async void CreateNewFeatureAsync(object parameter) { string message = String.Empty; bool creationResult = false; //Generate geometry if polygon or polyline, if adding new feature is from using coordinates and not the map tool if (Convert.ToBoolean(parameter) == true) { if (GeometryType == GeometryType.Polyline || GeometryType == GeometryType.Polygon) { GeneratePolyGeometry(); } } IEnumerable<GDBProjectItem> gdbProjectItems = Project.Current.GetItems<GDBProjectItem>(); await QueuedTask.Run(() => { foreach (GDBProjectItem gdbProjectItem in gdbProjectItems) { using (Datastore datastore = gdbProjectItem.GetDatastore()) { //Unsupported datastores (non File GDB and non Enterprise GDB) will be of type UnknownDatastore if (datastore is UnknownDatastore) continue; Geodatabase geodatabase = datastore as Geodatabase; //Find the correct gdb for the one with the complete schema string geodatabasePath = geodatabase.GetPath(); if (geodatabasePath == ProSymbolEditorModule.Current.MilitaryOverlaySchema.DatabaseName) { //Correct GDB, open the current selected feature class FeatureClass featureClass = geodatabase.OpenDataset<FeatureClass>(_currentFeatureClassName); using (featureClass) using (FeatureClassDefinition facilitySiteDefinition = featureClass.GetDefinition()) { EditOperation editOperation = new EditOperation(); editOperation.Name = "Military Symbol Insert"; editOperation.Callback(context => { try { RowBuffer rowBuffer = featureClass.CreateRowBuffer(); _symbolAttributeSet.PopulateRowBufferWithAttributes(ref rowBuffer); rowBuffer["Shape"] = GeometryEngine.Project(MapGeometry, facilitySiteDefinition.GetSpatialReference()); Feature feature = featureClass.CreateRow(rowBuffer); feature.Store(); //To Indicate that the attribute table has to be updated context.Invalidate(feature); } catch (GeodatabaseException geodatabaseException) { message = geodatabaseException.Message; } }, featureClass); var task = editOperation.ExecuteAsync(); creationResult = task.Result; if (!creationResult) { message = editOperation.ErrorMessage; } break; } } } } }); if (!creationResult) { MessageBox.Show(message); } }
private async Task <string> AddFeatureToLayer(Geometry geom, CircleAttributes attributes) { string message = String.Empty; if (attributes == null) { message = "Attributes are Empty"; // For debug does not need to be resource return(message); } FeatureClass circleFeatureClass = await GetFeatureClass(addToMapIfNotPresent : true); if (circleFeatureClass == null) { message = DistanceAndDirectionLibrary.Properties.Resources.ErrorFeatureClassNotFound + this.GetLayerName(); return(message); } bool creationResult = false; FeatureClassDefinition circleDefinition = circleFeatureClass.GetDefinition(); EditOperation editOperation = new EditOperation(); editOperation.Name = "Circular Feature Insert"; editOperation.Callback(context => { try { RowBuffer rowBuffer = circleFeatureClass.CreateRowBuffer(); double distance = attributes.distance; if (IsDistanceCalcExpanded && (CircleType == CircleFromTypes.Diameter)) { distance *= 2.0; } if (circleDefinition.FindField("Distance") >= 0) { rowBuffer["Distance"] = distance; // Double } if (circleDefinition.FindField("DistUnit") >= 0) { rowBuffer["DistUnit"] = attributes.distanceunit; // Text } if (circleDefinition.FindField("DistType") >= 0) { rowBuffer["DistType"] = attributes.circletype; // Text } if (circleDefinition.FindField("CenterX") >= 0) { rowBuffer["CenterX"] = attributes.centerx; // Double } if (circleDefinition.FindField("CenterY") >= 0) { rowBuffer["CenterY"] = attributes.centery; // Double } rowBuffer["Shape"] = GeometryEngine.Instance.Project(geom, circleDefinition.GetSpatialReference()); Feature feature = circleFeatureClass.CreateRow(rowBuffer); feature.Store(); //To Indicate that the attribute table has to be updated context.Invalidate(feature); } catch (GeodatabaseException geodatabaseException) { message = geodatabaseException.Message; } catch (Exception ex) { message = ex.Message; } }, circleFeatureClass); await QueuedTask.Run(async() => { creationResult = await editOperation.ExecuteAsync(); }); if (!creationResult) { message = editOperation.ErrorMessage; await Project.Current.DiscardEditsAsync(); } else { await Project.Current.SaveEditsAsync(); } return(message); }
/// <summary> /// The on comboBox selection change event. /// </summary> /// <param name="item">The newly selected combo box item</param> protected async override void OnSelectionChange(ComboBoxItem item) { if (item == null) { return; } if (string.IsNullOrEmpty(item.Text)) { return; } string error = String.Empty; bool result = false; await QueuedTask.Run(async() => { var layer = MapView.Active.GetSelectedLayers()[0]; if (layer is FeatureLayer) { var featureLayer = layer as FeatureLayer; if (featureLayer.GetTable().GetDatastore() is UnknownDatastore) { return; } using (var table = featureLayer.GetTable()) { var subtypeField = table.GetDefinition().GetSubtypeField(); var code = table.GetDefinition().GetSubtypes().First(subtype => subtype.GetName().Equals(item.Text)).GetCode(); var queryFilter = new QueryFilter { WhereClause = string.Format("{0} = {1}", subtypeField, code) }; try { using (var rowCursor = table.Search(queryFilter, false)) { var editOperation = new EditOperation() { Name = string.Format(@"Deleted where {0}", queryFilter.WhereClause) }; editOperation.Callback(context => { // Note: calling the following method: "await editOperation.ExecuteAsync();" // within the context of the "using (var rowCursor ..." clause // ensures that "rowCursor" in the following while statement is stil // defined and not disposed. So the warning "Access to disposed closure" // doesn't apply here while (rowCursor.MoveNext()) { Thread.Yield(); using (var row = rowCursor.Current) { context.Invalidate(row); row.Delete(); } } }, table); if (table.GetRegistrationType().Equals(RegistrationType.Nonversioned) && Project.Current.HasEdits) { error = "The FeatureClass is Non-Versioned and there are Unsaved Edits in the Project. Please save or discard the edits before attempting Non-Versioned Edits"; } else { result = await editOperation.ExecuteAsync(); } if (!result) { error = editOperation.ErrorMessage; } } } catch (Exception e) { error = e.Message; } } } }); if (!result) { MessageBox.Show(String.Format("Could not delete features for subtype {0} : {1}", item.Text, error)); } }
private async Task <string> AddFeatureToLayer(Geometry geom, EllipseAttributes attributes) { string message = String.Empty; if (attributes == null) { message = "Attributes are Empty"; // For debug does not need to be resource return(message); } FeatureClass ellipseFeatureClass = await GetFeatureClass(addToMapIfNotPresent : true); if (ellipseFeatureClass == null) { message = DistanceAndDirectionLibrary.Properties.Resources.ErrorFeatureClassNotFound + this.GetLayerName(); return(message); } bool creationResult = false; FeatureClassDefinition ellipseDefinition = ellipseFeatureClass.GetDefinition(); EditOperation editOperation = new EditOperation(); editOperation.Name = "Ellipse Feature Insert"; editOperation.Callback(context => { try { RowBuffer rowBuffer = ellipseFeatureClass.CreateRowBuffer(); if (ellipseDefinition.FindField("Major") >= 0) { rowBuffer["Major"] = attributes.majorAxis; // Text } if (ellipseDefinition.FindField("Minor") >= 0) { rowBuffer["Minor"] = attributes.minorAxis; // Double } if (ellipseDefinition.FindField("DistUnit") >= 0) { rowBuffer["DistUnit"] = attributes.distanceunit; // Text } if (ellipseDefinition.FindField("Angle") >= 0) { rowBuffer["Angle"] = attributes.angle; // Double } if (ellipseDefinition.FindField("AngleUnit") >= 0) { rowBuffer["AngleUnit"] = attributes.angleunit; // Text } if (ellipseDefinition.FindField("CenterX") >= 0) { rowBuffer["CenterX"] = attributes.centerx; // Double } if (ellipseDefinition.FindField("CenterY") >= 0) { rowBuffer["CenterY"] = attributes.centery; // Double } rowBuffer["Shape"] = GeometryEngine.Instance.Project(geom, ellipseDefinition.GetSpatialReference()); Feature feature = ellipseFeatureClass.CreateRow(rowBuffer); feature.Store(); //To indicate that the attribute table has to be updated context.Invalidate(feature); } catch (GeodatabaseException geodatabaseException) { message = geodatabaseException.Message; } catch (Exception ex) { message = ex.Message; } }, ellipseFeatureClass); await QueuedTask.Run(async() => { creationResult = await editOperation.ExecuteAsync(); }); if (!creationResult) { message = editOperation.ErrorMessage; } return(message); }
/// <summary> /// This method will /// 1. Make sure if a Feature Layer is selected. /// 2. The Workspace is not null /// 3. Make sure that the workspace is an Enterprise SQL Server Geodatabase Workspace /// /// and then create a new version (In a Queued Task) /// and Connect to the newly created version and delete all the features for the selected subtype (In a separate QueuedTask) /// </summary> /// <param name="item">The newly selected combo box item</param> protected override async void OnSelectionChange(ComboBoxItem item) { if (item == null) { return; } if (string.IsNullOrEmpty(item.Text)) { return; } Layer layer = MapView.Active.GetSelectedLayers()[0]; FeatureLayer featureLayer = null; if (layer is FeatureLayer) { featureLayer = layer as FeatureLayer; Geodatabase geodatabase = null; await QueuedTask.Run(() => geodatabase = (featureLayer.GetTable().GetDatastore() as Geodatabase)); using (geodatabase) { if (geodatabase == null) { return; } } } else { return; } EnterpriseDatabaseType enterpriseDatabaseType = EnterpriseDatabaseType.Unknown; await QueuedTask.Run(() => { using (Table table = (MapView.Active.GetSelectedLayers()[0] as FeatureLayer).GetTable()) { try { enterpriseDatabaseType = (table.GetDatastore() as Geodatabase).GetEnterpriseDatabaseType(); } catch (InvalidOperationException e) { } } }); if (enterpriseDatabaseType != EnterpriseDatabaseType.SQLServer) { Enabled = false; return; } string versionName = String.Empty; await QueuedTask.Run(async() => { using (Table table = featureLayer.GetTable()) { versionName = await CreateVersion(table); } }); if (versionName == null) { return; } await QueuedTask.Run(async() => { using (Table table = featureLayer.GetTable()) { if (table.GetRegistrationType().Equals(RegistrationType.Nonversioned)) { return; } } }); QueuedTask.Run(async() => { using (Table table = featureLayer.GetTable()) { string subtypeField = table.GetDefinition().GetSubtypeField(); int code = table.GetDefinition().GetSubtypes().First(subtype => subtype.GetName().Equals(item.Text)).GetCode(); QueryFilter queryFilter = new QueryFilter { WhereClause = string.Format("{0} = {1}", subtypeField, code) }; try { VersionManager versionManager = (table.GetDatastore() as Geodatabase).GetVersionManager(); Version newVersion = versionManager.GetVersions().First(version => version.GetName().Contains(versionName)); Geodatabase newVersionGeodatabase = newVersion.Connect(); using (Table newVersionTable = newVersionGeodatabase.OpenDataset <Table>(table.GetName())) { using (var rowCursor = newVersionTable.Search(queryFilter, false)) { EditOperation editOperation = new EditOperation { EditOperationType = EditOperationType.Long, Name = "Delete Based On Subtype" }; editOperation.Callback(context => { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { context.Invalidate(row); row.Delete(); } } }, newVersionTable); bool result = await editOperation.ExecuteAsync(); if (!result) { MessageBox.Show(String.Format("Could not delete features for subtype {0} : {1}", item.Text, editOperation.ErrorMessage)); } await Project.Current.SaveEditsAsync(); } } } catch (Exception e) { Console.WriteLine(e); } } }); }
public async Task MainMethodCode() { // 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 (RelationshipClass relationshipClass = geodatabase.OpenDataset <RelationshipClass>("LocalGovernment.GDB.luCodeViolationHasInspections")) using (FeatureClass violationsFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.luCodeViolation")) { List <Row> jeffersonAveViolations = new List <Row>(); QueryFilter queryFilter = new QueryFilter { WhereClause = "LOCDESC LIKE '///%Jefferson///%'" }; // If you need to *cache* the rows retrieved from the cursor for processing later, it is important that you don't use recycling in // the Search() method (i.e., useRecyclingCursor must be set to *false*). Also, the returned rows/features cached in the list // should be disposed when no longer in use so that unmanaged resources are not held on to longer than necessary. using (RowCursor rowCursor = violationsFeatureClass.Search(queryFilter, false)) { while (rowCursor.MoveNext()) { jeffersonAveViolations.Add(rowCursor.Current); } } foreach (Row jeffersoneAveViolation in jeffersonAveViolations) { IReadOnlyList <Row> relatedDestinationRows = relationshipClass.GetRowsRelatedToOriginRows(new List <long> { jeffersoneAveViolation.GetObjectID() }); try { EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { foreach (Row relatedDestinationRow in relatedDestinationRows) { try { relationshipClass.DeleteRelationship(jeffersoneAveViolation, relatedDestinationRow); } catch (GeodatabaseRelationshipClassException exception) { Console.WriteLine(exception); } } }, relationshipClass); bool editResult = editOperation.Execute(); } finally { Dispose(relatedDestinationRows); } } try { // 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(); } finally { Dispose(jeffersonAveViolations); } } }
public static async Task DeleteDxFeatures() { //Get the full list of features in the xpress design string[] commisioned = File.ReadAllLines(Common.GetConfiguration("CommisionedDesign")); //Turn the commissioned design list into a dictionary keyed by layer name Dictionary<string, List<int>> commissionedDesignLayerToOIDS = new Dictionary<string, List<int>>(); string lastLayerName = ""; foreach (string line in commisioned) { int oid = -1; if (int.TryParse(line, out oid) == false) { commissionedDesignLayerToOIDS.Add(line, new List<int>()); lastLayerName = line; } else { commissionedDesignLayerToOIDS[lastLayerName].Add(Convert.ToInt32(line)); } } List<FeatureLayer> layerList = new List<FeatureLayer>(); Map activeMap = MapView.Active.Map; var layers = activeMap.GetLayersAsFlattenedList().OfType<FeatureLayer>().Where( lyr => lyr.ShapeType == (ArcGIS.Core.CIM.esriGeometryType.esriGeometryPoint) || lyr.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolyline); QueuedTask.Run(() => { foreach (FeatureLayer fl in layers) { if (commissionedDesignLayerToOIDS.ContainsKey(fl.Name)) { List<int> oidsToDelete = commissionedDesignLayerToOIDS[fl.Name]; string oidsCommaSep = ""; foreach (int oid in oidsToDelete) { if (oidsCommaSep.Length > 0) { oidsCommaSep += "," + oid; } else { oidsCommaSep = oid.ToString(); } } Table t = fl.GetTable(); var gdb = t.GetWorkspace(); EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { QueryFilter qf = new QueryFilter { WhereClause = "OBJECTID IN (" + oidsCommaSep + ")" }; using (RowCursor rowCursor = t.Search(qf, false)) { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { row.Delete(); context.invalidate(row); } } } }, gdb); bool editResult = editOperation.ExecuteAsync().Result; bool saveResult = EditingModule.SaveEditsAsync().Result; } } }); }
public static async Task <BA_ReturnCode> UpdateReclassFeatureAttributesAsync(Uri uriFeatureClass, string strFeatureClassName, IList <BA_Objects.Interval> lstIntervals) { BA_ReturnCode success = BA_ReturnCode.UnknownError; // Add fields to be updated to feature class, if missing string[] arrReclassFields = { Constants.FIELD_NAME, Constants.FIELD_LBOUND, Constants.FIELD_UBOUND }; string[] arrReclassFieldTypes = { "TEXT", "DOUBLE", "DOUBLE" }; string strFeatureClassPath = uriFeatureClass.LocalPath + "\\" + strFeatureClassName; for (int i = 0; i < arrReclassFields.Length; i++) { if (await AttributeExistsAsync(uriFeatureClass, strFeatureClassName, arrReclassFields[i]) == false) { success = await GeoprocessingTools.AddFieldAsync(strFeatureClassPath, arrReclassFields[i], arrReclassFieldTypes[i]); } } if (success != BA_ReturnCode.Success) { Module1.Current.ModuleLogManager.LogError(nameof(UpdateReclassFeatureAttributesAsync), "Unable to add fields to " + strFeatureClassPath); ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Unable to add fields to " + strFeatureClassPath + "!!", "BAGIS-PRO"); return(success); } // Populate the fields bool modificationResult = false; string errorMsg = ""; await QueuedTask.Run(() => { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(uriFeatureClass))) { if (!String.IsNullOrEmpty(strFeatureClassPath)) { QueryFilter queryFilter = new QueryFilter(); using (Table table = geodatabase.OpenDataset <Table>(strFeatureClassName)) { foreach (var oInterval in lstIntervals) { queryFilter.WhereClause = Constants.FIELD_GRID_CODE + " = " + oInterval.Value; EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { using (RowCursor aCursor = table.Search(queryFilter, false)) { while (aCursor.MoveNext()) { using (Feature feature = (Feature)aCursor.Current) { // name int idxTarget = feature.FindField(arrReclassFields[0]); if (idxTarget > -1) { feature[idxTarget] = oInterval.Name; } // lower bound idxTarget = feature.FindField(arrReclassFields[1]); if (idxTarget > -1) { feature[idxTarget] = oInterval.LowerBound; } // upper bound idxTarget = feature.FindField(arrReclassFields[2]); if (idxTarget > -1) { feature[idxTarget] = oInterval.UpperBound; } feature.Store(); // Has to be called after the store too context.Invalidate(feature); } } } }, table); try { modificationResult = editOperation.Execute(); if (!modificationResult) { errorMsg = editOperation.ErrorMessage; } // increment feature counter } catch (GeodatabaseException exObj) { errorMsg = exObj.Message; } } } } } }); if (String.IsNullOrEmpty(errorMsg)) { await Project.Current.SaveEditsAsync(); } else { if (Project.Current.HasEdits) { await Project.Current.DiscardEditsAsync(); } Module1.Current.ModuleLogManager.LogError(nameof(UpdateReclassFeatureAttributesAsync), "Exception: " + errorMsg); return(BA_ReturnCode.UnknownError); } return(success); }
//Using Inspector... internal async void UpdateTextString() { BasicFeatureLayer annoLayer = MapView.Active.Map.GetLayersAsFlattenedList().First() as BasicFeatureLayer; var oid = 1; #region Update Annotation Text via attribute. Caveat: The TEXTSTRING Anno attribute must exist //See "Change Annotation Text Graphic" for an alternative if TEXTSTRING is missing from the schema await QueuedTask.Run(() => { //annoLayer is ~your~ Annotation layer... // use the inspector methodology var insp = new Inspector(); insp.Load(annoLayer, oid); // make sure TextString attribute exists. //It is not guaranteed to be in the schema ArcGIS.Desktop.Editing.Attributes.Attribute att = insp.FirstOrDefault(a => a.FieldName == "TEXTSTRING"); if (att != null) { insp["TEXTSTRING"] = "Hello World"; //create and execute the edit operation EditOperation op = new EditOperation(); op.Name = "Update annotation"; op.Modify(insp); //OR using a Dictionary - again TEXTSTRING has to exist in the schema //Dictionary<string, object> newAtts = new Dictionary<string, object>(); //newAtts.Add("TEXTSTRING", "hello world"); //op.Modify(annoLayer, oid, newAtts); op.Execute(); } }); #endregion #region Rotate or Move the Annotation await QueuedTask.Run(() => { //Don't use 'Shape'....Shape is the bounding box of the annotation text. This is NOT what you want... // //var insp = new Inspector(); //insp.Load(annoLayer, oid); //var shape = insp["SHAPE"] as Polygon; //...wrong shape... //Instead, we must get the TextGraphic from the anno feature. //The TextGraphic shape will be the anno baseline... //At 2.1 the only way to retrieve this textLine is to obtain the TextGraphic from the AnnotationFeature QueryFilter qf = new QueryFilter() { WhereClause = "OBJECTID = 1" }; //annoLayer is ~your~ Annotation layer using (var rowCursor = annoLayer.Search(qf)) { if (rowCursor.MoveNext()) { using (var annoFeature = rowCursor.Current as ArcGIS.Core.Data.Mapping.AnnotationFeature) { var graphic = annoFeature.GetGraphic(); var textGraphic = graphic as CIMTextGraphic; var textLine = textGraphic.Shape as Polyline; // rotate the shape 90 degrees var origin = GeometryEngine.Instance.Centroid(textLine); Geometry rotatedPolyline = GeometryEngine.Instance.Rotate(textLine, origin, System.Math.PI / 2); //Move the line 5 "units" in the x and y direction //GeometryEngine.Instance.Move(textLine, 5, 5); EditOperation op = new EditOperation(); op.Name = "Change annotation angle"; op.Modify(annoLayer, oid, rotatedPolyline); op.Execute(); } } } }); #endregion #region Change Annotation Text Graphic await QueuedTask.Run(() => { EditOperation op = new EditOperation(); op.Name = "Change annotation graphic"; //At 2.1 we must use an edit operation Callback... op.Callback(context => { QueryFilter qf = new QueryFilter() { WhereClause = "OBJECTID = 1" }; //Cursor must be non-recycling. Use the table ~not~ the layer..i.e. "GetTable().Search()" //annoLayer is ~your~ Annotation layer using (var rowCursor = annoLayer.GetTable().Search(qf, false)) { if (rowCursor.MoveNext()) { using (var annoFeature = rowCursor.Current as ArcGIS.Core.Data.Mapping.AnnotationFeature) { //Get the graphic from the anno feature var graphic = annoFeature.GetGraphic(); var textGraphic = graphic as CIMTextGraphic; // change the text and the color textGraphic.Text = "hello world"; var symbol = textGraphic.Symbol.Symbol; symbol.SetColor(ColorFactory.Instance.RedRGB); textGraphic.Symbol = symbol.MakeSymbolReference(); // update the graphic annoFeature.SetGraphic(textGraphic); // store is required annoFeature.Store(); //refresh layer cache context.Invalidate(annoFeature); } } } }, annoLayer.GetTable()); op.Execute(); }); #endregion }