publicasyncTaskOpenFileGDB(){try{awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{// Opens a file geodatabase. This will open the geodatabase if the folder exists and contains a valid geodatabase.using(Geodatabasegeodatabase=newGeodatabase(newFileGeodatabaseConnectionPath(newUri(@"C:\Data\LocalGovernment.gdb")))){// Use the geodatabase.}});}catch(GeodatabaseNotFoundOrOpenedExceptionexception){// Handle Exception.}}
Opening an Enterprise Geodatabase using connection properties
publicasyncTaskOpenEnterpriseGeodatabase(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{// Opening a Non-Versioned SQL Server instance.DatabaseConnectionPropertiesconnectionProperties=newDatabaseConnectionProperties(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="gdb",Password="password",Version="dbo.DEFAULT"};using(Geodatabasegeodatabase=newGeodatabase(connectionProperties)){// Use the geodatabase}});}
Opening an Enterprise Geodatabase using sde file path
publicasyncTaskOpenEnterpriseGeodatabaseUsingSDEFilePath(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file\\sdefile.sde")))){// Use the geodatabase.}});}
Obtaining Geodatabase from Project Item
publicasyncTaskObtainingGeodatabaseFromProjectItem(){IEnumerable<GDBProjectItem>gdbProjectItems=Project.Current.GetItems<GDBProjectItem>();awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{foreach(GDBProjectItemgdbProjectItemingdbProjectItems){using(Datastoredatastore=gdbProjectItem.GetDatastore()){//Unsupported datastores (non File GDB and non Enterprise GDB) will be of type UnknownDatastoreif(datastoreisUnknownDatastore)continue;Geodatabasegeodatabase=datastoreasGeodatabase;// Use the geodatabase.}}});}
Getting Database Connection Properties from a Connection File
DatabaseConnectionFileconnectionFile=newDatabaseConnectionFile(newUri("path\\to\\sde\\file\\sdefile.sde"));DatabaseConnectionPropertiesconnectionProperties=DatabaseClient.GetDatabaseConnectionProperties(connectionFile);// Now you could, for example, change the user name and password in the connection properties prior to use them to open a geodatabase
// Executes raw SQL on the underlying database management system.// Any SQL is permitted (DDL or DML), but no results can be returnedpublicvoidExecuteSQLOnGeodatabase(Geodatabasegeodatabase,stringstatement){QueuedTask.Run(()=>{DatabaseClient.ExecuteStatement(geodatabase,statement);});}
Definitions
Obtaining Definition from Geodatabase
publicasyncTaskObtainingDefinitionFromGeodatabase(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file\\sdefile.sde")))){// Remember that for Enterprise databases you have to qualify your dataset names with the DatabaseName and UserName.TableDefinitionenterpriseTableDefinition=geodatabase.GetDefinition<TableDefinition>("LocalGovernment.GDB.CitizenContactInfo");// It does not matter if the dataset is within a FeatureDataset or not.FeatureClassDefinitionfeatureClassDefinition=geodatabase.GetDefinition<FeatureClassDefinition>("LocalGovernment.GDB.FireStation");// GetDefinition For a RelationshipClass.RelationshipClassDefinitionrelationshipClassDefinition=geodatabase.GetDefinition<RelationshipClassDefinition>("LocalGovernment.GDB.AddressPointHasSiteAddresses");// GetDefinition For a FeatureDataset.FeatureDatasetDefinitionfeatureDatasetDefinition=geodatabase.GetDefinition<FeatureDatasetDefinition>("LocalGovernment.GDB.Address");}});}
publicasyncTaskObtainingRelatedDefinitionsFromGeodatabase(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file\\sdefile.sde")))){// Remember the qualification of DatabaseName. for the RelationshipClass.RelationshipClassDefinitionenterpriseDefinition=geodatabase.GetDefinition<RelationshipClassDefinition>("LocalGovernment.GDB.AddressPointHasSiteAddresses");IReadOnlyList<Definition>enterpriseDefinitions=geodatabase.GetRelatedDefinitions(enterpriseDefinition,DefinitionRelationshipType.DatasetsRelatedThrough);FeatureClassDefinitionenterpriseAddressPointDefinition=enterpriseDefinitions.First(defn =>defn.GetName().Equals("LocalGovernment.GDB.AddressPoint"))asFeatureClassDefinition;FeatureDatasetDefinitionfeatureDatasetDefinition=geodatabase.GetDefinition<FeatureDatasetDefinition>("LocalGovernment.GDB.Address");IReadOnlyList<Definition>datasetsInAddressDataset=geodatabase.GetRelatedDefinitions(featureDatasetDefinition,DefinitionRelationshipType.DatasetInFeatureDataset);FeatureClassDefinitionaddressPointInAddressDataset=datasetsInAddressDataset.First(defn =>defn.GetName().Equals("LocalGovernment.GDB.AddressPoint"))asFeatureClassDefinition;RelationshipClassDefinitionaddressPointHasSiteAddressInAddressDataset=datasetsInAddressDataset.First(defn =>defn.GetName().Equals("LocalGovernment.GDB.AddressPointHasSiteAddresses"))asRelationshipClassDefinition;}});}
Getting a Table Definition from a Layer
// GetDefinitionFromLayer - This code works even if the layer has a join to another tableprivateTableDefinitionGetDefinitionFromLayer(FeatureLayerfeatureLayer){// Get feature class from the layerFeatureClassfeatureClass=featureLayer.GetFeatureClass();// Determine if feature class is a joinif(featureClass.IsJoinedTable()){// Get join from feature classJoinjoin=featureClass.GetJoin();// Get origin table from joinTableoriginTable=join.GetOriginTable();// Return feature class definition from the join's origin tablereturnoriginTable.GetDefinition();}else{returnfeatureClass.GetDefinition();}}
Datasets
Opening datasets from Geodatabase
publicasyncTaskOpeningDatasetsFromGeodatabase(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file\\sdefile.sde")))){using(Tabletable=geodatabase.OpenDataset<Table>("LocalGovernment.GDB.EmployeeInfo")){}// Open a featureClass (within a feature dataset or outside a feature dataset).using(FeatureClassfeatureClass=geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.AddressPoint")){}// You can open a FeatureClass as a Table which will give you a Table Reference.using(TablefeatureClassAsTable=geodatabase.OpenDataset<Table>("LocalGovernment.GDB.AddressPoint")){// But it is really a FeatureClass object.FeatureClassfeatureClassOpenedAsTable=featureClassAsTableasFeatureClass;}// Open a FeatureDataset.using(FeatureDatasetfeatureDataset=geodatabase.OpenDataset<FeatureDataset>("LocalGovernment.GDB.Address")){}// Open a RelationsipClass. Just as you can open a FeatureClass as a Table, you can also open an AttributedRelationshipClass as a RelationshipClass.using(RelationshipClassrelationshipClass=geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.AddressPointHasSiteAddresses")){}}});}
Checking for the existence of a Table
// Must be called within QueuedTask.Run9)publicboolTableExists(Geodatabasegeodatabase,stringtableName){try{TableDefinitiontableDefinition=geodatabase.GetDefinition<TableDefinition>(tableName);tableDefinition.Dispose();returntrue;}catch{// GetDefinition throws an exception if the definition doesn't existreturnfalse;}}
Checking for the existence of a Feature Class
// Must be called within QueuedTask.Run()publicboolFeatureClassExists(Geodatabasegeodatabase,stringfeatureClassName){try{FeatureClassDefinitionfeatureClassDefinition=geodatabase.GetDefinition<FeatureClassDefinition>(featureClassName);featureClassDefinition.Dispose();returntrue;}catch{// GetDefinition throws an exception if the definition doesn't existreturnfalse;}}
Opening RelationshipClass between two Tables
// Must be called within QueuedTask.Run(). // When used with file or enterprise geodatabases, this routine takes two table names.// When used with feature services, this routine takes layer IDs, or the names of the tables as they are exposed through the service (e.g., "L0States")publicIReadOnlyList<RelationshipClass>OpenRelationshipClassFeatureServices(Geodatabasegeodatabase,stringoriginClass,stringdestinationClass){returngeodatabase.OpenRelationshipClasses(originClass,destinationClass);}
Obtaining related Feature Classes from a Relationship Class
publicasyncTaskGetFeatureClassesInRelationshipClassAsync(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newFileGeodatabaseConnectionPath(newUri(@"C:\Data\LocalGovernment.gdb")))){IReadOnlyList<RelationshipClassDefinition>relationshipClassDefinitions=geodatabase.GetDefinitions<RelationshipClassDefinition>();foreach(RelationshipClassDefinitionrelationshipClassDefinitioninrelationshipClassDefinitions){IReadOnlyList<Definition>definitions=geodatabase.GetRelatedDefinitions(relationshipClassDefinition,DefinitionRelationshipType.DatasetsRelatedThrough);foreach(Definitiondefinitionindefinitions){System.Diagnostics.Debug.WriteLine($"Feature class in the RelationshipClass is:{definition.GetName()}");}}}});}
Opening a FeatureClass from a ShapeFile Datastore
publicasyncTaskOpenShapefileFeatureClass(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{FileSystemConnectionPathfileConnection=newFileSystemConnectionPath(newUri("path\\to\\folder\\containing\\shapefiles"),FileSystemDatastoreType.Shapefile);using(FileSystemDatastoreshapefile=newFileSystemDatastore(fileConnection)){FeatureClasstaxLotsFeatureClass=shapefile.OpenDataset<FeatureClass>("TaxLots");FeatureClassmanHolesFeatureClass=shapefile.OpenDataset<FeatureClass>("ManHoles.shp");// Can use the .shp extension, but its not needed.TabletaxDetailsTableWithoutExtension=shapefile.OpenDataset<Table>("TaxDetails");TabletaxDetailsTable=shapefile.OpenDataset<Table>("TaxDetails.dbf");}});}
Opening a CAD Datastore
publicasyncTaskOpenCADFeatureClass(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{FileSystemConnectionPathfileConnection=newFileSystemConnectionPath(newUri("path\\to\\folder\\containing\\CAD"),FileSystemDatastoreType.Cad);using(FileSystemDatastorecadDatastore=newFileSystemDatastore(fileConnection)){// note - extension is requiredFeatureClasscadDataset=cadDatastore.OpenDataset<FeatureClass>("hatchplayboundaries.dwg");// take note of the pattern for referencing a feature class. FeatureClasscadfeatureClass=cadDatastore.OpenDataset<FeatureClass>("hatchplayboundaries.dwg:Polyline");intnumRows=0;using(RowCursorcursor=cadfeatureClass.Search()){while(cursor.MoveNext())numRows++;}}});}
Queries
Searching a Table using QueryFilter
publicasyncTaskSearchingATable(){try{awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file\\sdefile.sde"))))using(Tabletable=geodatabase.OpenDataset<Table>("EmployeeInfo")){QueryFilterqueryFilter=newQueryFilter{WhereClause="COSTCTRN = 'Information Technology'",SubFields="KNOWNAS, OFFICE, LOCATION",PostfixClause="ORDER BY OFFICE"};using(RowCursorrowCursor=table.Search(queryFilter,false)){while(rowCursor.MoveNext()){using(Rowrow=rowCursor.Current){stringlocation=Convert.ToString(row["LOCATION"]);stringknownAs=Convert.ToString(row["KNOWNAS"]);}}}}});}catch(GeodatabaseFieldExceptionfieldException){// One of the fields in the where clause might not exist. There are multiple ways this can be handled:// Handle error appropriately}catch(Exceptionexception){// logger.Error(exception.Message);}}
Searching a Table for non-Latin characters
using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file\\sdefile.sde"))))using(Tabletable=geodatabase.OpenDataset<Table>("TableWithChineseCharacters")){// This will fail with many database systems that expect Latin characters by defaultstringincorrectWhereClause="颜色 = '绿'";// Correct solution is to prepend the 'National String Prefix' to the attribute value// For example, with SQL Server this value is 'N'// This value is obtained using the SQLSyntax classstringnationalStringPrefix="";SQLSyntaxsqlSyntax=geodatabase.GetSQLSyntax();nationalStringPrefix=sqlSyntax.GetSupportedStrings(SQLStringType.NationalStringPrefix).First();// This Where clause will workQueryFilterqueryFilter=newQueryFilter(){WhereClause="颜色 = "+nationalStringPrefix+"'绿'"};}
publicasyncTaskSearchingAFeatureClass(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file\\sdefile.sde"))))using(FeatureClassschoolBoundaryFeatureClass=geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.SchoolBoundary")){// Using a spatial query filter to find all features which have a certain district name and lying within a given Polygon.SpatialQueryFilterspatialQueryFilter=newSpatialQueryFilter{WhereClause="DISTRCTNAME = 'Indian Prairie School District 204'",FilterGeometry=newPolygonBuilderEx(newList<Coordinate2D>{newCoordinate2D(1021880,1867396),newCoordinate2D(1028223,1870705),newCoordinate2D(1031165,1866844),newCoordinate2D(1025373,1860501),newCoordinate2D(1021788,1863810)}).ToGeometry(),SpatialRelationship=SpatialRelationship.Within};using(RowCursorindianPrairieCursor=schoolBoundaryFeatureClass.Search(spatialQueryFilter,false)){while(indianPrairieCursor.MoveNext()){using(Featurefeature=(Feature)indianPrairieCursor.Current){// Process the feature. For example...Console.WriteLine(feature.GetObjectID());}}}}});}
Selecting Rows from a Table
publicasyncTaskSelectingRowsFromATable(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file\\sdefile.sde"))))using(TableenterpriseTable=geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost")){QueryFilteranotherQueryFilter=newQueryFilter{WhereClause="FLOOR = 1 AND WING = 'E'"};// For Selecting all matching entries.using(SelectionanotherSelection=enterpriseTable.Select(anotherQueryFilter,SelectionType.ObjectID,SelectionOption.Normal)){}// This can be used to get one record which matches the criteria. No assumptions can be made about which record satisfying the criteria is selected.using(SelectiononlyOneSelection=enterpriseTable.Select(anotherQueryFilter,SelectionType.ObjectID,SelectionOption.OnlyOne)){}// This can be used to obtain a empty selction which can be used as a container to combine results from different selections.using(SelectionemptySelection=enterpriseTable.Select(anotherQueryFilter,SelectionType.ObjectID,SelectionOption.Empty)){}// If you want to select all the records in a table.using(SelectionallRecordSelection=enterpriseTable.Select(null,SelectionType.ObjectID,SelectionOption.Normal)){}}});}
Selecting Features from a FeatureClass
publicasyncTaskSelectingFeaturesFromAFeatureClass(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file\\sdefile.sde"))))using(FeatureClassenterpriseFeatureClass=geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite")){List<Coordinate2D>newCoordinates=newList<Coordinate2D>{newCoordinate2D(1021570,1880583),newCoordinate2D(1028730,1880994),newCoordinate2D(1029718,1875644),newCoordinate2D(1021405,1875397)};SpatialQueryFilterspatialFilter=newSpatialQueryFilter{WhereClause="FCODE = 'Park'",FilterGeometry=newPolygonBuilderEx(newCoordinates).ToGeometry(),SpatialRelationship=SpatialRelationship.Crosses};// For Selecting all matching entries.using(SelectionanotherSelection=enterpriseFeatureClass.Select(spatialFilter,SelectionType.ObjectID,SelectionOption.Normal)){}// This can be used to get one record which matches the criteria. No assumptions can be made about which record satisfying the // criteria is selected.using(SelectiononlyOneSelection=enterpriseFeatureClass.Select(spatialFilter,SelectionType.ObjectID,SelectionOption.OnlyOne)){}// This can be used to obtain a empty selction which can be used as a container to combine results from different selections.using(SelectionemptySelection=enterpriseFeatureClass.Select(spatialFilter,SelectionType.ObjectID,SelectionOption.Empty)){}// If you want to select all the records in a table.using(SelectionallRecordSelection=enterpriseFeatureClass.Select(null,SelectionType.ObjectID,SelectionOption.Normal)){}}});}
Gets the count of how many rows are currently in a Table
//Note: call within QueuedTask.Run()Tabletable=featureLayer.GetTable();longcount=table.GetCount();
publicRowCursorSortWorldCities(FeatureClassworldCitiesTable){using(FeatureClassDefinitionfeatureClassDefinition=worldCitiesTable.GetDefinition()){FieldcountryField=featureClassDefinition.GetFields().First(x =>x.Name.Equals("COUNTRY_NAME"));FieldcityNameField=featureClassDefinition.GetFields().First(x =>x.Name.Equals("CITY_NAME"));// Create SortDescription for Country fieldSortDescriptioncountrySortDescription=newSortDescription(countryField);countrySortDescription.CaseSensitivity=CaseSensitivity.Insensitive;countrySortDescription.SortOrder=SortOrder.Ascending;// Create SortDescription for City fieldSortDescriptioncitySortDescription=newSortDescription(cityNameField);citySortDescription.CaseSensitivity=CaseSensitivity.Insensitive;citySortDescription.SortOrder=SortOrder.Ascending;// Create our TableSortDescriptionTableSortDescriptiontableSortDescription=newTableSortDescription(newList<SortDescription>(){countrySortDescription,citySortDescription});returnworldCitiesTable.Sort(tableSortDescription);}}
Calculating Statistics on a Table
// Calculate the Sum and Average of the Population_1990 and Population_2000 fields, grouped and ordered by RegionpublicvoidCalculateStatistics(FeatureClasscountryFeatureClass){using(FeatureClassDefinitionfeatureClassDefinition=countryFeatureClass.GetDefinition()){// Get fieldsFieldregionField=featureClassDefinition.GetFields().First(x =>x.Name.Equals("Region"));Fieldpop1990Field=featureClassDefinition.GetFields().First(x =>x.Name.Equals("Population_1990"));Fieldpop2000Field=featureClassDefinition.GetFields().First(x =>x.Name.Equals("Population_2000"));// Create StatisticsDescriptionsStatisticsDescriptionpop1990StatisticsDescription=newStatisticsDescription(pop1990Field,newList<StatisticsFunction>(){StatisticsFunction.Sum,StatisticsFunction.Average});StatisticsDescriptionpop2000StatisticsDescription=newStatisticsDescription(pop2000Field,newList<StatisticsFunction>(){StatisticsFunction.Sum,StatisticsFunction.Average});// Create TableStatisticsDescriptionTableStatisticsDescriptiontableStatisticsDescription=newTableStatisticsDescription(newList<StatisticsDescription>(){pop1990StatisticsDescription,pop2000StatisticsDescription});tableStatisticsDescription.GroupBy=newList<Field>(){regionField};tableStatisticsDescription.OrderBy=newList<SortDescription>(){newSortDescription(regionField)};// Calculate StatisticsIReadOnlyList<TableStatisticsResult>tableStatisticsResults=countryFeatureClass.CalculateStatistics(tableStatisticsDescription);foreach(TableStatisticsResulttableStatisticsResultintableStatisticsResults){// Get the Region name// If multiple fields had been passed into TableStatisticsDescription.GroupBy, there would be multiple values in TableStatisticsResult.GroupBystringregionName=tableStatisticsResult.GroupBy.First().Value.ToString();// Get the statistics results for the Population_1990 fieldStatisticsResultpop1990Statistics=tableStatisticsResult.StatisticsResults[0];doublepopulation1990Sum=pop1990Statistics.Sum;doublepopulation1990Average=pop1990Statistics.Average;// Get the statistics results for the Population_2000 fieldStatisticsResultpop2000Statistics=tableStatisticsResult.StatisticsResults[1];doublepopulation2000Sum=pop2000Statistics.Sum;doublepopulation2000Average=pop2000Statistics.Average;// Do something with the results here...}}}
Evaluating a QueryDef on a single table
publicasyncTaskSimpleQueryDef(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file")))){QueryDefadaCompilantParksQueryDef=newQueryDef{Tables="Park",WhereClause="ADACOMPLY = 'Yes'",};using(RowCursorrowCursor=geodatabase.Evaluate(adaCompilantParksQueryDef,false)){while(rowCursor.MoveNext()){using(Rowrow=rowCursor.Current){Featurefeature=rowasFeature;Geometryshape=feature.GetShape();Stringtype=Convert.ToString(row["ADACOMPLY"]);// will be "Yes" for each row.try{Tabletable=row.GetTable();// Will always throw exception.}catch(NotSupportedExceptionexception){// Handle not supported exception.}}}}}});}
Evaluating a QueryDef on a Join using WHERE Clause
publicasyncTaskJoiningWithWhereQueryDef(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file")))){QueryDefmunicipalEmergencyFacilitiesQueryDef=newQueryDef{SubFields="EmergencyFacility.OBJECTID, EmergencyFacility.Shape, EmergencyFacility.FACILITYID, FacilitySite.FACILITYID, FacilitySite.FCODE",Tables="EmergencyFacility, FacilitySite",WhereClause="EmergencyFacility.FACNAME = FacilitySite.NAME AND EmergencyFacility.JURISDICT = 'Municipal'",};using(RowCursorrowCursor=geodatabase.Evaluate(municipalEmergencyFacilitiesQueryDef,false)){while(rowCursor.MoveNext()){using(Rowrow=rowCursor.Current){Featurefeature=rowasFeature;Geometryshape=feature.GetShape();longobjectID=Convert.ToInt64(row["EmergencyFacility.OBJECTID"]);StringfeatureCode=Convert.ToString(row["FacilitySite.FCODE"]);IReadOnlyList<Field>fields=feature.GetFields();//Contains one ArcGIS.Core.Data.Field objects for every subfield}}}}});}
Evaluating a QueryDef on a OUTER JOIN
publicasyncTaskEvaluatingQueryDefWithOuterJoin(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file")))){QueryDefqueryDefWithLeftOuterJoin=newQueryDef{Tables="CommunityAddress LEFT OUTER JOIN MunicipalBoundary on CommunityAddress.Municipality = MunicipalBoundary.Name",SubFields="CommunityAddress.OBJECTID, CommunityAddress.Shape, CommunityAddress.SITEADDID, CommunityAddress.ADDRNUM, CommunityAddress.FULLNAME, CommunityAddress.FULLADDR, CommunityAddress.MUNICIPALITY, MunicipalBoundary.Name, MunicipalBoundary.MUNITYP, MunicipalBoundary.LOCALFIPS",};using(RowCursorrowCursor=geodatabase.Evaluate(queryDefWithLeftOuterJoin,false)){while(rowCursor.MoveNext()){using(Rowrow=rowCursor.Current){Featurefeature=rowasFeature;Geometryshape=feature.GetShape();intsiteAddressId=Convert.ToInt32(row["CommunityAddress.SITEADDID"]);StringstateName=Convert.ToString(row["MunicipalBoundary.name"]);}}}}});}
Evaluating a QueryDef on a INNER join
publicasyncTaskEvaluatingQueryDefWithInnerJoin(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file")))){QueryDefqueryDef=newQueryDef(){Tables="People INNER JOIN States ON People.FK_STATE_ID = States.OBJECTID",SubFields="People.OBJECTID, People.First_Name, People.Last_Name, People.City, States.State_Name"};using(RowCursorcursor=geodatabase.Evaluate(queryDef)){while(cursor.MoveNext()){using(Rowrow=cursor.Current){// Handle row}}}}});}
Evaluating a QueryDef on a nested - INNER and OUTER join
publicasyncTaskEvaluatingQueryDefWithNestedJoin(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file")))){QueryDefqueryDef=newQueryDef(){Tables="((People INNER JOIN States ON People.FK_STATE_ID = States.OBJECTID) LEFT OUTER JOIN Homes ON People.OBJECTID = Homes.FK_People_ID)",SubFields="People.OBJECTID, People.First_Name, People.Last_Name, States.State_Name, Homes.Address"};using(RowCursorcursor=geodatabase.Evaluate(queryDef,false)){while(cursor.MoveNext()){using(Rowrow=cursor.Current){// Handle row}}}}});}
Create Default QueryDescription for a Database table and obtain the ArcGIS.Core.Data.Table for the QueryDescription
Create QueryDescription from a custom query for a Database table
publicasyncTaskCustomQueryDescription(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{DatabaseConnectionPropertiesdatabaseConnectionProperties=newDatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer){AuthenticationMode=AuthenticationMode.DBMS,Instance="instance",Database="database",User="user",Password="password"};using(Databasedatabase=newDatabase(databaseConnectionProperties)){QueryDescriptionqueryDescription=database.GetQueryDescription("SELECT OBJECTID, Shape, FACILITYID FROM EmergencyFacility WHERE JURISDICT = 'Municipal'","MunicipalEmergencyFacilities");using(Tabletable=database.OpenTable(queryDescription)){// Use the table.}}});}
Create QueryDescription from a join query where there is no non-nullable unique id column
publicasyncTaskJoinQueryDescription(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{DatabaseConnectionPropertiesdatabaseConnectionProperties=newDatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer){AuthenticationMode=AuthenticationMode.DBMS,Instance="instance",Database="database",User="user",Password="password"};using(Databasedatabase=newDatabase(databaseConnectionProperties)){QueryDescriptionqueryDescription=database.GetQueryDescription("SELECT BUSLINES.ID as BUSLINESID, BUSSTOPS.ID as BUSSTOPSID, BUSLINES.RTE_DESC, BUSLINES.DIR, BUSSTOPS.JURISDIC, BUSSTOPS.LOCATION, BUSSTOPS.ROUTE,BUSSTOPS.SHAPE from demosql.dbo.BUSSTOPS JOIN demosql.dbo.BUSLINES ON BUSSTOPS.ROUTE = BUSLINES.ROUTE","BusInfo");queryDescription.SetObjectIDFields("BUSLINESID,BUSSTOPSID");using(Tabletable=database.OpenTable(queryDescription)){// Use the table.}}});}
Create QueryDescription from a query for a Database table which has more than one shape type
publicasyncTaskMultiGeometryQueryDescription(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{DatabaseConnectionPropertiesdatabaseConnectionProperties=newDatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer){AuthenticationMode=AuthenticationMode.DBMS,Instance="instance",Database="database",User="user",Password="password"};using(Databasedatabase=newDatabase(databaseConnectionProperties)){QueryDescriptionpointQueryDescription=database.GetQueryDescription("select Description, SHAPE, UniqueID from MULTIGEOMETRYTEST","MultiGeometryPoint");pointQueryDescription.SetShapeType(GeometryType.Point);using(TablepointTable=database.OpenTable(pointQueryDescription)){//use pointTable}QueryDescriptionpolygonQueryDescription=database.GetQueryDescription("select Description, SHAPE, UniqueID from MULTIGEOMETRYTEST","MultiGeometryPolygon");polygonQueryDescription.SetShapeType(GeometryType.Polygon);using(TablepolygonTable=database.OpenTable(polygonQueryDescription)){//use polygonTable}}});}
Create QueryDescription from a query for an SQLite Database table
publicasyncTaskSqliteQueryDescription(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Databasedatabase=newDatabase(newSQLiteConnectionPath(newUri("Path\\To\\Sqlite\\Database\\USA.sqlite")))){QueryDescriptionwashingtonCitiesQueryDescription=database.GetQueryDescription("select OBJECTID, Shape, CITY_FIPS, CITY_NAME, STATE_FIPS, STATE_CITY, TYPE, CAPITAL from main.cities where STATE_NAME='Washington'","WashingtonCities");using(TablewashingtonTable=database.OpenTable(washingtonCitiesQueryDescription)){// Use washingtonTable.}}});}
Using SQLSyntax to form platform agnostic queries
publicasyncTaskUsingSqlSyntaxToFormPlatformAgnosticQueries(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newFileGeodatabaseConnectionPath(newUri("C:\\Data\\LocalGovernment.gdb"))))using(FeatureClassfeatureClass=geodatabase.OpenDataset<FeatureClass>("FacilitySite")){SQLSyntaxsqlSyntax=geodatabase.GetSQLSyntax();stringsubstringFunctionName=sqlSyntax.GetFunctionName(SQLFunction.Substring);stringupperFunctionName=sqlSyntax.GetFunctionName(SQLFunction.Upper);stringsubstringfunction=string.Format("{0}({1}(FCODE, 1, 6)) = 'SCHOOL'",upperFunctionName,substringFunctionName);QueryFilterqueryFilter=newQueryFilter{WhereClause=substringfunction};using(Selectionselection=featureClass.Select(queryFilter,SelectionType.ObjectID,SelectionOption.Normal)){// work with the selection.}}});}
Joining a file geodatabase feature class to an Oracle database query layer feature class with a virtual relationship class
publicasyncTaskJoiningFileGeodatabaseFeatureClassToOracleQueryLayer(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newFileGeodatabaseConnectionPath(newUri("C:\\Data\\LocalGovernment.gdb"))))using(Databasedatabase=newDatabase(newDatabaseConnectionProperties(EnterpriseDatabaseType.Oracle){AuthenticationMode=AuthenticationMode.DBMS,Instance="instance",User="user",Password="password",Database="database"}))using(FeatureClassleftFeatureClass=geodatabase.OpenDataset<FeatureClass>("Hospital"))using(TablerightTable=database.OpenTable(database.GetQueryDescription("FacilitySite"))){FieldoriginPrimaryKey=leftFeatureClass.GetDefinition().GetFields().FirstOrDefault(field =>field.Name.Equals("facilityId"));FielddestinationForeignKey=rightTable.GetDefinition().GetFields().FirstOrDefault(field =>field.Name.Equals("hospitalID"));VirtualRelationshipClassDescriptiondescription=newVirtualRelationshipClassDescription(originPrimaryKey,destinationForeignKey,RelationshipCardinality.OneToOne);using(RelationshipClassrelationshipClass=leftFeatureClass.RelateTo(rightTable,description)){JoinDescriptionjoinDescription=newJoinDescription(relationshipClass){JoinDirection=JoinDirection.Forward,JoinType=JoinType.LeftOuterJoin};Joinjoin=newJoin(joinDescription);using(TablejoinedTable=join.GetJoinedTable()){// Perform operation on joined table.}}}});}
Joining two tables from different geodatabases
publicasyncTaskJoinTablesFromDifferentGeodatabases(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(GeodatabasesourceGeodatabase=newGeodatabase(newFileGeodatabaseConnectionPath(newUri("Path \\ to \\Geodatabase \\ one"))))using(GeodatabasedestinationGeodatabase=newGeodatabase(newFileGeodatabaseConnectionPath(newUri("Path \\ to \\Geodatabase \\ two"))))using(TablesourceTable=sourceGeodatabase.OpenDataset<Table>("State"))using(TabledestinationTable=destinationGeodatabase.OpenDataset<Table>("Cities")){FieldprimaryKeyField=sourceTable.GetDefinition().GetFields().FirstOrDefault(field =>field.Name.Equals("State.State_Abbreviation"));FieldforeignKeyField=destinationTable.GetDefinition().GetFields().FirstOrDefault(field =>field.Name.Equals("Cities.State"));VirtualRelationshipClassDescriptionvirtualRelationshipClassDescription=newVirtualRelationshipClassDescription(primaryKeyField,foreignKeyField,RelationshipCardinality.OneToMany);using(RelationshipClassrelationshipClass=sourceTable.RelateTo(destinationTable,virtualRelationshipClassDescription)){JoinDescriptionjoinDescription=newJoinDescription(relationshipClass){JoinDirection=JoinDirection.Forward,JoinType=JoinType.InnerJoin,TargetFields=sourceTable.GetDefinition().GetFields()};using(Joinjoin=newJoin(joinDescription)){TablejoinedTable=join.GetJoinedTable();//Process the joined table. For example ..using(RowCursorcursor=joinedTable.Search()){while(cursor.MoveNext()){using(Rowrow=cursor.Current){// Use Row}}}}}}});}
Creating a QueryTable using a query which joins two versioned tables in a geodatabase
publicasyncTaskQueryTableJoinWithVersionedData(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{QueryDefqueryDef=newQueryDef{Tables="CommunityAddress JOIN MunicipalBoundary on CommunityAddress.Municipality = MunicipalBoundary.Name",SubFields="CommunityAddress.OBJECTID, CommunityAddress.Shape, CommunityAddress.SITEADDID, CommunityAddress.ADDRNUM, CommunityAddress.FULLNAME, CommunityAddress.FULLADDR, CommunityAddress.MUNICIPALITY, MunicipalBoundary.Name, MunicipalBoundary.MUNITYP, MunicipalBoundary.LOCALFIPS",};using(GeodatabasetestVersion1Geodatabase=newGeodatabase(newDatabaseConnectionProperties(EnterpriseDatabaseType.Oracle){AuthenticationMode=AuthenticationMode.DBMS,Instance="instance",User="user",Password="password",Database="database",Version="user.testVersion1"})){QueryTableDescriptionqueryTableDescription=newQueryTableDescription(queryDef){Name="CommunityAddrJounMunicipalBoundr",PrimaryKeys=testVersion1Geodatabase.GetSQLSyntax().QualifyColumnName("CommunityAddress","OBJECTID")};// Will be based on testVersion1.using(TablequeryTable=testVersion1Geodatabase.OpenQueryTable(queryTableDescription)){// Use queryTable.}}using(GeodatabasetestVersion2Geodatabase=newGeodatabase(newDatabaseConnectionProperties(EnterpriseDatabaseType.Oracle){AuthenticationMode=AuthenticationMode.DBMS,Instance="instance",User="user",Password="password",Database="database",Version="user.testVersion2"})){QueryTableDescriptionqueryTableDescription=newQueryTableDescription(queryDef){Name="CommunityAddrJounMunicipalBoundr",PrimaryKeys=testVersion2Geodatabase.GetSQLSyntax().QualifyColumnName("CommunityAddress","OBJECTID")};// Will be based on testVersion2.using(TablequeryTable=testVersion2Geodatabase.OpenQueryTable(queryTableDescription)){// Use queryTable.}}});}
Checking a field value for null
objectval=row[field.Name];if(valisDBNull||val==null){// field value is null}else{// field value is not null}
Get domain string from a field
publicstringGetDomainStringFromField(Rowrow,Fieldfield){// Get the table and table definition from the Rowusing(Tabletable=row.GetTable())using(TableDefinitiontableDefinition=table.GetDefinition()){// Get name of subtype fieldstringsubtypeFieldName=tableDefinition.GetSubtypeField();// Get subtype, if anySubtypesubtype=null;if(subtypeFieldName.Length!=0){// Get value of subtype field for this rowobjectvarSubtypeCode=row[subtypeFieldName];longsubtypeCode=(long)varSubtypeCode;// Get subtype for this rowsubtype=tableDefinition.GetSubtypes().First(x =>x.GetCode()==subtypeCode);}// Get the coded value domain for this fieldCodedValueDomaindomain=field.GetDomain(subtype)asCodedValueDomain;// Return the text string for this fieldif(domain!=null){returndomain.GetName(row[field.Name]);}else{returnrow[field.Name].ToString();}}}
Get datastore or workspace properties
publicvoidGetDatastoreProperties(Datastoregeodatabase){// Check if a data store supports datastore propertiesboolareDatastorePropertiesSupported=geodatabase.AreDatastorePropertiesSupported();if(areDatastorePropertiesSupported){DatastorePropertiesdatastoreProperties=geodatabase.GetDatastoreProperties();// Supports 64-bit integer fieldboolsupportsBigInteger=datastoreProperties.SupportsBigInteger;// Supports paginationboolsupportsQueryPagination=datastoreProperties.SupportsQueryPagination;// Supports datastore edit boolcanEdit=datastoreProperties.CanEdit;// Supports 64-bit Object IDboolsupportsBigObjectId=datastoreProperties.SupportsBigObjectID;// Supports DateOnly fieldboolsupportsDateOnly=datastoreProperties.SupportsDateOnly;// Supports TimeOnly fieldboolsupportsTimeOnly=datastoreProperties.SupportsTimeOnly;// Supports TimestampOffset fieldboolsupportsTimestampOffset=datastoreProperties.SupportsTimestampOffset;}}
Pagination in QueryFilter
publicvoidQueryFilterWithPagination(Tabletable,List<long>objectIDs){introwsPerBatch=100;intoffset=0;// Query filter// Some datastores support pagination only through an SQL postfix clauseQueryFilterqueryFilter=newQueryFilter(){ObjectIDs=objectIDs,PostfixClause="ORDER BY OBJECTID"};// Fetch rows in a batch from a tablefor(intindex=offset;index<=objectIDs.Count;index+=rowsPerBatch){// Set number of rows to return from a tablequeryFilter.RowCount=rowsPerBatch;// Set positional offset to skip number of rows from a table queryFilter.Offset=index;using(RowCursorcursor=table.Search(queryFilter)){while(cursor.MoveNext()){using(Rowrow=cursor.Current){Console.WriteLine(row.GetObjectID());}}}}}
Illustrate version conflict information from a reconcile operation
publicvoidGetVersionConflictsInfoInUpdateDeleteType(ServiceConnectionPropertiesfeatureServiceConnectionProperties,stringfeatureClassName){// To illustrate the conflict between versions,// the feature is updated in the child version and deleted in the parent version.longfeatureObjectIDForEdit=Int64.MinValue;// Get branch versioned serviceusing(GeodatabasefsGeodatabase=newGeodatabase(featureServiceConnectionProperties))using(VersionManagerversionManager=fsGeodatabase.GetVersionManager())using(VersiondefaultVersion=versionManager.GetDefaultVersion())using(GeodatabasedefaultGeodatabase=defaultVersion.Connect())using(FeatureClassdefaultFeatureClass=defaultGeodatabase.OpenDataset<FeatureClass>(featureClassName))using(FeatureClassDefinitiondefaultFeatureClassDefinition=defaultFeatureClass.GetDefinition()){// Create a feature in the default version to edit in a branchdefaultGeodatabase.ApplyEdits(()=>{using(RowBufferrowBuffer=defaultFeatureClass.CreateRowBuffer()){rowBuffer["NAME"]="Loblolly Pine";rowBuffer["TREEAGE"]=1;rowBuffer[defaultFeatureClassDefinition.GetShapeField()]=newMapPointBuilderEx(newCoordinate2D(1,1),SpatialReferenceBuilder.CreateSpatialReference(4152,0)).ToGeometry();using(Featurefeature=defaultFeatureClass.CreateRow(rowBuffer)){featureObjectIDForEdit=feature.GetObjectID();}}});// Add newly created feature in the filterQueryFilterqueryFilter=newQueryFilter{ObjectIDs=newList<long>{featureObjectIDForEdit}};// Create a branch versionVersionDescriptionversionDescription=newVersionDescription("UpdateDeleteConflictType","Update-Delete version conflict type",VersionAccessType.Private);// Edit the feature in the branch using(VersioneditVersion=versionManager.CreateVersion(versionDescription))using(GeodatabasebranchGeodatabase=editVersion.Connect())using(FeatureClassfeatureClass=branchGeodatabase.OpenDataset<FeatureClass>(featureClassName))using(RowCursorrowCursor=featureClass.Search(queryFilter,false)){branchGeodatabase.ApplyEdits(()=>{while(rowCursor.MoveNext()){using(Rowrow=rowCursor.Current){row["TREEAGE"]=100;row["NAME"]=$"{row["Name"]}_EditInBranch";row.Store();}}});// Delete the feature from the default versiondefaultFeatureClass.DeleteRows(queryFilter);// Reconcile optionsReconcileOptionsreconcileOptions=newReconcileOptions(defaultVersion){ConflictResolutionType=ConflictResolutionType.FavorEditVersion,ConflictDetectionType=ConflictDetectionType.ByRow,ConflictResolutionMethod=ConflictResolutionMethod.Continue};// Reconcile with defaultReconcileResultreconcileResult=editVersion.Reconcile(reconcileOptions);// Check for conflictsboolhasConflictsReconcileResults=reconcileResult.HasConflicts;boolhasConflictsAfterReconcile=editVersion.HasConflicts();// Fetch conflictsIReadOnlyList<Conflict>conflictsAfterReconcile=editVersion.GetConflicts();// Iterate conflictsforeach(ConflictconflictinconflictsAfterReconcile){// Object ID of row where conflict occurslongobjectId=conflict.ObjectID;ConflictTypeconflictType=conflict.ConflictType;IReadOnlyList<FieldValue>ancestorVersionValues=conflict.AncestorVersionValues;objectnameAncestor=ancestorVersionValues.FirstOrDefault(f =>f.FieldName.Contains("NAME")).Value;objecttreeAgeAncestor=ancestorVersionValues.FirstOrDefault(f =>f.FieldName.Contains("TREEAGE")).Value;IReadOnlyList<FieldValue>childVersionValues=conflict.ChildVersionValues;objectnameChild=childVersionValues.FirstOrDefault(f =>f.FieldName.Contains("NAME")).Value;objecttreeAgeChild=childVersionValues.FirstOrDefault(f =>f.FieldName.Contains("TREEAGE")).Value;IReadOnlyList<FieldValue>parentVersionValues=conflict.ParentVersionValues;IReadOnlyList<Field>originalFields=defaultFeatureClassDefinition.GetFields();stringdatasetName=conflict.DatasetName;}}}}
Explore cotingent attribute values
publicvoidExploreContingentValues(Tabletable){using(TableDefinitiontableDefinition=table.GetDefinition()){IReadOnlyList<Contingency>contingencies=tableDefinition.GetContingencies();foreach(Contingencycontingencyincontingencies){// Field group FieldGroupfiledGroup=contingency.FieldGroup;stringfieldGroupName=filedGroup.Name;IReadOnlyList<string>fieldInFieldGroup=filedGroup.FieldNames;boolisEditRestriction=filedGroup.IsRestrictive;intcontingencyId=contingency.ID;Subtypesubtype=contingency.Subtype;boolisContingencyRetired=contingency.IsRetired;// Contingent values IReadOnlyDictionary<string,ContingentValue>contingentValuesByFieldName=contingency.GetContingentValues();foreach(KeyValuePair<string,ContingentValue>contingentValueKeyValuePairincontingentValuesByFieldName){stringattributeFieldName=contingentValueKeyValuePair.Key;// Contingent value type associated with the attribute fieldContingentValuecontingentValue=contingentValueKeyValuePair.Value;switch(contingentValue){caseContingentCodedValuecontingentCodedValue:stringcodedValueDomainName=contingentCodedValue.Name;objectcodedValueDomainValue=contingentCodedValue.CodedValue;break;caseContingentRangeValuecontingentRangeValue:objectrangeDomainMaxValue=contingentRangeValue.Max;objectrangeDomainMinValue=contingentRangeValue.Min;break;caseContingentAnyValuecontingentAnyValue:// Any value typebreak;caseContingentNullValuecontingentNullValue:// Null valuebreak;}}}}}
Validate contingent attribute values
publicvoidValidateContingentValues(FeatureClassparcels,stringzoningFieldName="Zone",stringtaxCodeFieldName="TaxCode"){using(RowBufferrowBuffer=parcels.CreateRowBuffer()){// Insert values in a row bufferrowBuffer[zoningFieldName]="Business";rowBuffer[taxCodeFieldName]="TaxB";// Validate contingency values of the parcels' row ContingencyValidationResultcontingencyValidationResult=parcels.ValidateContingencies(rowBuffer);// Valid contingenciesIReadOnlyList<Contingency>matchedContingencies=contingencyValidationResult.Matches;if(matchedContingencies.Count>0){// Create a row with valid contingency valuesparcels.CreateRow(rowBuffer);}// Invalid contingenciesIReadOnlyList<ContingencyViolation>violatedContingencies=contingencyValidationResult.Violations;foreach(ContingencyViolationcontingencyViolationinviolatedContingencies){ContingencyViolationTypeviolationType=contingencyViolation.Type;ContingencyviolatedContingency=contingencyViolation.Contingency;}}}
Get possible contingent values
publicvoidGetPossibleContingentValues(FeatureClassparcels,stringzoningFieldName="Zone"){using(RowBufferrowBuffer=parcels.CreateRowBuffer()){IReadOnlyDictionary<FieldGroup,IReadOnlyList<ContingentValue>>possibleZonings=parcels.GetContingentValues(rowBuffer,zoningFieldName);IEnumerable<FieldGroup>possibleFieldGroups=possibleZonings.Keys;foreach(FieldGrouppossibleFieldGroupinpossibleFieldGroups){IReadOnlyList<ContingentValue>possibleZoningValues=possibleZonings[possibleFieldGroup];foreach(ContingentValuepossibleZoningValueinpossibleZoningValues){switch(possibleZoningValue){caseContingentCodedValuecodedValue:stringcodedValueDomainName=codedValue.Name;objectcodedValueDomainValue=codedValue.CodedValue;break;caseContingentRangeValuerangeValue:objectrangeDomainMaxValue=rangeValue.Max;objectrangeDomainMinValue=rangeValue.Min;break;caseContingentAnyValuecontingentAnyValue:// Any value typebreak;caseContingentNullValuecontingentNullValue:// Null valuebreak;}}}}}
Editing
Creating a Row
publicasyncTaskCreatingARow(){stringmessage=String.Empty;boolcreationResult=false;EditOperationeditOperation=newEditOperation();awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file\\sdefile.sde"))))using(TableenterpriseTable=geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost")){//var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(uri)) for a File GDB////var shapeFileConnPath = new FileSystemConnectionPath(uri, FileSystemDatastoreType.Shapefile);//var shapefile = new FileSystemDatastore(shapeFileConnPath);//var table = shapefile.OpenDataset<Table>(strShapeFileName); for a Shape file//declare the callback here. We are not executing it .yet.editOperation.Callback(context =>{TableDefinitiontableDefinition=enterpriseTable.GetDefinition();intassetNameIndex=tableDefinition.FindField("ASSETNA");using(RowBufferrowBuffer=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;using(Rowrow=enterpriseTable.CreateRow(rowBuffer)){// To Indicate that the attribute table has to be updated.context.Invalidate(row);}}},enterpriseTable);try{creationResult=editOperation.Execute();if(!creationResult)message=editOperation.ErrorMessage;}catch(GeodatabaseExceptionexObj){message=exObj.Message;}}});if(!string.IsNullOrEmpty(message))MessageBox.Show(message);}
Creating a Feature
publicasyncTaskCreatingAFeature(){stringmessage=String.Empty;boolcreationResult=false;awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file\\sdefile.sde"))))using(FeatureClassenterpriseFeatureClass=geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite")){//var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(uri)) for a File GDB////var shapeFileConnPath = new FileSystemConnectionPath(uri, FileSystemDatastoreType.Shapefile);//var shapefile = new FileSystemDatastore(shapeFileConnPath);//var table = shapefile.OpenDataset<Table>(strShapeFileName); for a Shape file//declare the callback here. We are not executing it yetEditOperationeditOperation=newEditOperation();editOperation.Callback(context =>{FeatureClassDefinitionfacilitySiteDefinition=enterpriseFeatureClass.GetDefinition();intfacilityIdIndex=facilitySiteDefinition.FindField("FACILITYID");using(RowBufferrowBuffer=enterpriseFeatureClass.CreateRowBuffer()){// Either the field index or the field name can be used in the indexer.rowBuffer[facilityIdIndex]="wMain";rowBuffer["NAME"]="Griffith Park";rowBuffer["OWNTYPE"]="Municipal";rowBuffer["FCODE"]="Park";// Add it to Public Attractions Subtype.rowBuffer[facilitySiteDefinition.GetSubtypeField()]=820;List<Coordinate2D>newCoordinates=newList<Coordinate2D>{newCoordinate2D(1021570,1880583),newCoordinate2D(1028730,1880994),newCoordinate2D(1029718,1875644),newCoordinate2D(1021405,1875397)};rowBuffer[facilitySiteDefinition.GetShapeField()]=newPolygonBuilderEx(newCoordinates).ToGeometry();using(Featurefeature=enterpriseFeatureClass.CreateRow(rowBuffer)){//To Indicate that the attribute table has to be updatedcontext.Invalidate(feature);}}},enterpriseFeatureClass);try{creationResult=editOperation.Execute();if(!creationResult)message=editOperation.ErrorMessage;}catch(GeodatabaseExceptionexObj){message=exObj.Message;}}});if(!string.IsNullOrEmpty(message))MessageBox.Show(message);}
Modifying a Row
publicasyncTaskModifyingARow(){stringmessage=String.Empty;boolmodificationResult=false;awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file\\sdefile.sde"))))using(TableenterpriseTable=geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost")){//var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(uri)) for a File GDB////var shapeFileConnPath = new FileSystemConnectionPath(uri, FileSystemDatastoreType.Shapefile);//var shapefile = new FileSystemDatastore(shapeFileConnPath);//var table = shapefile.OpenDataset<Table>(strShapeFileName); for a Shape fileEditOperationeditOperation=newEditOperation();editOperation.Callback(context =>{QueryFilteropenCutFilter=newQueryFilter{WhereClause="ACTION = 'Open Cut'"};using(RowCursorrowCursor=enterpriseTable.Search(openCutFilter,false)){TableDefinitiontableDefinition=enterpriseTable.GetDefinition();intsubtypeFieldIndex=tableDefinition.FindField(tableDefinition.GetSubtypeField());while(rowCursor.MoveNext()){using(Rowrow=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["ASSETNA"]="wMainOpenCut";if(Convert.ToDouble(row["COST"])>700){// Abandon asset if cost is higher than 700 (if that is what you want to do).row["ACTION"]="Open Cut Abandon";row[subtypeFieldIndex]=3;//subtype value for "Abandon" }//After all the changes are done, persist it.row.Store();// Has to be called after the store too.context.Invalidate(row);}}}},enterpriseTable);try{modificationResult=editOperation.Execute();if(!modificationResult)message=editOperation.ErrorMessage;}catch(GeodatabaseExceptionexObj){message=exObj.Message;}}});if(!string.IsNullOrEmpty(message))MessageBox.Show(message);}
Modifying a Feature
publicasyncTaskModifyingAFeature(){stringmessage=String.Empty;boolmodificationResult=false;awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file\\sdefile.sde"))))using(FeatureClassenterpriseFeatureClass=geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite")){//var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(uri)) for a File GDB////var shapeFileConnPath = new FileSystemConnectionPath(uri, FileSystemDatastoreType.Shapefile);//var shapefile = new FileSystemDatastore(shapeFileConnPath);//var table = shapefile.OpenDataset<Table>(strShapeFileName); for a Shape fileFeatureClassDefinitionfacilitySiteDefinition=enterpriseFeatureClass.GetDefinition();intownTypeIndex=facilitySiteDefinition.FindField("OWNTYPE");intareaIndex=facilitySiteDefinition.FindField(facilitySiteDefinition.GetAreaField());EditOperationeditOperation=newEditOperation();editOperation.Callback(context =>{QueryFilterqueryFilter=newQueryFilter{WhereClause="FCODE = 'Hazardous Materials Facility' AND OWNTYPE = 'Private'"};using(RowCursorrowCursor=enterpriseFeatureClass.Search(queryFilter,false)){while(rowCursor.MoveNext()){using(Featurefeature=(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 rowcontext.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=newList<Coordinate2D>{newCoordinate2D(1021570,1880583),newCoordinate2D(1028730,1880994),newCoordinate2D(1029718,1875644),newCoordinate2D(1021405,1875397)};feature.SetShape(newPolygonBuilderEx(newCoordinates).ToGeometry());}feature.Store();// Has to be called after the store toocontext.Invalidate(feature);}}}},enterpriseFeatureClass);try{modificationResult=editOperation.Execute();if(!modificationResult)message=editOperation.ErrorMessage;}catch(GeodatabaseExceptionexObj){message=exObj.Message;}}});if(!string.IsNullOrEmpty(message))MessageBox.Show(message);}
Writing a value into a Guid column
row[field.Name]="{"+guid.ToString()+"}";
Deleting a Row/Feature
publicasyncTaskDeletingARowOrFeature(){stringmessage=String.Empty;booldeletionResult=false;awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file\\sdefile.sde"))))using(TableenterpriseTable=geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost")){//var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(uri)) for a File GDB////var shapeFileConnPath = new FileSystemConnectionPath(uri, FileSystemDatastoreType.Shapefile);//var shapefile = new FileSystemDatastore(shapeFileConnPath);//var table = shapefile.OpenDataset<Table>(strShapeFileName); for a Shape fileEditOperationeditOperation=newEditOperation();editOperation.Callback(context =>{QueryFilteropenCutFilter=newQueryFilter{WhereClause="ACTION = 'Open Cut'"};using(RowCursorrowCursor=enterpriseTable.Search(openCutFilter,false)){while(rowCursor.MoveNext()){using(Rowrow=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);try{deletionResult=editOperation.Execute();if(!deletionResult)message=editOperation.ErrorMessage;}catch(GeodatabaseExceptionexObj){message=exObj.Message;}}});if(!string.IsNullOrEmpty(message))MessageBox.Show(message);}
Split a feature by geometry
publicvoidSplitALineByPoint(FeatureClasslineFeatureClass,MapPointxPoint){using(RowCursorrowCursor=lineFeatureClass.Search(newQueryFilter(){ObjectIDs=newList<long>(){1}})){if(rowCursor.MoveNext()){using(Featurefeature=rowCursor.CurrentasFeature){// ObjectIDs of newly created linesIReadOnlyList<long>splits=feature.Split(xPoint);}}}}
publicasyncTaskWriteBlobField(Tabletable,stringblobFieldName,stringimageFileName){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{// Read the image file into a MemoryStreamMemoryStreammemoryStream=newMemoryStream();;using(FileStreamimageFile=newFileStream(imageFileName,FileMode.Open,FileAccess.Read)){imageFile.CopyTo(memoryStream);}// Create a new row in the table, and write the Memory Stream into a blob fieleusing(RowBufferrowBuffer=table.CreateRowBuffer()){rowBuffer[blobFieldName]=memoryStream;table.CreateRow(rowBuffer).Dispose();}});}
Reading a Blob field
publicasyncTaskReadBlobField(Tabletable,QueryFilterqueryFilter,stringblobFieldName){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{conststringimageFileBaseName="C:\\path\\to\\image\\directory\\Image";// for each row that satisfies the search criteria, write the blob field out to an image fileusing(RowCursorrowCursor=table.Search(queryFilter)){intfileCount=0;while(rowCursor.MoveNext()){using(Rowrow=rowCursor.Current){// Read the blob field into a MemoryStreamMemoryStreammemoryStream=row[blobFieldName]asMemoryStream;// Create a fileusing(FileStreamoutputFile=newFileStream(imageFileBaseName+fileCount.ToString(),FileMode.Create,FileAccess.Write)){// Write the MemoryStream into the filememoryStream.WriteTo(outputFile);}}}}});}
Getting Rows related by RelationshipClass
publicasyncTaskGettingRowsRelatedByRelationshipClass(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file"))))using(RelationshipClassrelationshipClass=geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.luCodeViolationHasInspections"))using(FeatureClassviolationsFeatureClass=geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.luCodeViolation"))using(TableinspectionTable=geodatabase.OpenDataset<Table>("LocalGovernment.GDB.luCodeInspection")){List<Row>jeffersonAveViolations=newList<Row>();QueryFilterqueryFilter=newQueryFilter{WhereClause="LOCDESC LIKE '///%Jefferson///%'"};using(RowCursorrowCursor=violationsFeatureClass.Search(queryFilter,false)){while(rowCursor.MoveNext()){jeffersonAveViolations.Add(rowCursor.Current);}}IReadOnlyList<Row>relatedOriginRows=null;IReadOnlyList<Row>relatedDestinationRows=null;try{QueryFilterfilter=newQueryFilter{WhereClause="ACTION = '1st Notice'"};using(Selectionselection=inspectionTable.Select(filter,SelectionType.ObjectID,SelectionOption.Normal)){relatedOriginRows=relationshipClass.GetRowsRelatedToDestinationRows(selection.GetObjectIDs());}boolcontainsJeffersonAve=relatedOriginRows.Any(row =>Convert.ToString(row["LOCDESC"]).Contains("Jefferson"));List<long>jeffersonAveViolationObjectIds=jeffersonAveViolations.Select(row =>row.GetObjectID()).ToList();relatedDestinationRows=relationshipClass.GetRowsRelatedToOriginRows(jeffersonAveViolationObjectIds);boolhasFirstNoticeInspections=relatedDestinationRows.Any(row =>Convert.ToString(row["ACTION"]).Contains("1st Notice"));}finally{Dispose(jeffersonAveViolations);Dispose(relatedOriginRows);Dispose(relatedDestinationRows);}}});}privatestaticvoidDispose(IEnumerable<Row>rows){foreach(Rowrowinrows)row.Dispose();}
Creating a Relationship
publicasyncTaskCreatingARelationship(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file"))))using(RelationshipClassrelationshipClass=geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.OverviewToProject"))using(FeatureClassprojectsFeatureClass=geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.CIPProjects"))using(FeatureClassoverviewFeatureClass=geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.CIPProjectsOverview")){// This will be PROJNAME. This can be used to get the field index or used directly as the field name.stringoriginKeyField=relationshipClass.GetDefinition().GetOriginKeyField();EditOperationeditOperation=newEditOperation();editOperation.Callback(context =>{// The rows are being added to illustrate adding relationships. If one has existing rows, those can be used to add a relationship.using(RowBufferprojectsRowBuffer=projectsFeatureClass.CreateRowBuffer())using(RowBufferoverviewRowBuffer=overviewFeatureClass.CreateRowBuffer()){projectsRowBuffer["TOTCOST"]=500000;overviewRowBuffer[originKeyField]="LibraryConstruction";overviewRowBuffer["PROJECTMAN"]="John Doe";overviewRowBuffer["FUNDSOUR"]="Public";using(RowprojectsRow=projectsFeatureClass.CreateRow(projectsRowBuffer))using(RowoverviewRow=overviewFeatureClass.CreateRow(overviewRowBuffer)){Relationshiprelationship=relationshipClass.CreateRelationship(overviewRow,projectsRow);//To Indicate that the Map has to draw this feature/row and/or the attribute table has to be updatedcontext.Invalidate(projectsRow);context.Invalidate(overviewRow);context.Invalidate(relationshipClass);}}},projectsFeatureClass,overviewFeatureClass);booleditResult=editOperation.Execute();}});}
Deleting a Relationship
publicasyncTaskDeletingARelationship(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file"))))using(RelationshipClassrelationshipClass=geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.luCodeViolationHasInspections"))using(FeatureClassviolationsFeatureClass=geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.luCodeViolation")){QueryFilterqueryFilter=newQueryFilter{WhereClause="LOCDESC LIKE '///%Jefferson///%'"};using(RowCursorrowCursor=violationsFeatureClass.Search(queryFilter,false)){if(!rowCursor.MoveNext())return;using(RowjeffersonAveViolation=rowCursor.Current){IReadOnlyList<Row>relatedDestinationRows=relationshipClass.GetRowsRelatedToOriginRows(newList<long>{jeffersonAveViolation.GetObjectID()});try{EditOperationeditOperation=newEditOperation();editOperation.Callback(context =>{foreach(RowrelatedDestinationRowinrelatedDestinationRows){try{relationshipClass.DeleteRelationship(jeffersonAveViolation,relatedDestinationRow);}catch(GeodatabaseRelationshipClassExceptionexception){Console.WriteLine(exception);}}},relationshipClass);booleditResult=editOperation.Execute();}finally{foreach(RowrowinrelatedDestinationRows)row.Dispose();}}}}});}
Using an Insert Cursor
// Insert Cursors are intended for use in CoreHost applications, not Pro Add-inspublicvoidUsingInsertCursor(){using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file"))))using(TablecitiesTable=geodatabase.OpenDataset<Table>("name\\of\\cities_table")){geodatabase.ApplyEdits(()=>{using(InsertCursorinsertCursor=citiesTable.CreateInsertCursor())using(RowBufferrowBuffer=citiesTable.CreateRowBuffer()){rowBuffer["State"]="Colorado";rowBuffer["Name"]="Fort Collins";rowBuffer["Population"]=167830;insertCursor.Insert(rowBuffer);rowBuffer["Name"]="Denver";rowBuffer["Population"]=727211;insertCursor.Insert(rowBuffer);// Insert more rows here// A more realistic example would be reading source data from a fileinsertCursor.Flush();}});}}
Creating a new Annotation Feature in an Annotation FeatureClass using a RowBuffer
publicasyncTaskCreatingAnAnnotationFeature(Geodatabasegeodatabase){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(AnnotationFeatureClassannotationFeatureClass=geodatabase.OpenDataset<AnnotationFeatureClass>("Annotation // feature // class // name"))using(AnnotationFeatureClassDefinitionannotationFeatureClassDefinition=annotationFeatureClass.GetDefinition())using(RowBufferrowBuffer=annotationFeatureClass.CreateRowBuffer())using(AnnotationFeatureannotationFeature=annotationFeatureClass.CreateRow(rowBuffer)){annotationFeature.SetAnnotationClassID(0);annotationFeature.SetStatus(AnnotationStatus.Placed);// Get the annotation labels from the label collectionIReadOnlyList<CIMLabelClass>labelClasses=annotationFeatureClassDefinition.GetLabelClassCollection();// Setup the symbol reference with the symbol id and the text symbolCIMSymbolReferencecimSymbolReference=newCIMSymbolReference();cimSymbolReference.Symbol=labelClasses[0].TextSymbol.Symbol;cimSymbolReference.SymbolName=labelClasses[0].TextSymbol.SymbolName;// Setup the text graphicCIMTextGraphiccimTextGraphic=newCIMTextGraphic();cimTextGraphic.Text="Charlotte, North Carolina";cimTextGraphic.Shape=newMapPointBuilderEx(newCoordinate2D(-80.843,35.234),SpatialReferences.WGS84).ToGeometry();cimTextGraphic.Symbol=cimSymbolReference;// Set the symbol reference on the graphic and storeannotationFeature.SetGraphic(cimTextGraphic);annotationFeature.Store();}});}
Reconciling and Posting a Version with its Parent in separate edit sessions
publicvoidReconcileAndPost(Geodatabasegeodatabase){// Get a reference to our version and our parentif(geodatabase.IsVersioningSupported()){using(VersionManagerversionManager=geodatabase.GetVersionManager())using(VersioncurrentVersion=versionManager.GetCurrentVersion())using(VersionparentVersion=currentVersion.GetParent()){//// Create a ReconcileDescription object//At 2.x - //ReconcileDescription reconcileDescription = new ReconcileDescription(parentVersion);//reconcileDescription.ConflictResolutionMethod = ConflictResolutionMethod.Continue; // continue if conflicts are found//reconcileDescription.WithPost = true;//// Reconcile and post//ReconcileResult reconcileResult = currentVersion.Reconcile(reconcileDescription);// ReconcileResult.HasConflicts can be checked as-needed// Create a ReconcileOptions objectReconcileOptionsreconcileOptions=newReconcileOptions(parentVersion);reconcileOptions.ConflictResolutionMethod=ConflictResolutionMethod.Continue;// continue if conflicts are foundreconcileOptions.ConflictDetectionType=ConflictDetectionType.ByRow;//DefaultreconcileOptions.ConflictResolutionType=ConflictResolutionType.FavorTargetVersion;//or FavorEditVersion// ReconcileReconcileResultreconcileResult=currentVersion.Reconcile(reconcileOptions);if(!reconcileResult.HasConflicts){//No conflicts, perform the postPostOptionspostOptions=newPostOptions(parentVersion);//var postOptions = new PostOptions(); for default versionpostOptions.ServiceSynchronizationType=ServiceSynchronizationType.Synchronous;//DefaultcurrentVersion.Post(postOptions);}}}}
Reconciling and Posting a Version with its Parent in the same edit session
publicvoidReconcileAndPost2(Geodatabasegeodatabase){// Get a reference to our version and our parentif(geodatabase.IsVersioningSupported()){using(VersionManagerversionManager=geodatabase.GetVersionManager())using(VersioncurrentVersion=versionManager.GetCurrentVersion())using(VersionparentVersion=currentVersion.GetParent()){//// Create a ReconcileDescription object//At 2.x - //ReconcileDescription reconcileDescription = new ReconcileDescription(parentVersion);//reconcileDescription.ConflictResolutionMethod = ConflictResolutionMethod.Continue; // continue if conflicts are found//reconcileDescription.WithPost = true;//// Reconcile and post//ReconcileResult reconcileResult = currentVersion.Reconcile(reconcileDescription);// ReconcileResult.HasConflicts can be checked as-needed// Create a ReconcileOptions objectReconcileOptionsreconcileOptions=newReconcileOptions(parentVersion);reconcileOptions.ConflictResolutionMethod=ConflictResolutionMethod.Continue;// continue if conflicts are foundreconcileOptions.ConflictDetectionType=ConflictDetectionType.ByRow;//DefaultreconcileOptions.ConflictResolutionType=ConflictResolutionType.FavorTargetVersion;//or FavorEditVersionPostOptionspostOptions=newPostOptions(parentVersion);//var postOptions = new PostOptions(); for default versionpostOptions.ServiceSynchronizationType=ServiceSynchronizationType.Synchronous;//Default// ReconcileReconcileResultreconcileResult=currentVersion.Reconcile(reconcileOptions,postOptions);if(reconcileResult.HasConflicts){//TODO resolve conflicts}}}}
// Check to see if the current version is default.// Works with both branch and traditional versioning.publicboolIsDefaultVersion(Versionversion){VersionparentVersion=version.GetParent();if(parentVersion==null){returntrue;}parentVersion.Dispose();returnfalse;}publicboolIsDefaultVersion(Geodatabasegeodatabase){if(!geodatabase.IsVersioningSupported())returnfalse;using(VersionManagerversionManager=geodatabase.GetVersionManager())using(VersioncurrentVersion=versionManager.GetCurrentVersion()){returnIsDefaultVersion(currentVersion);}}// Gets the default version.// Works with both branch and traditional versioning.// Note that this routine depends on IsDefaultVersion(), above.publicVersionGetDefaultVersion(Versionversion){if(IsDefaultVersion(version)){returnversion;}else{Versionparent=version.GetParent();Versionancestor=GetDefaultVersion(parent);if(parent!=ancestor){parent.Dispose();//If the versioning tree is more than 2 deep, we want to dispose any intermediary versions}returnancestor;}}publicVersionGetDefaultVersion(Geodatabasegeodatabase){if(!geodatabase.IsVersioningSupported())returnnull;using(VersionManagerversionManager=geodatabase.GetVersionManager()){VersioncurrentVersion=versionManager.GetCurrentVersion();VersiondefaultVersion=GetDefaultVersion(currentVersion);if(currentVersion!=defaultVersion){currentVersion.Dispose();// If we are not pointing to default, we want to dispose this Version object}returndefaultVersion;}}
publicvoidChangeVersions(Geodatabasegeodatabase,stringtoVersionName){using(VersionManagerversionManager=geodatabase.GetVersionManager()){VersionBaseTypeversionBaseType=versionManager.GetCurrentVersionBaseType();if(versionBaseType==VersionBaseType.Version){VersionfromVersion=versionManager.GetCurrentVersion();VersiontoVersion=versionManager.GetVersion(toVersionName);// Switch between versionsMapView.Active.Map.ChangeVersion(fromVersion,toVersion);}if(versionBaseType==VersionBaseType.HistoricalVersion){HistoricalVersionfromHistoricalVersion=versionManager.GetCurrentHistoricalVersion();HistoricalVersiontoHistoricalVersion=versionManager.GetHistoricalVersion(toVersionName);// Switch between historical versionsMapView.Active.Map.ChangeVersion(fromHistoricalVersion,toHistoricalVersion);}// Switch from HistoricalVersion to Version and vice-versa // MapView.Active.Map.ChangeVersion(fromHistoricalVersion, toVersion);// MapView.Active.Map.ChangeVersion(fromVersion, toHistoricalVersion);}}
Partial Posting
// Partial posting allows developers to post a subset of changes made in a version.// One sample use case is an electric utility that uses a version to design the facilities in// a new housing subdivision. At some point in the process, one block of new houses have been// completed, while the rest of the subdivision remains unbuilt. Partial posting allows the user// to post the completed work, while leaving not yet constructed features in the version to be// posted later. Partial posting requires a branch-versioned feature service using ArcGIS// Enterprise 10.9 and higher// Specify a set of features that were constructedQueryFilterconstructedFilter=newQueryFilter(){WhereClause="ConstructedStatus = 'True'"};// This selection represents the inserts and updates to the support// structure feature class that we wish to postusing(SelectionconstructedSupportStructures=supportStructureFeatureClass.Select(constructedFilter,SelectionType.ObjectID,SelectionOption.Normal)){// Specifying which feature deletions you wish to post is slightly trickier, since you cannot issue// a query to fetch a set of deleted features Instead, a list of ObjectIDs must be usedusing(SelectiondeletedSupportStructures=supportStructureFeatureClass.Select(null,SelectionType.ObjectID,SelectionOption.Empty)){deletedSupportStructures.Add(deletedSupportStructureObjectIDs);//deletedSupportStructureObjectIDs is//defined as List<long>//Perform the reconcile with partial post//At 2.x - //ReconcileDescription reconcileDescription = new ReconcileDescription();//reconcileDescription.ConflictDetectionType = ConflictDetectionType.ByColumn;//reconcileDescription.ConflictResolutionMethod = ConflictResolutionMethod.Continue;//reconcileDescription.ConflictResolutionType = ConflictResolutionType.FavorEditVersion;//reconcileDescription.PartialPostSelections = new List<Selection>() { constructedSupportStructures, deletedSupportStructures };//reconcileDescription.WithPost = true;//ReconcileResult reconcileResult = designVersion.Reconcile(reconcileDescription);ReconcileOptionsreconcileOptions=newReconcileOptions();//reconcile against DefaultreconcileOptions.ConflictDetectionType=ConflictDetectionType.ByColumn;reconcileOptions.ConflictResolutionMethod=ConflictResolutionMethod.Continue;reconcileOptions.ConflictResolutionType=ConflictResolutionType.FavorEditVersion;PostOptionspostOptions=newPostOptions();//post against DefaultpostOptions.PartialPostSelections=newList<Selection>(){constructedSupportStructures,deletedSupportStructures};postOptions.ServiceSynchronizationType=ServiceSynchronizationType.Synchronous;ReconcileResultreconcileResult=designVersion.Reconcile(reconcileOptions,postOptions);//TODO process result(s)}}
Iterate datasets inside a feature dataset
publicvoidIterateDatasetsFromAFeatureDataset(Geodatabasegeodatabase,stringfeatureDatasetName="City",stringfeatureClassInFeatureDataset="Buildings"){// Open a feature datasetusing(FeatureDatasetcityFeatureDataset=geodatabase.OpenDataset<FeatureDataset>(featureDatasetName)){// Get a feature class definition from a feature datasetFeatureClassDefinitionbuildingsFeatureClassDefinition=cityFeatureDataset.GetDefinition<FeatureClassDefinition>(featureClassInFeatureDataset);// Iterate dataset definitionIReadOnlyList<FeatureClassDefinition>cityFeatureClassDefinitions=cityFeatureDataset.GetDefinitions<FeatureClassDefinition>();foreach(FeatureClassDefinitioncityFeatureClassDefinitionincityFeatureClassDefinitions){// Use feature class definition}}}
Get attribute rules of a dataset
publicvoidGetAttributeRules(Geodatabasegeodatabase,stringtableName){using(TableDefinitiontableDefinition=geodatabase.GetDefinition<TableDefinition>(tableName)){// Get all attribute rule typesIReadOnlyList<AttributeRuleDefinition>ruleDefinitions=tableDefinition.GetAttributeRules();// Iterate rule definitionsforeach(AttributeRuleDefinitionruleDefinitioninruleDefinitions){AttributeRuleTyperuleType=ruleDefinition.GetAttributeRuleType();stringruleDescription=ruleDefinition.GetDescription();boolisAttributeFieldEditable=ruleDefinition.GetIsFieldEditable();stringarcadeVersionToSupportRule=ruleDefinition.GetMinimumArcadeVersion();intruleEvaluationOrder=ruleDefinition.GetEvaluationOrder();AttributeRuleTriggerstriggeringEvents=ruleDefinition.GetTriggeringEvents();stringscriptExpression=ruleDefinition.GetScriptExpression();// more properties}}}
Creating a row buffer from a template row
publicvoidCreateRowBufferFromARow(Tabletable){using(RowCursorrowCursor=table.Search()){if(rowCursor.MoveNext()){using(RowtemplateRow=rowCursor.Current){RowBufferrowBuffer=table.CreateRowBuffer(templateRow);// Manipulate row buffer// Doesn't allow copying values of ObjectID and GlobalID//// rowBuffer["Field"] = "Update";//// create a new rowtable.CreateRow(rowBuffer);}}}}
Extension Ids
Table Extension Ids
publicvoidExtensionIds1(Tabletable){//Add an extension id to a table//Check documentation for restrictions on backward compatibility - backward//compatibility is limited to ArcGIS Pro 3.1 if an extension id is added.//Note: This is an extension method. It is for use in addins only and not CoreHost.stringextension_id_string="52d8f3be-b73d-4140-beaf-23d4f9b697ea";Guidextension_id=Guid.Parse(extension_id_string);//Note: Must be within the lambda of QueuedTask.Run(() => { ...//register the extension id with the relevant tabletable.AddActivationExtension(extension_id);//Remove an extension id from a table//Restores backward compatibility assuming no other compatibility limitations are//in place.//Note: This is an extension method. It is for use in addins only and not CoreHost.table.RemoveActivationExtension(extension_id);//Check if a given extension id is registered with a particular table.//Note: This is an extension method. It is for use in addins only and not CoreHost.if(table.GetHasActivationExtension(extension_id)){//TODO - implement custom logic relevant to presence of extension_id}//Enumerate all extension ids on a given table.//Note: This is an extension method. It is for use in addins only and not CoreHost.foreach(Guidext_idintable.GetActivationExtensions()){//TODO - logic based on extension ids}}
// Earthquake occurrences date and time// 9/28/2014 (DateOnly)FieldDescriptionearthquakeDateOnlyFieldDescription=newFieldDescription("Earthquake_DateOnly",FieldType.DateOnly);// 1:16:42 AM (TimeOnly)FieldDescriptionearthquakeTimeOnlyFieldDescription=newFieldDescription("Earthquake_TimeOnly",FieldType.TimeOnly);// 9/28/2014 1:16:42.000 AM -09:00 (Timestamp with Offset)FieldDescriptionearthquakeTimestampOffsetFieldDescription=newFieldDescription("Earthquake_TimestampOffset_Local",FieldType.TimestampOffset);// 9/28/2014 1:16:42 AM (DateTime)FieldDescriptionearthquakeDateFieldDescription=newFieldDescription("Earthquake_Date",FieldType.Date);
Creating a Table
publicvoidCreateTableSnippet(Geodatabasegeodatabase,CodedValueDomaininspectionResultsDomain){// Create a PoleInspection table with the following fields// GlobalID// ObjectID// InspectionDate (date)// InspectionResults (pre-existing InspectionResults coded value domain)// InspectionNotes (string)// This static helper routine creates a FieldDescription for a GlobalID field with default valuesFieldDescriptionglobalIDFieldDescription=FieldDescription.CreateGlobalIDField();// This static helper routine creates a FieldDescription for an ObjectID field with default valuesFieldDescriptionobjectIDFieldDescription=FieldDescription.CreateObjectIDField();// Create a FieldDescription for the InspectionDate fieldFieldDescriptioninspectionDateFieldDescription=newFieldDescription("InspectionDate",FieldType.Date){AliasName="Inspection Date"};// This static helper routine creates a FieldDescription for a Domain field (from a pre-existing domain)FieldDescriptioninspectionResultsFieldDescription=FieldDescription.CreateDomainField("InspectionResults",newCodedValueDomainDescription(inspectionResultsDomain));inspectionResultsFieldDescription.AliasName="Inspection Results";// This static helper routine creates a FieldDescription for a string fieldFieldDescriptioninspectionNotesFieldDescription=FieldDescription.CreateStringField("InspectionNotes",512);inspectionNotesFieldDescription.AliasName="Inspection Notes";// Assemble a list of all of our field descriptionsList<FieldDescription>fieldDescriptions=newList<FieldDescription>(){globalIDFieldDescription,objectIDFieldDescription,inspectionDateFieldDescription,inspectionResultsFieldDescription,inspectionNotesFieldDescription};// Create a TableDescription object to describe the table to createTableDescriptiontableDescription=newTableDescription("PoleInspection",fieldDescriptions);// Create a SchemaBuilder objectSchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Add the creation of PoleInspection to our list of DDL tasksschemaBuilder.Create(tableDescription);// Execute the DDLboolsuccess=schemaBuilder.Build();// Inspect error messagesif(!success){IReadOnlyList<string>errorMessages=schemaBuilder.ErrorMessages;//etc.}}
Creating a feature class
publicvoidCreateFeatureClassSnippet(Geodatabasegeodatabase,FeatureClassexistingFeatureClass,SpatialReferencespatialReference){// Create a Cities feature class with the following fields// GlobalID// ObjectID// Name (string)// Population (integer)// This static helper routine creates a FieldDescription for a GlobalID field with default valuesFieldDescriptionglobalIDFieldDescription=FieldDescription.CreateGlobalIDField();// This static helper routine creates a FieldDescription for an ObjectID field with default valuesFieldDescriptionobjectIDFieldDescription=FieldDescription.CreateObjectIDField();// This static helper routine creates a FieldDescription for a string fieldFieldDescriptionnameFieldDescription=FieldDescription.CreateStringField("Name",255);// This static helper routine creates a FieldDescription for an integer fieldFieldDescriptionpopulationFieldDescription=FieldDescription.CreateIntegerField("Population");// Assemble a list of all of our field descriptionsList<FieldDescription>fieldDescriptions=newList<FieldDescription>(){globalIDFieldDescription,objectIDFieldDescription,nameFieldDescription,populationFieldDescription};// Create a ShapeDescription objectShapeDescriptionshapeDescription=newShapeDescription(GeometryType.Point,spatialReference);// Alternatively, ShapeDescriptions can be created from another feature class. In this case, the new feature class will inherit the same shape properties of the existing classShapeDescriptionalternativeShapeDescription=newShapeDescription(existingFeatureClass.GetDefinition());// Create a FeatureClassDescription object to describe the feature class to createFeatureClassDescriptionfeatureClassDescription=newFeatureClassDescription("Cities",fieldDescriptions,shapeDescription);// Create a SchemaBuilder objectSchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Add the creation of the Cities feature class to our list of DDL tasksschemaBuilder.Create(featureClassDescription);// Execute the DDLboolsuccess=schemaBuilder.Build();// Inspect error messagesif(!success){IReadOnlyList<string>errorMessages=schemaBuilder.ErrorMessages;//etc.}}
Deleting a Table
publicvoidDeleteTableSnippet(Geodatabasegeodatabase,Tabletable){// Create a TableDescription objectTableDescriptiontableDescription=newTableDescription(table.GetDefinition());// Create a SchemaBuilder objectSchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Add the deletion of the table to our list of DDL tasksschemaBuilder.Delete(tableDescription);// Execute the DDLboolsuccess=schemaBuilder.Build();}
Deleting a Feature Class
publicvoidDeleteFeatureClassSnippet(Geodatabasegeodatabase,FeatureClassfeatureClass){// Create a FeatureClassDescription objectFeatureClassDescriptionfeatureClassDescription=newFeatureClassDescription(featureClass.GetDefinition());// Create a SchemaBuilder objectSchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Add the deletion fo the feature class to our list of DDL tasksschemaBuilder.Delete(featureClassDescription);// Execute the DDLboolsuccess=schemaBuilder.Build();}
Opens a memory geodatabase
publicvoidOpenMemoryGeodatabase(){// Connects to the default memory geodatabase, if exists otherwise throws exceptionMemoryConnectionPropertiesmemoryConnectionProperties=newMemoryConnectionProperties();// Alternatively, connects to memory geodatabase named as 'InterimMemoryGeodatabase'// MemoryConnectionProperties memoryConnectionProperties = new MemoryConnectionProperties("InterimMemoryGeodatabase");// Opens the memory geodatabaseusing(Geodatabasegeodatabase=newGeodatabase(memoryConnectionProperties)){// Use memory geodatabase}}
Creating a memory Geodatabase
publicvoidCreateMemoryGeodatabaseSnippet(){// Create the memory connection properties to connect to default memory geodatabaseMemoryConnectionPropertiesmemoryConnectionProperties=newMemoryConnectionProperties();// Alternatively create the memory connection properties to connect to memory geodatabase named as 'InterimMemoryGeodatabase'// MemoryConnectionProperties memoryConnectionProperties = new MemoryConnectionProperties("InterimMemoryGeodatabase");// Creates the new memory geodatabase if it does not exist or connects to an existing one if it already existsusing(Geodatabasegeodatabase=newGeodatabase(memoryConnectionProperties)){// Create additional schema here}}
Deleting a memory Geodatabase
publicvoidDeleteMemoryGeodatabaseSnippet(){// Create the memory connection properties to connect to default memory geodatabaseMemoryConnectionPropertiesmemoryConnectionProperties=newMemoryConnectionProperties();// Delete the memory geodatabaseSchemaBuilder.DeleteGeodatabase(memoryConnectionProperties);}
Creating a File Geodatabase
publicvoidCreateFileGeodatabaseSnippet(){// Create a FileGeodatabaseConnectionPath with the name of the file geodatabase you wish to createFileGeodatabaseConnectionPathfileGeodatabaseConnectionPath=newFileGeodatabaseConnectionPath(newUri(@"C:\Path-To-File-Geodatabase\YourName.gdb"));// Create and use the file geodatabaseusing(Geodatabasegeodatabase=SchemaBuilder.CreateGeodatabase(fileGeodatabaseConnectionPath)){// Create additional schema here}}
Deleting a File Geodatabase
publicvoidDeleteFileGeodatabaseSnippet(){// Create a FileGeodatabaseConnectionPath with the name of the file geodatabase you wish to deleteFileGeodatabaseConnectionPathfileGeodatabaseConnectionPath=newFileGeodatabaseConnectionPath(newUri(@"C:\Path-To-File-Geodatabase\YourName.gdb"));// Delete the file geodatabaseSchemaBuilder.DeleteGeodatabase(fileGeodatabaseConnectionPath);}
Creating a Mobile Geodatabase
publicvoidCreateMobileGeodatabase(){// Create a MobileGeodatabaseConnectionPath with the name of the mobile geodatabase you wish to createMobileGeodatabaseConnectionPathmobileGeodatabaseConnectionPath=newMobileGeodatabaseConnectionPath(newUri(@"C:\Path-To-Mobile-Geodatabase\YourName.geodatabase"));// Create and use the mobile geodatabaseusing(Geodatabasegeodatabase=SchemaBuilder.CreateGeodatabase(mobileGeodatabaseConnectionPath)){// Create additional schema here}}
Deleting a Mobile Geodatabase
publicvoidDeleteMobileGeodatabase(){// Create a MobileGeodatabaseConnectionPath with the name of the mobile geodatabase you wish to deleteMobileGeodatabaseConnectionPathmobileGeodatabaseConnectionPath=newMobileGeodatabaseConnectionPath(newUri(@"C:\Path-To-Mobile-Geodatabase\YourName.geodatabase"));// Delete the mobile geodatabaseSchemaBuilder.DeleteGeodatabase(mobileGeodatabaseConnectionPath);}
Creating a Range domain
publicvoidCreateRangeDomainSnippet(Geodatabasegeodatabase){// Create a range description with minimum value = 0 and maximum value = 1000RangeDomainDescriptionrangeDomainDescriptionMinMax=newRangeDomainDescription("RangeDomain_0_1000",FieldType.Integer,0,1000){Description="Domain value ranges from 0 to 1000"};SchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Create a range domain schemaBuilder.Create(rangeDomainDescriptionMinMax);schemaBuilder.Build();}
Creating a CodedValue domain
publicvoidCreateCodedDomainSnippet(Geodatabasegeodatabase){// Create a CodedValueDomain description for water pipesCodedValueDomainDescriptioncodedValueDomainDescription=newCodedValueDomainDescription("WaterPipeTypes",FieldType.String,newSortedList<object,string>{{"C_1","Copper"},{"S_2","Steel"}}){SplitPolicy=SplitPolicy.Duplicate,MergePolicy=MergePolicy.DefaultValue};SchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Create a coded value domain CodedValueDomainTokencodedValueDomainToken=schemaBuilder.Create(codedValueDomainDescription);schemaBuilder.Build();}
Creating a FeatureDataset
publicvoidCreateFeatureDatasetSnippet(Geodatabasegeodatabase){// Creating a FeatureDataset named as 'Parcel_Information'SchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Create a FeatureDataset named as 'Parcel Information'FeatureDatasetDescriptionfeatureDatasetDescription=newFeatureDatasetDescription("Parcel_Information",SpatialReferences.WGS84);schemaBuilder.Create(featureDatasetDescription);// Build statusboolbuildStatus=schemaBuilder.Build();// Build errorsif(!buildStatus){IReadOnlyList<string>errors=schemaBuilder.ErrorMessages;}}
Deleting a FeatureDataset
publicvoidDeleteFeatureDatasetSnippet(Geodatabasegeodatabase){// Deleting a FeatureDataset named as 'Parcel_Information'FeatureDatasetDefinitionfeatureDatasetDefinition=geodatabase.GetDefinition<FeatureDatasetDefinition>("Parcel_Information");FeatureDatasetDescriptionfeatureDatasetDescription=newFeatureDatasetDescription(featureDatasetDefinition);SchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Delete an existing feature dataset named as 'Parcel_Information'schemaBuilder.Delete(featureDatasetDescription);schemaBuilder.Build();}
Renaming a FeatureDataset
publicvoidRenameFeatureDatasetSnippet(Geodatabasegeodatabase){// Renaming a FeatureDataset from 'Parcel_Information' to 'Parcel_Information_With_Tax_Jurisdiction'stringoriginalDatasetName="Parcel_Information";stringdatasetRenameAs="Parcel_Information_With_Tax_Jurisdiction";FeatureDatasetDefinitionoriginalDatasetDefinition=geodatabase.GetDefinition<FeatureDatasetDefinition>(originalDatasetName);FeatureDatasetDescriptionoriginalFeatureDatasetDescription=newFeatureDatasetDescription(originalDatasetDefinition);SchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Rename the existing FeatureDataset, 'Parcel_Information' to 'Parcel_Information_With_Tax_Jurisdiction'schemaBuilder.Rename(originalFeatureDatasetDescription,datasetRenameAs);schemaBuilder.Build();}
Creating a FeatureDataset with a FeatureClass in one operation
publicvoidCreateFeatureDatasetWithFeatureClassSnippet(Geodatabasegeodatabase){// Creating a FeatureDataset named as 'Parcel_Information' and a FeatureClass with name 'Parcels' in one operationstringfeatureDatasetName="Parcel_Information";stringfeatureClassName="Parcels";SchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Create a FeatureDataset tokenFeatureDatasetDescriptionfeatureDatasetDescription=newFeatureDatasetDescription(featureDatasetName,SpatialReferences.WGS84);FeatureDatasetTokenfeatureDatasetToken=schemaBuilder.Create(featureDatasetDescription);// Create a FeatureClass descriptionFeatureClassDescriptionfeatureClassDescription=newFeatureClassDescription(featureClassName,newList<FieldDescription>(){newFieldDescription("Id",FieldType.Integer),newFieldDescription("Address",FieldType.String)},newShapeDescription(GeometryType.Point,SpatialReferences.WGS84));// Create a FeatureClass inside a FeatureDatasetFeatureClassTokenfeatureClassToken=schemaBuilder.Create(newFeatureDatasetDescription(featureDatasetToken),featureClassDescription);// Build statusboolbuildStatus=schemaBuilder.Build();// Build errorsif(!buildStatus){IReadOnlyList<string>errors=schemaBuilder.ErrorMessages;}}
Creating a FeatureClass in existing FeatureDataset
publicvoidCreateFeatureClassInsideFeatureDatasetSnippet(Geodatabasegeodatabase){// Creating a FeatureClass named as 'Tax_Jurisdiction' in existing FeatureDataset with name 'Parcels_Information'stringfeatureDatasetName="Parcels_Information";stringfeatureClassName="Tax_Jurisdiction";// Create a FeatureClass descriptionFeatureClassDescriptionfeatureClassDescription=newFeatureClassDescription(featureClassName,newList<FieldDescription>(){newFieldDescription("Tax_Id",FieldType.Integer),newFieldDescription("Address",FieldType.String)},newShapeDescription(GeometryType.Point,SpatialReferences.WGS84));FeatureDatasetDefinitionfeatureDatasetDefinition=geodatabase.GetDefinition<FeatureDatasetDefinition>(featureDatasetName);SchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Create a FeatureClass inside a FeatureDataset using a FeatureDatasetDefinitionschemaBuilder.Create(newFeatureDatasetDescription(featureDatasetDefinition),featureClassDescription);// Build statusboolbuildStatus=schemaBuilder.Build();// Build errorsif(!buildStatus){IReadOnlyList<string>errors=schemaBuilder.ErrorMessages;}}
Adding a FeatureClass to a FeatureDataset
publicvoidAddFeatureClassToFeatureDatasetSnippet(Geodatabasegeodatabase){// Adding a FeatureClass with name 'Tax_Jurisdiction' into a FeatureDataset named as 'Parcels_Information'stringfeatureDatasetName="Parcels_Information";stringfeatureClassNameToAdd="Tax_Jurisdiction";FeatureDatasetDefinitionfeatureDatasetDefinition=geodatabase.GetDefinition<FeatureDatasetDefinition>(featureDatasetName);FeatureDatasetDescriptionfeatureDatasetDescription=newFeatureDatasetDescription(featureDatasetDefinition);FeatureClassDefinitionfeatureClassDefinition=geodatabase.GetDefinition<FeatureClassDefinition>(featureClassNameToAdd);FeatureClassDescriptionfeatureClassDescription=newFeatureClassDescription(featureClassDefinition);SchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Add the 'Tax_Jurisdiction' FeatureClass to the 'Parcels_Information' FeatureDataset schemaBuilder.AddFeatureClass(featureDatasetDescription,featureClassDescription);booladdStatus=schemaBuilder.Build();if(!addStatus){IReadOnlyList<string>errors=schemaBuilder.ErrorMessages;}}
Renaming a Table
publicvoidRenameTableSnippet(Geodatabasegeodatabase){//Renaming a table from 'Original_Table' to 'Renamed_Table'stringtableToBeRenamed="Original_Table";stringtableRenameAs="Renamed_Table";TableDefinitiontableDefinition=geodatabase.GetDefinition<TableDefinition>(tableToBeRenamed);SchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Table rename schemaBuilder.Rename(newTableDescription(tableDefinition),tableRenameAs);schemaBuilder.Build();}
Adding fields to a FeatureClass
publicvoidAddFieldsInFeatureClassSnippet(Geodatabasegeodatabase){// Adding following fields to the 'Parcels' FeatureClass// Global ID// Parcel_ID// Tax_Code// Parcel_Address// The FeatureClass to add fieldsstringfeatureClassName="Parcels";FeatureClassDefinitionoriginalFeatureClassDefinition=geodatabase.GetDefinition<FeatureClassDefinition>(featureClassName);FeatureClassDescriptionoriginalFeatureClassDescription=newFeatureClassDescription(originalFeatureClassDefinition);// The four new fields to add on the 'Parcels' FeatureClassFieldDescriptionglobalIdField=FieldDescription.CreateGlobalIDField();FieldDescriptionparcelIdDescription=newFieldDescription("Parcel_ID",FieldType.GUID);FieldDescriptiontaxCodeDescription=FieldDescription.CreateIntegerField("Tax_Code");FieldDescriptionaddressDescription=FieldDescription.CreateStringField("Parcel_Address",150);List<FieldDescription>fieldsToAdd=newList<FieldDescription>{globalIdField,parcelIdDescription,taxCodeDescription,addressDescription};// Add new fields on the new FieldDescription listList<FieldDescription>modifiedFieldDescriptions=newList<FieldDescription>(originalFeatureClassDescription.FieldDescriptions);modifiedFieldDescriptions.AddRange(fieldsToAdd);// The new FeatureClassDescription with additional fieldsFeatureClassDescriptionmodifiedFeatureClassDescription=newFeatureClassDescription(originalFeatureClassDescription.Name,modifiedFieldDescriptions,originalFeatureClassDescription.ShapeDescription);SchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Update the 'Parcels' FeatureClass with newly added fieldsschemaBuilder.Modify(modifiedFeatureClassDescription);boolmodifyStatus=schemaBuilder.Build();if(!modifyStatus){IReadOnlyList<string>errors=schemaBuilder.ErrorMessages;}}
Adding a Field that uses a domain
publicvoidAddFieldWithDomainSnippet(Geodatabasegeodatabase){// Adding a field,'PipeType', which uses the coded value domain to the 'Pipes' FeatureClass//The FeatureClass to add fieldstringfeatureClassName="Pipes";SchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Create a CodedValueDomain description for water pipesCodedValueDomainDescriptionpipeDomainDescription=newCodedValueDomainDescription("WaterPipeTypes",FieldType.String,newSortedList<object,string>{{"C_1","Copper"},{"S_2","Steel"}}){SplitPolicy=SplitPolicy.Duplicate,MergePolicy=MergePolicy.DefaultValue};// Create a coded value domain tokenCodedValueDomainTokencodedValueDomainToken=schemaBuilder.Create(pipeDomainDescription);// Create a new description from domain tokenCodedValueDomainDescriptioncodedValueDomainDescription=newCodedValueDomainDescription(codedValueDomainToken);// Create a field named as 'PipeType' using a domain descriptionFieldDescriptiondomainFieldDescription=newFieldDescription("PipeType",FieldType.String);domainFieldDescription.SetDomainDescription(codedValueDomainDescription);//Retrieve existing information for 'Pipes' FeatureClassFeatureClassDefinitionoriginalFeatureClassDefinition=geodatabase.GetDefinition<FeatureClassDefinition>(featureClassName);FeatureClassDescriptionoriginalFeatureClassDescription=newFeatureClassDescription(originalFeatureClassDefinition);// Add domain field on existing fieldsList<FieldDescription>modifiedFieldDescriptions=newList<FieldDescription>(originalFeatureClassDescription.FieldDescriptions){domainFieldDescription};// Create a new description with updated fields for 'Pipes' FeatureClass FeatureClassDescriptionfeatureClassDescription=newFeatureClassDescription(originalFeatureClassDescription.Name,modifiedFieldDescriptions,originalFeatureClassDescription.ShapeDescription);// Update the 'Pipes' FeatureClass with domain fieldschemaBuilder.Modify(featureClassDescription);// Build statusboolbuildStatus=schemaBuilder.Build();// Build errorsif(!buildStatus){IReadOnlyList<string>errors=schemaBuilder.ErrorMessages;}}
Removing fields from a Table
publicvoidRemoveFieldTableSnippet(Geodatabasegeodatabase){// Removing all fields from 'Parcels' table except following // Tax_Code// Parcel_Address// The table to remove fieldsstringtableName="Parcels";TableDefinitiontableDefinition=geodatabase.GetDefinition<TableDefinition>(tableName);IReadOnlyList<Field>fields=tableDefinition.GetFields();// Existing fields from 'Parcels' tableFieldtaxCodeField=fields.First(f =>f.Name.Equals("Tax_Code"));FieldparcelAddressField=fields.First(f =>f.Name.Equals("Parcel_Address"));FieldDescriptiontaxFieldDescription=newFieldDescription(taxCodeField);FieldDescriptionparcelAddressFieldDescription=newFieldDescription(parcelAddressField);// Fields to retain in modified tableList<FieldDescription>fieldsToBeRetained=newList<FieldDescription>(){taxFieldDescription,parcelAddressFieldDescription};// New description of the 'Parcels' table with the 'Tax_Code' and 'Parcel_Address' fieldsTableDescriptionmodifiedTableDescription=newTableDescription(tableName,fieldsToBeRetained);SchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Remove all fields except the 'Tax_Code' and 'Parcel_Address' fieldsschemaBuilder.Modify(modifiedTableDescription);schemaBuilder.Build();}
Creating an annotation feature class
publicvoidCreateStandAloneAnnotationFeatureClass(Geodatabasegeodatabase,SpatialReferencespatialReference){// Creating a Cities annotation feature class// with following user defined fields// Name // GlobalID// Annotation feature class namestringannotationFeatureClassName="CitiesAnnotation";// Create user defined attribute fields for annotation feature class FieldDescriptionglobalIDFieldDescription=FieldDescription.CreateGlobalIDField();FieldDescriptionnameFieldDescription=FieldDescription.CreateStringField("Name",255);// Create a list of all field descriptionsList<FieldDescription>fieldDescriptions=newList<FieldDescription>{globalIDFieldDescription,nameFieldDescription};// Create a ShapeDescription objectShapeDescriptionshapeDescription=newShapeDescription(GeometryType.Polygon,spatialReference);// Create general placement properties for Maplex engine CIMMaplexGeneralPlacementPropertiesgeneralPlacementProperties=newCIMMaplexGeneralPlacementProperties{AllowBorderOverlap=true,PlacementQuality=MaplexQualityType.High,DrawUnplacedLabels=true,InvertedLabelTolerance=1.0,RotateLabelWithDisplay=true,UnplacedLabelColor=newCIMRGBColor{R=0,G=255,B=0,Alpha=0.5f// Green}};// Create general placement properties for Standard engine//CIMStandardGeneralPlacementProperties generalPlacementProperties =// new CIMStandardGeneralPlacementProperties// {// DrawUnplacedLabels = true,// InvertedLabelTolerance = 3.0,// RotateLabelWithDisplay = true,// UnplacedLabelColor = new CIMRGBColor// {// R = 255, G = 0, B = 0, Alpha = 0.5f // Red// } // };// Create annotation label classes// Green labelCIMLabelClassgreenLabelClass=newCIMLabelClass{Name="Green",ExpressionTitle="Expression-Green",ExpressionEngine=LabelExpressionEngine.Arcade,Expression="$feature.OBJECTID",ID=1,Priority=0,Visibility=true,TextSymbol=newCIMSymbolReference{Symbol=newCIMTextSymbol(){Angle=45,FontType=FontType.Type1,FontFamilyName="Tahoma",FontEffects=FontEffects.Normal,HaloSize=2.0,Symbol=newCIMPolygonSymbol{SymbolLayers=newCIMSymbolLayer[]{newCIMSolidFill{Color=CIMColor.CreateRGBColor(0,255,0)}},UseRealWorldSymbolSizes=true}},MaxScale=0,MinScale=0,SymbolName="TextSymbol-Green"},StandardLabelPlacementProperties=newCIMStandardLabelPlacementProperties{AllowOverlappingLabels=true,LineOffset=1.0},MaplexLabelPlacementProperties=newCIMMaplexLabelPlacementProperties{AlignLabelToLineDirection=true,AvoidPolygonHoles=true}};// Blue labelCIMLabelClassblueLabelClass=newCIMLabelClass{Name="Blue",ExpressionTitle="Expression-Blue",ExpressionEngine=LabelExpressionEngine.Arcade,Expression="$feature.OBJECTID",ID=2,Priority=0,Visibility=true,TextSymbol=newCIMSymbolReference{Symbol=newCIMTextSymbol(){Angle=45,FontType=FontType.Type1,FontFamilyName="Consolas",FontEffects=FontEffects.Normal,HaloSize=2.0,Symbol=newCIMPolygonSymbol{SymbolLayers=newCIMSymbolLayer[]{newCIMSolidFill{Color=CIMColor.CreateRGBColor(0,0,255)}},UseRealWorldSymbolSizes=true}},MaxScale=0,MinScale=0,SymbolName="TextSymbol-Blue"},StandardLabelPlacementProperties=newCIMStandardLabelPlacementProperties{AllowOverlappingLabels=true,LineOffset=1.0},MaplexLabelPlacementProperties=newCIMMaplexLabelPlacementProperties{AlignLabelToLineDirection=true,AvoidPolygonHoles=true}};// Create a list of labelsList<CIMLabelClass>labelClasses=newList<CIMLabelClass>{greenLabelClass,blueLabelClass};// Create an annotation feature class description object to describe the feature class to createAnnotationFeatureClassDescriptionannotationFeatureClassDescription=newAnnotationFeatureClassDescription(annotationFeatureClassName,fieldDescriptions,shapeDescription,generalPlacementProperties,labelClasses){IsAutoCreate=true,IsSymbolIDRequired=false,IsUpdatedOnShapeChange=true};// Create a SchemaBuilder objectSchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Add the creation of the Cities annotation feature class to the list of DDL tasksschemaBuilder.Create(annotationFeatureClassDescription);// Execute the DDLboolsuccess=schemaBuilder.Build();// Inspect error messagesif(!success){IReadOnlyList<string>errorMessages=schemaBuilder.ErrorMessages;//etc.}}
Creating a feature-linked annotation feature class
publicvoidCreateFeatureLinkedAnnotationFeatureClass(Geodatabasegeodatabase,SpatialReferencespatialReference){// Creating a feature-linked annotation feature class between water pipe and valve in water distribution network// with following user defined fields// PipeName // GlobalID// Annotation feature class namestringannotationFeatureClassName="WaterPipeAnnotation";// Create user defined attribute fields for annotation feature classFieldDescriptionpipeGlobalID=FieldDescription.CreateGlobalIDField();FieldDescriptionnameFieldDescription=FieldDescription.CreateStringField("Name",255);// Create a list of all field descriptionsList<FieldDescription>fieldDescriptions=newList<FieldDescription>{pipeGlobalID,nameFieldDescription};// Create a ShapeDescription objectShapeDescriptionshapeDescription=newShapeDescription(GeometryType.Polygon,spatialReference);// Create general placement properties for Maplex engine CIMMaplexGeneralPlacementPropertiesgeneralPlacementProperties=newCIMMaplexGeneralPlacementProperties{AllowBorderOverlap=true,PlacementQuality=MaplexQualityType.High,DrawUnplacedLabels=true,InvertedLabelTolerance=1.0,RotateLabelWithDisplay=true,UnplacedLabelColor=newCIMRGBColor{R=255,G=0,B=0,Alpha=0.5f}};// Create annotation label classes// Green labelCIMLabelClassgreenLabelClass=newCIMLabelClass{Name="Green",ExpressionTitle="Expression-Green",ExpressionEngine=LabelExpressionEngine.Arcade,Expression="$feature.OBJECTID",ID=1,Priority=0,Visibility=true,TextSymbol=newCIMSymbolReference{Symbol=newCIMTextSymbol(){Angle=45,FontType=FontType.Type1,FontFamilyName="Tahoma",FontEffects=FontEffects.Normal,HaloSize=2.0,Symbol=newCIMPolygonSymbol{SymbolLayers=newCIMSymbolLayer[]{newCIMSolidFill{Color=CIMColor.CreateRGBColor(0,255,0)}},UseRealWorldSymbolSizes=true}},MaxScale=0,MinScale=0,SymbolName="TextSymbol-Green"},StandardLabelPlacementProperties=newCIMStandardLabelPlacementProperties{AllowOverlappingLabels=true,LineOffset=1.0},MaplexLabelPlacementProperties=newCIMMaplexLabelPlacementProperties{AlignLabelToLineDirection=true,AvoidPolygonHoles=true}};// Blue labelCIMLabelClassblueLabelClass=newCIMLabelClass{Name="Blue",ExpressionTitle="Expression-Blue",ExpressionEngine=LabelExpressionEngine.Arcade,Expression="$feature.OBJECTID",ID=2,Priority=0,Visibility=true,TextSymbol=newCIMSymbolReference{Symbol=newCIMTextSymbol(){Angle=45,FontType=FontType.Type1,FontFamilyName="Consolas",FontEffects=FontEffects.Normal,HaloSize=2.0,Symbol=newCIMPolygonSymbol{SymbolLayers=newCIMSymbolLayer[]{newCIMSolidFill{Color=CIMColor.CreateRGBColor(0,0,255)}},UseRealWorldSymbolSizes=true}},MaxScale=0,MinScale=0,SymbolName="TextSymbol-Blue"},StandardLabelPlacementProperties=newCIMStandardLabelPlacementProperties{AllowOverlappingLabels=true,LineOffset=1.0},MaplexLabelPlacementProperties=newCIMMaplexLabelPlacementProperties{AlignLabelToLineDirection=true,AvoidPolygonHoles=true}};// Create a list of labelsList<CIMLabelClass>labelClasses=newList<CIMLabelClass>{greenLabelClass,blueLabelClass};// Create linked feature description// Linked feature class namestringlinkedFeatureClassName="WaterPipe";// Create fields for water pipeFieldDescriptionwaterPipeGlobalID=FieldDescription.CreateGlobalIDField();FieldDescriptionpipeName=FieldDescription.CreateStringField("PipeName",255);// Create a list of water pipe field descriptionsList<FieldDescription>pipeFieldDescriptions=newList<FieldDescription>{waterPipeGlobalID,pipeName};// Create a linked feature class descriptionFeatureClassDescriptionlinkedFeatureClassDescription=newFeatureClassDescription(linkedFeatureClassName,pipeFieldDescriptions,newShapeDescription(GeometryType.Polyline,spatialReference));// Create a SchemaBuilder objectSchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Add the creation of the linked feature class to the list of DDL tasksFeatureClassTokenlinkedFeatureClassToken=schemaBuilder.Create(linkedFeatureClassDescription);// Create an annotation feature class description object to describe the feature class to createAnnotationFeatureClassDescriptionannotationFeatureClassDescription=newAnnotationFeatureClassDescription(annotationFeatureClassName,fieldDescriptions,shapeDescription,generalPlacementProperties,labelClasses,newFeatureClassDescription(linkedFeatureClassToken)){IsAutoCreate=true,IsSymbolIDRequired=false,IsUpdatedOnShapeChange=true};// Add the creation of the annotation feature class to the list of DDL tasksschemaBuilder.Create(annotationFeatureClassDescription);// Execute the DDLboolsuccess=schemaBuilder.Build();// Inspect error messagesif(!success){IReadOnlyList<string>errorMessages=schemaBuilder.ErrorMessages;//etc.}}
Creating an annotation feature class inside feature dataset
publicvoidCreateAnnotationFeatureClassUsingExistingAnnotationFeatureClassInDataset(Geodatabasegeodatabase){// Create a Cities annotation feature class inside Places feature dataset using existing annotation feature class // Feature dataset namestringfeatureDatasetName="Places";// Annotation feature class namestringannotationFeatureClassName="CitiesAnnotation";// Create a SchemaBuilder objectSchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);// Open existing annotation feature class nameusing(AnnotationFeatureClassexistingAnnotationFeatureClass=geodatabase.OpenDataset<AnnotationFeatureClass>("ExistingAnnotationFeatureClass")){// Create Feature dataset descriptionFeatureDatasetDescriptionfeatureDatasetDescription=newFeatureDatasetDescription(featureDatasetName,existingAnnotationFeatureClass.GetDefinition().GetSpatialReference());// Add the creation of the Places dataset to DDL taskFeatureDatasetTokenfeatureDatasetToken=schemaBuilder.Create(featureDatasetDescription);// Create an annotation feature class description using existing annotation feature classAnnotationFeatureClassDescriptionannotationFeatureClassDescription=newAnnotationFeatureClassDescription(annotationFeatureClassName,existingAnnotationFeatureClass.GetDefinition()){IsAutoCreate=true,IsSymbolIDRequired=false,IsUpdatedOnShapeChange=true};// Add the creation of the Cities annotation feature class inside Places feature datasetschemaBuilder.Create(newFeatureDatasetDescription(featureDatasetToken),annotationFeatureClassDescription);// Execute the DDLboolsuccess=schemaBuilder.Build();// Inspect error messagesif(!success){IReadOnlyList<string>errorMessages=schemaBuilder.ErrorMessages;//etc.}}}
Creating the memory geodatabase
publicGeodatabaseGetMemoryGeodatabase(){// Creates the default memory geodatabase if not exist or connects to an existing one if already existsGeodatabasememoryGeodatabase=newGeodatabase(newMemoryConnectionProperties());// Creates schemaSchemaBuilderschemaBuilder=newSchemaBuilder(memoryGeodatabase);schemaBuilder.Create(newTableDescription("MyTable",newList<FieldDescription>()));schemaBuilder.Build();returnmemoryGeodatabase;}
Spatial query filter with DE9-IM spatial relationships
publicvoidFindSpatiallyRelatedFeaturesUsingDE9IMPredicate(Geodatabasegeodatabase,FeatureClasspolygonFeatureClass,FeatureClasspolylineFeatureClass){using(RowCursorpolygonRowCursor=polygonFeatureClass.Search(newQueryFilter())){if(polygonRowCursor.MoveNext()){using(FeaturepolygonFeature=polygonRowCursor.CurrentasFeature){// DE9IM predicate string to find overlapping featuresstringoverlappingDE9IM="1*T***T**";SpatialQueryFilterspatialQueryFilter=newSpatialQueryFilter(){FilterGeometry=polygonFeature.GetShape(),SpatialRelationship=SpatialRelationship.Relation,SpatialRelationshipDescription=overlappingDE9IM};using(RowCursoroverlappingPolyline=polylineFeatureClass.Search(spatialQueryFilter)){while(overlappingPolyline.MoveNext()){// Overlapping polylines on the polygon}}}}}}
Check if table is versioned
publicboolIsTableVersioned(Geodatabasegeodatabase,stringtableName){using(Tabletable=geodatabase.OpenDataset<Table>(tableName)){// Check table version typeRegistrationTyperegistrationType=table.GetRegistrationType();if(registrationType==RegistrationType.Versioned){returntrue;}}returnfalse;}
Creating a table with index from scratch
publicvoidCreatingTableWithIndex(SchemaBuilderschemaBuilder){FieldDescriptionnameFieldDescription=FieldDescription.CreateStringField("Name",50);FieldDescriptionaddressFieldDescription=FieldDescription.CreateStringField("Address",200);// Creating a feature class, 'Buildings' with two fieldsTableDescriptiontableDescription=newTableDescription("Buildings",newList<FieldDescription>(){nameFieldDescription,addressFieldDescription});// Enqueue DDL operation to create a tableTableTokentableToken=schemaBuilder.Create(tableDescription);// Creating an attribute index named as 'Idx'AttributeIndexDescriptionattributeIndexDescription=newAttributeIndexDescription("Idx",newTableDescription(tableToken),newList<string>{nameFieldDescription.Name,addressFieldDescription.Name});// Enqueue DDL operation to create an attribute indexschemaBuilder.Create(attributeIndexDescription);// Execute build indexes operationboolisBuildSuccess=schemaBuilder.Build();}
Adding indexes in pre-existing dataset
publicvoidAddingIndexes(SchemaBuilderschemaBuilder,FeatureClassDefinitionfeatureClassDefinition){// Field names to add in the attribute indexstringfieldName=featureClassDefinition.GetFields().First(f =>f.AliasName.Contains("Name")).Name;stringfieldAddress=featureClassDefinition.GetFields().First(f =>f.AliasName.Contains("Address")).Name;// Creating an attribute index with index name 'Idx' and two participating fields' nameAttributeIndexDescriptionattributeIndexDescription=newAttributeIndexDescription("Idx",newTableDescription(featureClassDefinition),newList<string>{fieldName,fieldAddress});// Enqueue DDL operation for an attribute index creation schemaBuilder.Create(attributeIndexDescription);// Creating the spatial index SpatialIndexDescriptionspatialIndexDescription=newSpatialIndexDescription(newFeatureClassDescription(featureClassDefinition));// Enqueue DDL operation for the spatial index creationschemaBuilder.Create(spatialIndexDescription);// Execute build indexes operationboolisBuildSuccess=schemaBuilder.Build();if(!isBuildSuccess){IReadOnlyList<string>errors=schemaBuilder.ErrorMessages;// Iterate and handle errors }}
Removing attribute index
publicvoidRemoveAttributeIndex(SchemaBuilderschemaBuilder,FeatureClassDefinitionfeatureClassDefinition,stringattributeIndexName){// Find a index to be removed ArcGIS.Core.Data.IndexindexToRemove=featureClassDefinition.GetIndexes().First(f =>f.GetName().Equals(attributeIndexName));// Index description of the index to be removed AttributeIndexDescriptionindexDescriptionToRemove=newAttributeIndexDescription(indexToRemove,newTableDescription(featureClassDefinition));// Enqueue the DDL operation to remove index schemaBuilder.Delete(indexDescriptionToRemove);// Execute the delete index operationboolisDeleteIndexSuccess=schemaBuilder.Build();}
Removing spatial index
publicvoidRemoveSpatialIndex(SchemaBuilderschemaBuilder,FeatureClassDefinitionfeatureClassDefinition){// Create a spatial description SpatialIndexDescriptionspatialIndexDescription=newSpatialIndexDescription(newFeatureClassDescription(featureClassDefinition));// Enqueue the DDL operation to remove index schemaBuilder.Delete(spatialIndexDescription);// Execute the delete index operationboolisDeleteIndexSuccess=schemaBuilder.Build();}
Modifying domain
publicvoidModifyDomain(Geodatabasegeodatabase,stringcodedValueDomainName="Pipe"){SchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);CodedValueDomaincodedValueDomain=geodatabase.GetDomains().First(f =>f.GetName().Equals(codedValueDomainName))asCodedValueDomain;CodedValueDomainDescriptioncodedValueDomainDescription=newCodedValueDomainDescription(codedValueDomain);// Update domain descriptioncodedValueDomainDescription.Description="Water Pipe Domain";// Adding code/value paircodedValueDomainDescription.CodedValuePairs.Add("C","Copper");schemaBuilder.Modify(codedValueDomainDescription);// To modify the orders of coded value domain// schemaBuilder.Modify(codedValueDomainDescription,SortBy.Name,SortOrder.Ascending);schemaBuilder.Build();}
Rename domain
publicvoidRenameDomain(Geodatabasegeodatabase,stringrangeDomainOldName="PipeDiameter",stringrangeDomainNewName="PipeDiam"){SchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);RangeDomainrangeDomain=geodatabase.GetDomains().First(f =>f.GetName().Equals(rangeDomainOldName))asRangeDomain;// Renaming a domainschemaBuilder.Rename(newRangeDomainDescription(rangeDomain),rangeDomainNewName);schemaBuilder.Build();}
Delete domain
publicvoidDeleteDomain(Geodatabasegeodatabase,stringdomainNameToBeDeleted="PipeMaterial"){SchemaBuilderschemaBuilder=newSchemaBuilder(geodatabase);CodedValueDomaincodedValueDomain=geodatabase.GetDomains().First(f =>f.GetName().Equals(domainNameToBeDeleted))asCodedValueDomain;CodedValueDomainDescriptioncodedValueDomainDescription=newCodedValueDomainDescription(codedValueDomain);// Deleting a coded value domainschemaBuilder.Delete(codedValueDomainDescription);schemaBuilder.Build();}
Creating table with subtypes
publicvoidCreateTableWithSubtypes(SchemaBuilderschemaBuilder){// Creating a 'Building' table with the subtype field 'BuildingType'FieldDescriptionbuildingType=newFieldDescription("BuildingType",FieldType.Integer);FieldDescriptionbuildingName=newFieldDescription("Name",FieldType.String);TableDescriptiontableDescription=newTableDescription("Building",newList<FieldDescription>{buildingName,buildingType});// Add the building type subtype with three subtypes - Business, Marketing, SecuritytableDescription.SubtypeFieldDescription=newSubtypeFieldDescription(buildingType.Name,newDictionary<int,string>{{1,"Business"},{2,"Marketing"},{3,"Security"}}){DefaultSubtypeCode=3// Assigning 'Security' building type as the default subtype};schemaBuilder.Create(tableDescription);schemaBuilder.Build();}
Removing subtype field designation
publicvoidDeleteSubtypeField(SchemaBuilderschemaBuilder,FeatureClassDefinitionfeatureClassDefinition){FeatureClassDescriptionfeatureClassDescription=newFeatureClassDescription(featureClassDefinition);// Set subtype field to null to remove the subtype field designation featureClassDescription.SubtypeFieldDescription=null;schemaBuilder.Modify(featureClassDescription);schemaBuilder.Build();}
Modifying subtypes
publicvoidModifySubtypes(SchemaBuilderschemaBuilder,TableDefinitiontableDefinition){TableDescriptiontableDescription=newTableDescription(tableDefinition);// Remove the first subtype from the tableIReadOnlyList<Subtype>subtypes=tableDefinition.GetSubtypes();tableDescription.SubtypeFieldDescription.Subtypes.Remove(subtypes.First().GetCode());// Adding a new subtype, 'Utility', in the existing tabletableDescription.SubtypeFieldDescription.Subtypes.Add(4,"Utility");// Assigning 'Utility' subtype as the default subtypetableDescription.SubtypeFieldDescription.DefaultSubtypeCode=4;schemaBuilder.Modify(tableDescription);schemaBuilder.Build();}
Creating relationship class
publicvoidCreateRelationshipWithRelationshipRules(SchemaBuilderschemaBuilder){// Creating a 'BuildingType' table with two fields - BuildingType and BuildingTypeDescriptionFieldDescriptionbuildingType=FieldDescription.CreateIntegerField("BuildingType");FieldDescriptionbuildingTypeeDescription=FieldDescription.CreateStringField("BuildingTypeDescription",100);TableDescriptionbuildingTypeDescription=newTableDescription("BuildingType",newList<FieldDescription>(){buildingType,buildingTypeeDescription});TableTokenbuildingtypeToken=schemaBuilder.Create(buildingTypeDescription);// Creating a 'Building' feature class with three fields - BuildingId, Address, and BuildingTypeFieldDescriptionbuildingId=FieldDescription.CreateIntegerField("BuildingId");FieldDescriptionbuildingAddress=FieldDescription.CreateStringField("Address",100);FieldDescriptionusageSubType=FieldDescription.CreateIntegerField("UsageSubtype");FeatureClassDescriptionfeatureClassDescription=newFeatureClassDescription("Building",newList<FieldDescription>{buildingId,buildingAddress,buildingType,usageSubType},newShapeDescription(GeometryType.Polygon,SpatialReferences.WGS84));// Set subtype details (optional)featureClassDescription.SubtypeFieldDescription=newSubtypeFieldDescription(usageSubType.Name,newDictionary<int,string>{{1,"Marketing"},{2,"Utility"}});FeatureClassTokenbuildingToken=schemaBuilder.Create(featureClassDescription);// Creating a 1:M relationship between the 'Building' feature class and 'BuildingType' tableRelationshipClassDescriptionrelationshipClassDescription=newRelationshipClassDescription("BuildingToBuildingType",newFeatureClassDescription(buildingToken),newTableDescription(buildingtypeToken),RelationshipCardinality.OneToMany,buildingType.Name,buildingType.Name){RelationshipType=RelationshipType.Composite};// Adding relationship rules for the 'Marketing' subtyperelationshipClassDescription.RelationshipRuleDescriptions.Add(newRelationshipRuleDescription(1,null));schemaBuilder.Create(relationshipClassDescription);schemaBuilder.Build();}
Creating attributed relationship class
publicvoidCreateAttributedRelationship(SchemaBuilderschemaBuilder){// Creating a 'BuildingType' table with two fields - BuildingType and BuildingTypeDescriptionFieldDescriptionbuildingType=FieldDescription.CreateIntegerField("BuildingType");FieldDescriptionbuildingTypeeDescription=FieldDescription.CreateStringField("BuildingTypeDescription",100);TableDescriptionbuildingTypeDescription=newTableDescription("BuildingType",newList<FieldDescription>(){buildingType,buildingTypeeDescription});TableTokenbuildingtypeToken=schemaBuilder.Create(buildingTypeDescription);// Creating a 'Building' feature class with three fields - BuildingId, Address, and BuildingTypeFieldDescriptionbuildingId=FieldDescription.CreateIntegerField("BuildingId");FieldDescriptionbuildingAddress=FieldDescription.CreateStringField("Address",100);FeatureClassDescriptionfeatureClassDescription=newFeatureClassDescription("Building",newList<FieldDescription>{buildingId,buildingAddress,buildingType},newShapeDescription(GeometryType.Polygon,SpatialReferences.WGS84));FeatureClassTokenbuildingToken=schemaBuilder.Create(featureClassDescription);// Creating M:M relationship between the 'Building' feature class and 'BuildingType' tableAttributedRelationshipClassDescriptionattributedRelationshipClassDescription=newAttributedRelationshipClassDescription("BuildingToBuildingType",newFeatureClassDescription(buildingToken),newTableDescription(buildingtypeToken),RelationshipCardinality.ManyToMany,"OBJECTID","BuildingID","OBJECTID","BuildingTypeID");// Adding optional attribute field in the intermediate table - 'OwnershipPercentage' fieldattributedRelationshipClassDescription.FieldDescriptions.Add(FieldDescription.CreateIntegerField("OwnershipPercentage"));schemaBuilder.Create(attributedRelationshipClassDescription);schemaBuilder.Build();}
Add relationship rules to a relationship class
publicvoidModifyRelationshipClass(SchemaBuilderschemaBuilder,AttributedRelationshipClassDefinitionattributedRelationshipClassDefinition){AttributedRelationshipClassDescriptionattributedRelationshipClassDescription=newAttributedRelationshipClassDescription(attributedRelationshipClassDefinition);// Update the relationship split policyattributedRelationshipClassDescription.RelationshipSplitPolicy=RelationshipSplitPolicy.UseDefault;// Add field in the intermediate tableattributedRelationshipClassDescription.FieldDescriptions.Add(FieldDescription.CreateIntegerField("RelationshipStatus"));// Add relationship rules based on subtypes,if available// Assuming origin class has subtype with code 1attributedRelationshipClassDescription.RelationshipRuleDescriptions.Add(newRelationshipRuleDescription(1,null));// Enqueue modify operationschemaBuilder.Modify(attributedRelationshipClassDescription);// Execute modify DDL operationschemaBuilder.Build();}
Adding/Removing Relationship class in/out of a feature dataset
publicvoidMoveRelationshipClass(SchemaBuilderschemaBuilder,FeatureDatasetDefinitionfeatureDatasetDefinition,RelationshipClassDefinitionrelationshipClassDefinition){FeatureDatasetDescriptionfeatureDatasetDescription=newFeatureDatasetDescription(featureDatasetDefinition);RelationshipClassDescriptionrelationshipClassDescription=newRelationshipClassDescription(relationshipClassDefinition);// Remove relationship class from the feature datasetschemaBuilder.RemoveRelationshipClass(featureDatasetDescription,relationshipClassDescription);// Add relationship class inside the feature dataset// schemaBuilder.AddRelationshipClass(featureDatasetDescription, relationshipClassDescription);schemaBuilder.Build();}
Modifying annotation labels and symbols
publicvoidModifyAnnotationLabelAndSymbols(SchemaBuilderschemaBuilder,AnnotationFeatureClassDefinitionannotationFeatureClassDefinition){AnnotationFeatureClassDescriptionannotationFeatureClassDescription=newAnnotationFeatureClassDescription(annotationFeatureClassDefinition);IReadOnlyList<CIMLabelClass>labelClasses=annotationFeatureClassDescription.LabelClasses;// Adding a new annotation label class List<CIMLabelClass>modifiedLabelClasses=newList<CIMLabelClass>(labelClasses);modifiedLabelClasses.Add(newCIMLabelClass(){Name="RedSymbol",TextSymbol=newCIMSymbolReference{Symbol=newCIMTextSymbol(){Angle=45,FontType=FontType.Type1,FontFamilyName="Arial",FontEffects=FontEffects.Normal,HaloSize=2.0,Symbol=newCIMPolygonSymbol{SymbolLayers=newCIMSymbolLayer[]{newCIMSolidFill{Color=CIMColor.CreateRGBColor(255,0,0)}},UseRealWorldSymbolSizes=true}},MaxScale=0,MinScale=0,SymbolName="TextSymbol-RED"},});// Adding a new symbolannotationFeatureClassDescription.Symbols.Add(newCIMSymbolIdentifier(){ID=1001,Name="ID_10001",Symbol=newCIMTextSymbol(){Angle=43,FontEffects=FontEffects.Subscript,FontType=FontType.TTOpenType,FontStyleName="Regular",FontFamilyName="Tahoma",TextCase=TextCase.Allcaps}});// Modify annotation feature class AnnotationFeatureClassDescriptionmodifiedAnnotationFeatureClassDescription=newAnnotationFeatureClassDescription(annotationFeatureClassDescription.Name,annotationFeatureClassDescription.FieldDescriptions,annotationFeatureClassDescription.ShapeDescription,annotationFeatureClassDescription.GeneralPlacementProperties,modifiedLabelClasses);// Enqueue modifyschemaBuilder.Modify(modifiedAnnotationFeatureClassDescription);// DDL executeschemaBuilder.Build();}
privatevoidModifyExistingField(SchemaBuilderschemaBuilder,TableDefinitiontableDefinition,stringfieldNameToBeModified="PropertyAddress"){Fieldfield=tableDefinition.GetFields().FirstOrDefault(f =>f.Name.Contains(fieldNameToBeModified));// Update field's alias name and lengthFieldDescriptionfieldDescription=newFieldDescription(field){AliasName="Physical Property Address",Length=50};// Update the default valuefieldDescription.SetDefaultValue("123 Main St");// Enqueue modify operationschemaBuilder.Modify(newTableDescription(tableDefinition),field.Name,fieldDescription);// Execute DDLschemaBuilder.Build();}