publicasync Task OpenFileGDB(){try{await ArcGIS.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=new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb")))){// Use the geodatabase.}});}catch(GeodatabaseNotFoundOrOpenedExceptionexception){// Handle Exception.}}
Opening an Enterprise Geodatabase using connection properties
publicasync Task OpenEnterpriseGeodatabase(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{// Opening a Non-Versioned SQL Server instance.DatabaseConnectionPropertiesconnectionProperties=new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer){AuthenticationMode= AuthenticationMode.DBMS,// Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance.Instance=@"testMachine\testInstance",// Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database.Database="LocalGovernment",// Provided that a login called gdb has been created and corresponding schema has been created with the required permissions.User="gdb",Password="password",Version="dbo.DEFAULT"};using(Geodatabasegeodatabase=new Geodatabase(connectionProperties)){// Use the geodatabase}});}
Opening an Enterprise Geodatabase using sde file path
publicasync Task OpenEnterpriseGeodatabaseUsingSDEFilePath(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde")))){// Use the geodatabase.}});}
Obtaining Geodatabase from Project Item
publicasync Task ObtainingGeodatabaseFromProjectItem(){IEnumerable<GDBProjectItem>gdbProjectItems= Project.Current.GetItems<GDBProjectItem>();await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{foreach(GDBProjectItem gdbProjectItem in gdbProjectItems){using(Datastoredatastore= gdbProjectItem.GetDatastore()){//Unsupported datastores (non File GDB and non Enterprise GDB) will be of type UnknownDatastoreif(datastore is UnknownDatastore)continue;Geodatabasegeodatabase= datastore as Geodatabase;// Use the geodatabase.}}});}
Getting Database Connection Properties from a Connection File
DatabaseConnectionFileconnectionFile=new DatabaseConnectionFile(new Uri("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
Obtaining Geodatabase from FeatureLayer
publicasync Task ObtainingGeodatabaseFromFeatureLayer(){IEnumerable<Layer>layers= MapView.Active.Map.Layers.Where(layer => layer is FeatureLayer);await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{foreach(FeatureLayer featureLayer in layers){using(Tabletable= featureLayer.GetTable())using(Datastoredatastore= table.GetDatastore()){if(datastore is UnknownDatastore)continue;Geodatabasegeodatabase= datastore as Geodatabase;}}});}
Executing SQL Statements
// 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
publicasync Task ObtainingDefinitionFromGeodatabase(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("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");}});}
publicasync Task ObtainingRelatedDefinitionsFromGeodatabase(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("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"))as FeatureClassDefinition;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"))as FeatureClassDefinition;RelationshipClassDefinitionaddressPointHasSiteAddressInAddressDataset= datasetsInAddressDataset.First(defn => defn.GetName().Equals("LocalGovernment.GDB.AddressPointHasSiteAddresses"))as RelationshipClassDefinition;}});}
Getting a Table Definition from a Layer
// GetDefinitionFromLayer - This code works even if the layer has a join to another tableprivate TableDefinition GetDefinitionFromLayer(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 tablereturn originTable.GetDefinition();}else{return featureClass.GetDefinition();}}
Datasets
Opening datasets from Geodatabase
publicasync Task OpeningDatasetsFromGeodatabase(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("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= featureClassAsTable as FeatureClass;}// 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){return geodatabase.OpenRelationshipClass(originClass, destinationClass);}
Obtaining related Feature Classes from a Relationship Class
publicasync Task GetFeatureClassesInRelationshipClassAsync(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb")))){IReadOnlyList<RelationshipClassDefinition>relationshipClassDefinitions= geodatabase.GetDefinitions<RelationshipClassDefinition>();foreach(var relationshipClassDefintion in relationshipClassDefinitions){IReadOnlyList<Definition>definitions= geodatabase.GetRelatedDefinitions(relationshipClassDefintion, DefinitionRelationshipType.DatasetsRelatedThrough);foreach(var definition in definitions){ MessageBox.Show($"Feature class in the RelationshipClass is:{definition.GetName()}");}}}});}
Opening a FeatureClass from a ShapeFile Datastore
publicasync Task OpenShapefileFeatureClass(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{varfileConnection=new FileSystemConnectionPath(new Uri("path\\to\\folder\\containing\\shapefiles"), FileSystemDatastoreType.Shapefile);using(FileSystemDatastoreshapefile=new FileSystemDatastore(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
publicasync Task SearchingATable(){try{await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))using(Tabletable= geodatabase.OpenDataset<Table>("EmployeeInfo")){QueryFilterqueryFilter=new QueryFilter{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=new Geodatabase(new DatabaseConnectionFile(new Uri("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=new QueryFilter(){WhereClause="颜色 = "+nationalStringPrefix+"'绿'"};}
Searching a Table using a set of ObjectIDs
public RowCursor SearchingATable(Tabletable,IReadOnlyList<long>objectIDs){QueryFilterqueryFilter=new QueryFilter(){ObjectIDs=objectIDs};return table.Search(queryFilter);}
Searching a FeatureClass using SpatialQueryFilter
publicasync Task SearchingAFeatureClass(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("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=new SpatialQueryFilter{WhereClause="DISTRCTNAME = 'Indian Prairie School District 204'",FilterGeometry=new PolygonBuilder(newList<Coordinate2D>{new Coordinate2D(1021880,1867396),new Coordinate2D(1028223,1870705),new Coordinate2D(1031165,1866844),new Coordinate2D(1025373,1860501),new Coordinate2D(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
publicasync Task SelectingRowsFromATable(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))using(TableenterpriseTable= geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost")){QueryFilteranotherQueryFilter=new QueryFilter {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
publicasync Task SelectingFeaturesFromAFeatureClass(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))using(FeatureClassenterpriseFeatureClass= geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite")){List<Coordinate2D>newCoordinates=newList<Coordinate2D>{new Coordinate2D(1021570,1880583),new Coordinate2D(1028730,1880994),new Coordinate2D(1029718,1875644),new Coordinate2D(1021405,1875397)};SpatialQueryFilterspatialFilter=new SpatialQueryFilter{WhereClause="FCODE = 'Park'",FilterGeometry=new PolygonBuilder(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();
public RowCursor SortWorldCities(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=new SortDescription(countryField);
countrySortDescription.CaseSensitivity = CaseSensitivity.Insensitive;
countrySortDescription.SortOrder = SortOrder.Ascending;// Create SortDescription for City fieldSortDescriptioncitySortDescription=new SortDescription(cityNameField);
citySortDescription.CaseSensitivity = CaseSensitivity.Insensitive;
citySortDescription.SortOrder = SortOrder.Ascending;// Create our TableSortDescriptionTableSortDescriptiontableSortDescription=new TableSortDescription(newList<SortDescription>(){ countrySortDescription, citySortDescription });return worldCitiesTable.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=new StatisticsDescription(pop1990Field,newList<StatisticsFunction>(){ StatisticsFunction.Sum, StatisticsFunction.Average });StatisticsDescriptionpop2000StatisticsDescription=new StatisticsDescription(pop2000Field,newList<StatisticsFunction>(){ StatisticsFunction.Sum, StatisticsFunction.Average });// Create TableStatisticsDescriptionTableStatisticsDescriptiontableStatisticsDescription=new TableStatisticsDescription(newList<StatisticsDescription>(){ pop1990StatisticsDescription, pop2000StatisticsDescription });
tableStatisticsDescription.GroupBy =newList<Field>(){ regionField };
tableStatisticsDescription.OrderBy =newList<SortDescription>(){new SortDescription(regionField)};// Calculate StatisticsIReadOnlyList<TableStatisticsResult>tableStatisticsResults= countryFeatureClass.CalculateStatistics(tableStatisticsDescription);foreach(TableStatisticsResult tableStatisticsResult in tableStatisticsResults){// 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
publicasync Task SimpleQueryDef(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file")))){QueryDefadaCompilantParksQueryDef=new QueryDef{Tables="Park",WhereClause="ADACOMPLY = 'Yes'",};using(RowCursorrowCursor= geodatabase.Evaluate(adaCompilantParksQueryDef,false)){while(rowCursor.MoveNext()){using(Rowrow= rowCursor.Current){Featurefeature= row as Feature;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
publicasync Task JoiningWithWhereQueryDef(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file")))){QueryDefmunicipalEmergencyFacilitiesQueryDef=new QueryDef{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= row as Feature;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}}}}});}
publicasync Task JoinTablesFromDifferentGeodatabases(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(GeodatabasesourceGeodatabase=new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("Path \\ to \\Geodatabase \\ one"))))using(GeodatabasedestinationGeodatabase=new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("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=new VirtualRelationshipClassDescription(primaryKeyField, foreignKeyField, RelationshipCardinality.OneToMany);using(RelationshipClassrelationshipClass= sourceTable.RelateTo(destinationTable, virtualRelationshipClassDescription)){JoinDescriptionjoinDescription=new JoinDescription(relationshipClass){JoinDirection= JoinDirection.Forward,JoinType= JoinType.InnerJoin,TargetFields= sourceTable.GetDefinition().GetFields()};using(Joinjoin=new Join(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
publicasync Task QueryTableJoinWithVersionedData(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{QueryDefqueryDef=new QueryDef{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=new Geodatabase(new DatabaseConnectionProperties(EnterpriseDatabaseType.Oracle){AuthenticationMode= AuthenticationMode.DBMS,Instance="instance",User="user",Password="password",Database="database",Version="user.testVersion1"})){QueryTableDescriptionqueryTableDescription=new QueryTableDescription(queryDef){Name="CommunityAddrJounMunicipalBoundr",PrimaryKeys= testVersion1Geodatabase.GetSQLSyntax().QualifyColumnName("CommunityAddress","OBJECTID")};// Will be based on testVersion1.using(TablequeryTable= testVersion1Geodatabase.OpenQueryTable(queryTableDescription)){// Use queryTable.}}using(GeodatabasetestVersion2Geodatabase=new Geodatabase(new DatabaseConnectionProperties(EnterpriseDatabaseType.Oracle){AuthenticationMode= AuthenticationMode.DBMS,Instance="instance",User="user",Password="password",Database="database",Version="user.testVersion2"})){QueryTableDescriptionqueryTableDescription=new QueryTableDescription(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(val isDBNull||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)as CodedValueDomain;// Return the text string for this fieldif(domain!=null){return domain.GetName(row[field.Name]);}else{return row[field.Name].ToString();}}}
Editing
Creating a Row
publicasync Task CreatingARow(){stringmessage= String.Empty;boolcreationResult=false;EditOperationeditOperation=new EditOperation();await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("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
publicasync Task CreatingAFeature(){stringmessage= String.Empty;boolcreationResult=false;await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("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=new EditOperation(); 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>{new Coordinate2D(1021570,1880583),new Coordinate2D(1028730,1880994),new Coordinate2D(1029718,1875644),new Coordinate2D(1021405,1875397)}; rowBuffer[facilitySiteDefinition.GetShapeField()]=new PolygonBuilder(newCoordinates).ToGeometry();using(Featurefeature= enterpriseFeatureClass.CreateRow(rowBuffer)){//To Indicate that the attribute table has to be updated context.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
publicasync Task ModifyingARow(){stringmessage= String.Empty;boolmodificationResult=false;await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("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=new EditOperation(); editOperation.Callback(context =>{QueryFilteropenCutFilter=new QueryFilter {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
publicasync Task ModifyingAFeature(){stringmessage= String.Empty;boolmodificationResult=false;await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("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=new EditOperation(); editOperation.Callback(context =>{QueryFilterqueryFilter=new QueryFilter {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 row context.Invalidate(feature);// Transfer all Hazardous Material Facilities to the City. feature[ownTypeIndex]="Municipal";if(Convert.ToDouble(feature[areaIndex])>50000){// Set the Shape of the feature to whatever you need.List<Coordinate2D>newCoordinates=newList<Coordinate2D>{new Coordinate2D(1021570,1880583),new Coordinate2D(1028730,1880994),new Coordinate2D(1029718,1875644),new Coordinate2D(1021405,1875397)}; feature.SetShape(new PolygonBuilder(newCoordinates).ToGeometry());} feature.Store();// Has to be called after the store too context.Invalidate(feature);}}}}, enterpriseFeatureClass);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
publicasync Task DeletingARowOrFeature(){stringmessage= String.Empty;booldeletionResult=false;await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("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=new EditOperation(); editOperation.Callback(context =>{QueryFilteropenCutFilter=new QueryFilter {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
publicasync Task WriteBlobField(Tabletable,stringblobFieldName,stringimageFileName){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{// Read the image file into a MemoryStreamMemoryStreammemoryStream=new MemoryStream();;using(FileStreamimageFile=new FileStream(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
publicasync Task ReadBlobField(Tabletable,QueryFilterqueryFilter,stringblobFieldName){await ArcGIS.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]as MemoryStream;// Create a fileusing(FileStreamoutputFile=new FileStream(imageFileBaseName+ fileCount.ToString(), FileMode.Create, FileAccess.Write)){// Write the MemoryStream into the file memoryStream.WriteTo(outputFile);}}}}});}
publicasync Task CreatingARelationship(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("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=new EditOperation(); 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 updated context.Invalidate(projectsRow); context.Invalidate(overviewRow); context.Invalidate(relationshipClass);}}}, projectsFeatureClass, overviewFeatureClass);booleditResult= editOperation.Execute();}});}
// Insert Cursors are intended for use in CoreHost applications, not Pro Add-inspublicvoidUsingInsertCursor(){using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("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 file insertCursor.Flush();}});}}
Versioning
Connecting to a Version
public Geodatabase ConnectToVersion(Geodatabasegeodatabase,stringversionName){GeodatabaseconnectedVersion=null;if(geodatabase.IsVersioningSupported()){using(VersionManagerversionManager= geodatabase.GetVersionManager())using(Versionversion= versionManager.GetVersion(versionName)){connectedVersion= version.Connect();}}returnconnectedVersion;}
Reconciling and Posting a Version with its Parent
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=new ReconcileDescription(parentVersion);
reconcileDescription.ConflictResolutionMethod = ConflictResolutionMethod.Continue;// continue if conflicts are found
reconcileDescription.WithPost =true;// Reconcile and postReconcileResultreconcileResult= currentVersion.Reconcile(reconcileDescription);// ReconcileResult.HasConflicts can be checked as-needed}}}
Working with Versions
publicasync Task WorkingWithVersions(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(Geodatabasegeodatabase=new Geodatabase(new DatabaseConnectionFile(new Uri("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()){return IsDefaultVersion(currentVersion);}}// Gets the default version.// Works with both branch and traditional versioning.// Note that this routine depends on IsDefaultVersion(), above.public Version GetDefaultVersion(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;}}public Version GetDefaultVersion(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;}}
Creating a Version
public Version CreateVersion(Geodatabasegeodatabase,stringversionName,stringdescription,VersionAccessTypeversionAccessType){if(!geodatabase.IsVersioningSupported())returnnull;using(VersionManagerversionManager= geodatabase.GetVersionManager()){VersionDescriptionversionDescription=new VersionDescription(versionName, description, versionAccessType);return versionManager.CreateVersion(versionDescription);}}
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=new QueryFilter(){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=new ReconcileDescription();
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=new FieldDescription("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",new CodedValueDomainDescription(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=new TableDescription("PoleInspection", fieldDescriptions);// Create a SchemaBuilder objectSchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Add the creation of PoleInspection to our list of DDL tasks
schemaBuilder.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=new ShapeDescription(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=new ShapeDescription(existingFeatureClass.GetDefinition());// Create a FeatureClassDescription object to describe the feature class to createFeatureClassDescriptionfeatureClassDescription=new FeatureClassDescription("Cities", fieldDescriptions, shapeDescription);// Create a SchemaBuilder objectSchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Add the creation of the Cities feature class to our list of DDL tasks
schemaBuilder.Create(featureClassDescription);// Execute the DDLboolsuccess= schemaBuilder.Build();// Inspect error messagesif(!success){IReadOnlyList<string>errorMessages= schemaBuilder.ErrorMessages;//etc.}
Deleting a Table
// Create a TableDescription objectTableDescriptiontableDescription=new TableDescription(table.GetDefinition());// Create a SchemaBuilder objectSchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Add the deletion of the table to our list of DDL tasks
schemaBuilder.Delete(tableDescription);// Execute the DDLboolsuccess= schemaBuilder.Build();
Deleting a Feature Class
// Create a FeatureClassDescription objectFeatureClassDescriptionfeatureClassDescription=new FeatureClassDescription(featureClass.GetDefinition());// Create a SchemaBuilder objectSchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Add the deletion fo the feature class to our list of DDL tasks
schemaBuilder.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=new FileGeodatabaseConnectionPath(new Uri(@"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=new FileGeodatabaseConnectionPath(new Uri(@"C:\Path-To-File-Geodatabase\YourName.gdb"));// Delete the file geodatabase
SchemaBuilder.DeleteGeodatabase(fileGeodatabaseConnectionPath);