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.OpenRelationshipClass(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(varrelationshipClassDefintioninrelationshipClassDefinitions){IReadOnlyList<Definition>definitions=geodatabase.GetRelatedDefinitions(relationshipClassDefintion,DefinitionRelationshipType.DatasetsRelatedThrough);foreach(vardefinitionindefinitions){MessageBox.Show($"Feature class in the RelationshipClass is:{definition.GetName()}");}}}});}
Opening a FeatureClass from a ShapeFile Datastore
publicasyncTaskOpenShapefileFeatureClass(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{varfileConnection=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");}});}
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=newPolygonBuilder(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=newPolygonBuilder(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()vartable=featureLayer.GetTable();varcount=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 & 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
varval=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 rowvarvarSubtypeCode=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();}}}
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 ~yet~EditOperationeditOperation=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()]=newPolygonBuilder(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(newPolygonBuilder(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);}
Obtaining a memory stream to modify or create Attachment data
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();}});}}
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 objectReconcileDescriptionreconcileDescription=newReconcileDescription(parentVersion);reconcileDescription.ConflictResolutionMethod=ConflictResolutionMethod.Continue;// continue if conflicts are foundreconcileDescription.WithPost=true;// Reconcile and postReconcileResultreconcileResult=currentVersion.Reconcile(reconcileDescription);// ReconcileResult.HasConflicts can be checked as-needed}}}
Working with Versions
publicasyncTaskWorkingWithVersions(){awaitArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri("path\\to\\sde\\file"))))using(VersionManagerversionManager=geodatabase.GetVersionManager()){IReadOnlyList<Version>versionList=versionManager.GetVersions();//The default version will have a null ParentVersiondefaultVersion=versionList.First(version =>version.GetParent()==null);IEnumerable<Version>publicVersions=versionList.Where(version =>version.GetAccessType()==VersionAccessType.Public);VersionqaVersion=defaultVersion.GetChildren().First(version =>version.GetName().Contains("QA"));GeodatabaseqaVersionGeodatabase=qaVersion.Connect();FeatureClasscurrentFeatureClass=geodatabase.OpenDataset<FeatureClass>("featureClassName");FeatureClassqaFeatureClass=qaVersionGeodatabase.OpenDataset<FeatureClass>("featureClassName");}});}
Working with the Default Version
// 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;}}
// 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 postReconcileDescriptionreconcileDescription=newReconcileDescription();reconcileDescription.ConflictDetectionType=ConflictDetectionType.ByColumn;reconcileDescription.ConflictResolutionMethod=ConflictResolutionMethod.Continue;reconcileDescription.ConflictResolutionType=ConflictResolutionType.FavorEditVersion;reconcileDescription.PartialPostSelections=newList<Selection>(){constructedSupportStructures,deletedSupportStructures};reconcileDescription.WithPost=true;ReconcileResultreconcileResult=designVersion.Reconcile(reconcileDescription);}}
DDL
Creating a Table
// Geodatabase DDL is pre-release for Pro 2.7. See https://github.com/esri/arcgis-pro-sdk/wiki/ProConcepts-DDL for more information// 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
// Geodatabase DDL is pre-release for Pro 2.7. See https://github.com/esri/arcgis-pro-sdk/wiki/ProConcepts-DDL for more information// 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);// Alternately, ShapeDescriptions can be created from another feature class. In this case, the new feature class will inherit the same shape properties of the existing classShapeDescriptionalternateShapeDescription=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
// 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
// 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();
Creating a File Geodatabase
// 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
// 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);