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.OpenRelationshipClasses(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(RelationshipClassDefinition relationshipClassDefinition in relationshipClassDefinitions){IReadOnlyList<Definition>definitions= geodatabase.GetRelatedDefinitions(relationshipClassDefinition, DefinitionRelationshipType.DatasetsRelatedThrough);foreach(Definition definition in definitions){ System.Diagnostics.Debug.WriteLine($"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(()=>{FileSystemConnectionPathfileConnection=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");}});}
Opening a CAD Datastore
publicasync Task OpenCADFeatureClass(){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{FileSystemConnectionPathfileConnection=new FileSystemConnectionPath(new Uri("path\\to\\folder\\containing\\CAD"), FileSystemDatastoreType.Cad);using(FileSystemDatastorecadDatastore=new FileSystemDatastore(fileConnection)){// note - extension is requiredFeatureClasscadDataset= cadDatastore.OpenDataset<FeatureClass>("hatchplayboundaries.dwg");// take note of the pattern for referencing a feature class. FeatureClasscadfeatureClass= cadDatastore.OpenDataset<FeatureClass>("hatchplayboundaries.dwg:Polyline");intnumRows=0;using(RowCursorcursor= cadfeatureClass.Search()){while(cursor.MoveNext())numRows++;}}});}
Queries
Searching a Table using QueryFilter
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 PolygonBuilderEx(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 PolygonBuilderEx(newCoordinates).ToGeometry(),SpatialRelationship= SpatialRelationship.Crosses};// For Selecting all matching entries.using(SelectionanotherSelection= enterpriseFeatureClass.Select(spatialFilter, SelectionType.ObjectID, SelectionOption.Normal)){}// This can be used to get one record which matches the criteria. No assumptions can be made about which record satisfying the // criteria is selected.using(SelectiononlyOneSelection= enterpriseFeatureClass.Select(spatialFilter, SelectionType.ObjectID, SelectionOption.OnlyOne)){}// This can be used to obtain a empty selction which can be used as a container to combine results from different selections.using(SelectionemptySelection= enterpriseFeatureClass.Select(spatialFilter, SelectionType.ObjectID, SelectionOption.Empty)){}// If you want to select all the records in a table.using(SelectionallRecordSelection= enterpriseFeatureClass.Select(null, SelectionType.ObjectID, SelectionOption.Normal)){}}});}
Gets the count of how many rows are currently in a Table
//Note: call within QueuedTask.Run()Tabletable= featureLayer.GetTable();longcount= table.GetCount();
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
objectval= 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 rowobjectvarSubtypeCode= row[subtypeFieldName];longsubtypeCode=(long)varSubtypeCode;// Get subtype for this rowsubtype= tableDefinition.GetSubtypes().First(x => x.GetCode()==subtypeCode);}// Get the coded value domain for this fieldCodedValueDomaindomain= field.GetDomain(subtype)as CodedValueDomain;// Return the text string for this fieldif(domain!=null){return domain.GetName(row[field.Name]);}else{return row[field.Name].ToString();}}}
publicvoidQueryFilterWithPagination(Tabletable,List<long>objectIDs){introwsPerBatch=100;intoffset=0;// Query filter// Some datastores support pagination only through an SQL postfix clauseQueryFilterqueryFilter=new QueryFilter(){ObjectIDs=objectIDs,PostfixClause="ORDER BY OBJECTID"};// Fetch rows in a batch from a tablefor(intindex= offset;index <= objectIDs.Count;index+=rowsPerBatch){// Set number of rows to return from a table
queryFilter.RowCount =rowsPerBatch;// Set positional offset to skip number of rows from a table
queryFilter.Offset =index;using(RowCursorcursor= table.Search(queryFilter)){while(cursor.MoveNext()){using(Rowrow= cursor.Current){
Console.WriteLine(row.GetObjectID());}}}}}
Illustrate version conflict information from a reconcile operation
publicvoidGetVersionConflictsInfoInUpdateDeleteType(ServiceConnectionPropertiesfeatureServiceConnectionProperties,stringfeatureClassName){// To illustrate the conflict between versions,// the feature is updated in the child version and deleted in the parent version.longfeatureObjectIDForEdit= Int64.MinValue;// Get branch versioned serviceusing(GeodatabasefsGeodatabase=new Geodatabase(featureServiceConnectionProperties))using(VersionManagerversionManager= fsGeodatabase.GetVersionManager())using(VersiondefaultVersion= versionManager.GetDefaultVersion())using(GeodatabasedefaultGeodatabase= defaultVersion.Connect())using(FeatureClassdefaultFeatureClass= defaultGeodatabase.OpenDataset<FeatureClass>(featureClassName))using(FeatureClassDefinitiondefaultFeatureClassDefinition= defaultFeatureClass.GetDefinition()){// Create a feature in the default version to edit in a branch
defaultGeodatabase.ApplyEdits(()=>{using(RowBufferrowBuffer= defaultFeatureClass.CreateRowBuffer()){ rowBuffer["NAME"]="Loblolly Pine"; rowBuffer["TREEAGE"]=1; rowBuffer[defaultFeatureClassDefinition.GetShapeField()]=new MapPointBuilderEx(new Coordinate2D(1,1), SpatialReferenceBuilder.CreateSpatialReference(4152,0)).ToGeometry();using(Featurefeature= defaultFeatureClass.CreateRow(rowBuffer)){featureObjectIDForEdit= feature.GetObjectID();}}});// Add newly created feature in the filterQueryFilterqueryFilter=new QueryFilter {ObjectIDs=newList<long>{ featureObjectIDForEdit }};// Create a branch versionVersionDescriptionversionDescription=new VersionDescription("UpdateDeleteConflictType","Update-Delete version conflict type", VersionAccessType.Private);// Edit the feature in the branch using(VersioneditVersion= versionManager.CreateVersion(versionDescription))using(GeodatabasebranchGeodatabase= editVersion.Connect())using(FeatureClassfeatureClass= branchGeodatabase.OpenDataset<FeatureClass>(featureClassName))using(RowCursorrowCursor= featureClass.Search(queryFilter,false)){
branchGeodatabase.ApplyEdits(()=>{while(rowCursor.MoveNext()){using(Rowrow= rowCursor.Current){ row["TREEAGE"]=100; row["NAME"]=$"{row["Name"]}_EditInBranch"; row.Store();}}});// Delete the feature from the default version
defaultFeatureClass.DeleteRows(queryFilter);// Reconcile optionsReconcileOptionsreconcileOptions=new ReconcileOptions(defaultVersion){ConflictResolutionType= ConflictResolutionType.FavorEditVersion,ConflictDetectionType= ConflictDetectionType.ByRow,ConflictResolutionMethod= ConflictResolutionMethod.Continue
};// Reconcile with defaultReconcileResultreconcileResult= editVersion.Reconcile(reconcileOptions);// Check for conflictsboolhasConflictsReconcileResults= reconcileResult.HasConflicts;boolhasConflictsAfterReconcile= editVersion.HasConflicts();// Fetch conflictsIReadOnlyList<Conflict>conflictsAfterReconcile= editVersion.GetConflicts();// Iterate conflictsforeach(Conflict conflict in conflictsAfterReconcile){// Object ID of row where conflict occurslongobjectId= conflict.ObjectID;ConflictTypeconflictType= conflict.ConflictType;IReadOnlyList<FieldValue>ancestorVersionValues= conflict.AncestorVersionValues;objectnameAncestor= ancestorVersionValues.FirstOrDefault(f => f.FieldName.Contains("NAME")).Value;objecttreeAgeAncestor= ancestorVersionValues.FirstOrDefault(f => f.FieldName.Contains("TREEAGE")).Value;IReadOnlyList<FieldValue>childVersionValues= conflict.ChildVersionValues;objectnameChild= childVersionValues.FirstOrDefault(f => f.FieldName.Contains("NAME")).Value;objecttreeAgeChild= childVersionValues.FirstOrDefault(f => f.FieldName.Contains("TREEAGE")).Value;IReadOnlyList<FieldValue>parentVersionValues= conflict.ParentVersionValues;IReadOnlyList<Field>originalFields= defaultFeatureClassDefinition.GetFields();stringdatasetName= conflict.DatasetName;}}}}
Explore cotingent attribute values
publicvoidExploreContingentValues(Tabletable){using(TableDefinitiontableDefinition= table.GetDefinition()){IReadOnlyList<Contingency>contingencies= tableDefinition.GetContingencies();foreach(Contingency contingency in contingencies){// Field group FieldGroupfiledGroup= contingency.FieldGroup;stringfieldGroupName= filedGroup.Name;IReadOnlyList<string>fieldInFieldGroup= filedGroup.FieldNames;boolisEditRestriction= filedGroup.IsRestrictive;intcontingencyId= contingency.ID;Subtypesubtype= contingency.Subtype;boolisContingencyRetired= contingency.IsRetired;// Contingent values IReadOnlyDictionary<string,ContingentValue>contingentValuesByFieldName= contingency.GetContingentValues();foreach(KeyValuePair<string,ContingentValue> contingentValueKeyValuePair in contingentValuesByFieldName){stringattributeFieldName= contingentValueKeyValuePair.Key;// Contingent value type associated with the attribute fieldContingentValuecontingentValue= contingentValueKeyValuePair.Value;switch(contingentValue){case ContingentCodedValue contingentCodedValue:stringcodedValueDomainName= contingentCodedValue.Name;objectcodedValueDomainValue= contingentCodedValue.CodedValue;break;case ContingentRangeValue contingentRangeValue:objectrangeDomainMaxValue= contingentRangeValue.Max;objectrangeDomainMinValue= contingentRangeValue.Min;break;case ContingentAnyValue contingentAnyValue:// Any value typebreak;case ContingentNullValue contingentNullValue:// Null valuebreak;}}}}}
Validate contingent attribute values
publicvoidValidateContingentValues(FeatureClassparcels,stringzoningFieldName="Zone",stringtaxCodeFieldName="TaxCode"){using(RowBufferrowBuffer= parcels.CreateRowBuffer()){// Insert values in a row buffer
rowBuffer[zoningFieldName]="Business";
rowBuffer[taxCodeFieldName]="TaxB";// Validate contingency values of the parcels' row ContingencyValidationResultcontingencyValidationResult= parcels.ValidateContingencies(rowBuffer);// Valid contingenciesIReadOnlyList<Contingency>matchedContingencies= contingencyValidationResult.Matches;if(matchedContingencies.Count >0){// Create a row with valid contingency values
parcels.CreateRow(rowBuffer);}// Invalid contingenciesIReadOnlyList<ContingencyViolation>violatedContingencies= contingencyValidationResult.Violations;foreach(ContingencyViolation contingencyViolation in violatedContingencies){ContingencyViolationTypeviolationType= contingencyViolation.Type;ContingencyviolatedContingency= contingencyViolation.Contingency;}}}
Get possible contingent values
publicvoidGetPossibleContingentValues(FeatureClassparcels,stringzoningFieldName="Zone"){using(RowBufferrowBuffer= parcels.CreateRowBuffer()){IReadOnlyDictionary<FieldGroup,IReadOnlyList<ContingentValue>>possibleZonings= parcels.GetContingentValues(rowBuffer, zoningFieldName);IEnumerable<FieldGroup>possibleFieldGroups= possibleZonings.Keys;foreach(FieldGroup possibleFieldGroup in possibleFieldGroups){IReadOnlyList<ContingentValue>possibleZoningValues= possibleZonings[possibleFieldGroup];foreach(ContingentValue possibleZoningValue in possibleZoningValues){switch(possibleZoningValue){case ContingentCodedValue codedValue:stringcodedValueDomainName= codedValue.Name;objectcodedValueDomainValue= codedValue.CodedValue;break;case ContingentRangeValue rangeValue:objectrangeDomainMaxValue= rangeValue.Max;objectrangeDomainMinValue= rangeValue.Min;break;case ContingentAnyValue contingentAnyValue:// Any value typebreak;case ContingentNullValue contingentNullValue:// Null valuebreak;}}}}}
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 yetEditOperationeditOperation=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 PolygonBuilderEx(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 PolygonBuilderEx(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);}
Split a feature by geometry
publicvoidSplitALineByPoint(FeatureClasslineFeatureClass,MapPointxPoint){using(RowCursorrowCursor= lineFeatureClass.Search(new QueryFilter(){ObjectIDs=newList<long>(){1}})){if(rowCursor.MoveNext()){using(Featurefeature= rowCursor.Current as Feature){// ObjectIDs of newly created linesIReadOnlyList<long>splits= feature.Split(xPoint);}}}}
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();}});}}
Creating a new Annotation Feature in an Annotation FeatureClass using a RowBuffer
publicasync Task CreatingAnAnnotationFeature(Geodatabasegeodatabase){await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(AnnotationFeatureClassannotationFeatureClass= geodatabase.OpenDataset<AnnotationFeatureClass>("Annotation // feature // class // name"))using(AnnotationFeatureClassDefinitionannotationFeatureClassDefinition= annotationFeatureClass.GetDefinition())using(RowBufferrowBuffer= annotationFeatureClass.CreateRowBuffer())using(AnnotationFeatureannotationFeature= annotationFeatureClass.CreateRow(rowBuffer)){ annotationFeature.SetAnnotationClassID(0); annotationFeature.SetStatus(AnnotationStatus.Placed);// Get the annotation labels from the label collectionIReadOnlyList<CIMLabelClass>labelClasses= annotationFeatureClassDefinition.GetLabelClassCollection();// Setup the symbol reference with the symbol id and the text symbolCIMSymbolReferencecimSymbolReference=new CIMSymbolReference(); cimSymbolReference.Symbol = labelClasses[0].TextSymbol.Symbol; cimSymbolReference.SymbolName = labelClasses[0].TextSymbol.SymbolName;// Setup the text graphicCIMTextGraphiccimTextGraphic=new CIMTextGraphic(); cimTextGraphic.Text ="Charlotte, North Carolina"; cimTextGraphic.Shape =new MapPointBuilderEx(new Coordinate2D(-80.843,35.234), SpatialReferences.WGS84).ToGeometry(); cimTextGraphic.Symbol =cimSymbolReference;// Set the symbol reference on the graphic and store annotationFeature.SetGraphic(cimTextGraphic); annotationFeature.Store();}});}
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 in separate edit sessions
publicvoidReconcileAndPost(Geodatabasegeodatabase){// Get a reference to our version and our parentif(geodatabase.IsVersioningSupported()){using(VersionManagerversionManager= geodatabase.GetVersionManager())using(VersioncurrentVersion= versionManager.GetCurrentVersion())using(VersionparentVersion= currentVersion.GetParent()){//// Create a ReconcileDescription object//At 2.x - //ReconcileDescription reconcileDescription = new ReconcileDescription(parentVersion);//reconcileDescription.ConflictResolutionMethod = ConflictResolutionMethod.Continue; // continue if conflicts are found//reconcileDescription.WithPost = true;//// Reconcile and post//ReconcileResult reconcileResult = currentVersion.Reconcile(reconcileDescription);// ReconcileResult.HasConflicts can be checked as-needed// Create a ReconcileOptions objectReconcileOptionsreconcileOptions=new ReconcileOptions(parentVersion);
reconcileOptions.ConflictResolutionMethod = ConflictResolutionMethod.Continue;// continue if conflicts are found
reconcileOptions.ConflictDetectionType = ConflictDetectionType.ByRow;//Default
reconcileOptions.ConflictResolutionType = ConflictResolutionType.FavorTargetVersion;//or FavorEditVersion// ReconcileReconcileResultreconcileResult= currentVersion.Reconcile(reconcileOptions);if(!reconcileResult.HasConflicts){//No conflicts, perform the postPostOptionspostOptions=new PostOptions(parentVersion);//var postOptions = new PostOptions(); for default version
postOptions.ServiceSynchronizationType = ServiceSynchronizationType.Synchronous;//Default
currentVersion.Post(postOptions);}}}}
Reconciling and Posting a Version with its Parent in the same edit session
publicvoidReconcileAndPost2(Geodatabasegeodatabase){// Get a reference to our version and our parentif(geodatabase.IsVersioningSupported()){using(VersionManagerversionManager= geodatabase.GetVersionManager())using(VersioncurrentVersion= versionManager.GetCurrentVersion())using(VersionparentVersion= currentVersion.GetParent()){//// Create a ReconcileDescription object//At 2.x - //ReconcileDescription reconcileDescription = new ReconcileDescription(parentVersion);//reconcileDescription.ConflictResolutionMethod = ConflictResolutionMethod.Continue; // continue if conflicts are found//reconcileDescription.WithPost = true;//// Reconcile and post//ReconcileResult reconcileResult = currentVersion.Reconcile(reconcileDescription);// ReconcileResult.HasConflicts can be checked as-needed// Create a ReconcileOptions objectReconcileOptionsreconcileOptions=new ReconcileOptions(parentVersion);
reconcileOptions.ConflictResolutionMethod = ConflictResolutionMethod.Continue;// continue if conflicts are found
reconcileOptions.ConflictDetectionType = ConflictDetectionType.ByRow;//Default
reconcileOptions.ConflictResolutionType = ConflictResolutionType.FavorTargetVersion;//or FavorEditVersionPostOptionspostOptions=new PostOptions(parentVersion);//var postOptions = new PostOptions(); for default version
postOptions.ServiceSynchronizationType = ServiceSynchronizationType.Synchronous;//Default// ReconcileReconcileResultreconcileResult= currentVersion.Reconcile(reconcileOptions, postOptions);if(reconcileResult.HasConflicts){//TODO resolve conflicts}}}}
// Check to see if the current version is default.// Works with both branch and traditional versioning.publicboolIsDefaultVersion(Versionversion){VersionparentVersion= version.GetParent();if(parentVersion==null){returntrue;}
parentVersion.Dispose();returnfalse;}publicboolIsDefaultVersion(Geodatabasegeodatabase){if(!geodatabase.IsVersioningSupported())returnfalse;using(VersionManagerversionManager= geodatabase.GetVersionManager())using(VersioncurrentVersion= versionManager.GetCurrentVersion()){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);}}
Creating a Historical version
public HistoricalVersion CreateHistoricalVersion(Geodatabasegeodatabase,stringversionName){using(VersionManagerversionManager= geodatabase.GetVersionManager()){HistoricalVersionDescriptionhistoricalVersionDescription=new HistoricalVersionDescription(versionName, DateTime.Now);HistoricalVersionhistoricalVersion= versionManager.CreateHistoricalVersion(historicalVersionDescription);returnhistoricalVersion;}}
Switching between versions
publicvoidChangeVersions(Geodatabasegeodatabase,stringtoVersionName){using(VersionManagerversionManager= geodatabase.GetVersionManager()){VersionBaseTypeversionBaseType= versionManager.GetCurrentVersionBaseType();if(versionBaseType== VersionBaseType.Version){VersionfromVersion= versionManager.GetCurrentVersion();VersiontoVersion= versionManager.GetVersion(toVersionName);// Switch between versions
MapView.Active.Map.ChangeVersion(fromVersion, toVersion);}if(versionBaseType== VersionBaseType.HistoricalVersion){HistoricalVersionfromHistoricalVersion= versionManager.GetCurrentHistoricalVersion();HistoricalVersiontoHistoricalVersion= versionManager.GetHistoricalVersion(toVersionName);// Switch between historical versions
MapView.Active.Map.ChangeVersion(fromHistoricalVersion, toHistoricalVersion);}// Switch from HistoricalVersion to Version and vice-versa // MapView.Active.Map.ChangeVersion(fromHistoricalVersion, toVersion);// MapView.Active.Map.ChangeVersion(fromVersion, toHistoricalVersion);}}
Partial Posting
// Partial posting allows developers to post a subset of changes made in a version.// One sample use case is an electric utility that uses a version to design the facilities in// a new housing subdivision. At some point in the process, one block of new houses have been// completed, while the rest of the subdivision remains unbuilt. Partial posting allows the user// to post the completed work, while leaving not yet constructed features in the version to be// posted later. Partial posting requires a branch-versioned feature service using ArcGIS// Enterprise 10.9 and higher// Specify a set of features that were constructedQueryFilterconstructedFilter=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 post//At 2.x - //ReconcileDescription reconcileDescription = new ReconcileDescription();//reconcileDescription.ConflictDetectionType = ConflictDetectionType.ByColumn;//reconcileDescription.ConflictResolutionMethod = ConflictResolutionMethod.Continue;//reconcileDescription.ConflictResolutionType = ConflictResolutionType.FavorEditVersion;//reconcileDescription.PartialPostSelections = new List<Selection>() { constructedSupportStructures, deletedSupportStructures };//reconcileDescription.WithPost = true;//ReconcileResult reconcileResult = designVersion.Reconcile(reconcileDescription);ReconcileOptionsreconcileOptions=new ReconcileOptions();//reconcile against Default
reconcileOptions.ConflictDetectionType = ConflictDetectionType.ByColumn;
reconcileOptions.ConflictResolutionMethod = ConflictResolutionMethod.Continue;
reconcileOptions.ConflictResolutionType = ConflictResolutionType.FavorEditVersion;PostOptionspostOptions=new PostOptions();//post against Default
postOptions.PartialPostSelections =newList<Selection>(){
constructedSupportStructures, deletedSupportStructures };
postOptions.ServiceSynchronizationType = ServiceSynchronizationType.Synchronous;ReconcileResultreconcileResult= designVersion.Reconcile(reconcileOptions, postOptions);//TODO process result(s)}}
Iterate datasets inside a feature dataset
publicvoidIterateDatasetsFromAFeatureDataset(Geodatabasegeodatabase,stringfeatureDatasetName="City",stringfeatureClassInFeatureDataset="Buildings"){// Open a feature datasetusing(FeatureDatasetcityFeatureDataset= geodatabase.OpenDataset<FeatureDataset>(featureDatasetName)){// Get a feature class definition from a feature datasetFeatureClassDefinitionbuildingsFeatureClassDefinition= cityFeatureDataset.GetDefinition<FeatureClassDefinition>(featureClassInFeatureDataset);// Iterate dataset definitionIReadOnlyList<FeatureClassDefinition>cityFeatureClassDefinitions= cityFeatureDataset.GetDefinitions<FeatureClassDefinition>();foreach(FeatureClassDefinition cityFeatureClassDefinition in cityFeatureClassDefinitions){// Use feature class definition}}}
Get attribute rules of a dataset
publicvoidGetAttributeRules(Geodatabasegeodatabase,stringtableName){using(TableDefinitiontableDefinition= geodatabase.GetDefinition<TableDefinition>(tableName)){// Get all attribute rule typesIReadOnlyList<AttributeRuleDefinition>ruleDefinitions= tableDefinition.GetAttributeRules();// Iterate rule definitionsforeach(AttributeRuleDefinition ruleDefinition in ruleDefinitions){AttributeRuleTyperuleType= ruleDefinition.GetAttributeRuleType();stringruleDescription= ruleDefinition.GetDescription();boolisAttributeFieldEditable= ruleDefinition.GetIsFieldEditable();stringarcadeVersionToSupportRule= ruleDefinition.GetMinimumArcadeVersion();intruleEvaluationOrder= ruleDefinition.GetEvaluationOrder();AttributeRuleTriggerstriggeringEvents= ruleDefinition.GetTriggeringEvents();stringscriptExpression= ruleDefinition.GetScriptExpression();// more properties}}}
Creating a row buffer from a template row
publicvoidCreateRowBufferFromARow(Tabletable){using(RowCursorrowCursor= table.Search()){if(rowCursor.MoveNext()){using(RowtemplateRow= rowCursor.Current){RowBufferrowBuffer= table.CreateRowBuffer(templateRow);// Manipulate row buffer// Doesn't allow copying values of ObjectID and GlobalID//// rowBuffer["Field"] = "Update";//// create a new row
table.CreateRow(rowBuffer);}}}}
Extension Ids
Table Extension Ids
publicvoidExtensionIds1(Tabletable){//Add an extension id to a table//Check documentation for restrictions on backward compatibility - backward//compatibility is limited to ArcGIS Pro 3.1 if an extension id is added.//Note: This is an extension method. It is for use in addins only and not CoreHost.stringextension_id_string="52d8f3be-b73d-4140-beaf-23d4f9b697ea";Guidextension_id= Guid.Parse(extension_id_string);//Note: Must be within the lambda of QueuedTask.Run(() => { ...//register the extension id with the relevant table
table.AddActivationExtension(extension_id);//Remove an extension id from a table//Restores backward compatibility assuming no other compatibility limitations are//in place.//Note: This is an extension method. It is for use in addins only and not CoreHost.
table.RemoveActivationExtension(extension_id);//Check if a given extension id is registered with a particular table.//Note: This is an extension method. It is for use in addins only and not CoreHost.if(table.GetHasActivationExtension(extension_id)){//TODO - implement custom logic relevant to presence of extension_id}//Enumerate all extension ids on a given table.//Note: This is an extension method. It is for use in addins only and not CoreHost.foreach(Guid ext_id in table.GetActivationExtensions()){//TODO - logic based on extension ids}}
// Earthquake occurrences date and time// 9/28/2014 (DateOnly)FieldDescriptionearthquakeDateOnlyFieldDescription=new FieldDescription("Earthquake_DateOnly", FieldType.DateOnly);// 1:16:42 AM (TimeOnly)FieldDescriptionearthquakeTimeOnlyFieldDescription=new FieldDescription("Earthquake_TimeOnly", FieldType.TimeOnly);// 9/28/2014 1:16:42.000 AM -09:00 (Timestamp with Offset)FieldDescriptionearthquakeTimestampOffsetFieldDescription=new FieldDescription("Earthquake_TimestampOffset_Local", FieldType.TimestampOffset);// 9/28/2014 1:16:42 AM (DateTime)FieldDescriptionearthquakeDateFieldDescription=new FieldDescription("Earthquake_Date", FieldType.Date);
Creating a Table
publicvoidCreateTableSnippet(Geodatabasegeodatabase,CodedValueDomaininspectionResultsDomain){// Create a PoleInspection table with the following fields// GlobalID// ObjectID// InspectionDate (date)// InspectionResults (pre-existing InspectionResults coded value domain)// InspectionNotes (string)// This static helper routine creates a FieldDescription for a GlobalID field with default valuesFieldDescriptionglobalIDFieldDescription= FieldDescription.CreateGlobalIDField();// This static helper routine creates a FieldDescription for an ObjectID field with default valuesFieldDescriptionobjectIDFieldDescription= FieldDescription.CreateObjectIDField();// Create a FieldDescription for the InspectionDate fieldFieldDescriptioninspectionDateFieldDescription=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
publicvoidCreateFeatureClassSnippet(Geodatabasegeodatabase,FeatureClassexistingFeatureClass,SpatialReferencespatialReference){// Create a Cities feature class with the following fields// GlobalID// ObjectID// Name (string)// Population (integer)// This static helper routine creates a FieldDescription for a GlobalID field with default valuesFieldDescriptionglobalIDFieldDescription= FieldDescription.CreateGlobalIDField();// This static helper routine creates a FieldDescription for an ObjectID field with default valuesFieldDescriptionobjectIDFieldDescription= FieldDescription.CreateObjectIDField();// This static helper routine creates a FieldDescription for a string fieldFieldDescriptionnameFieldDescription= FieldDescription.CreateStringField("Name",255);// This static helper routine creates a FieldDescription for an integer fieldFieldDescriptionpopulationFieldDescription= FieldDescription.CreateIntegerField("Population");// Assemble a list of all of our field descriptionsList<FieldDescription>fieldDescriptions=newList<FieldDescription>(){ globalIDFieldDescription, objectIDFieldDescription, nameFieldDescription, populationFieldDescription };// Create a ShapeDescription objectShapeDescriptionshapeDescription=new ShapeDescription(GeometryType.Point, spatialReference);// Alternatively, ShapeDescriptions can be created from another feature class. In this case, the new feature class will inherit the same shape properties of the existing classShapeDescriptionalternativeShapeDescription=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
publicvoidDeleteTableSnippet(Geodatabasegeodatabase,Tabletable){// 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
publicvoidDeleteFeatureClassSnippet(Geodatabasegeodatabase,FeatureClassfeatureClass){// 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();}
Opens a memory geodatabase
publicvoidOpenMemoryGeodatabase(){// Connects to the default memory geodatabase, if exists otherwise throws exceptionMemoryConnectionPropertiesmemoryConnectionProperties=new MemoryConnectionProperties();// Alternatively, connects to memory geodatabase named as 'InterimMemoryGeodatabase'// MemoryConnectionProperties memoryConnectionProperties = new MemoryConnectionProperties("InterimMemoryGeodatabase");// Opens the memory geodatabaseusing(Geodatabasegeodatabase=new Geodatabase(memoryConnectionProperties)){// Use memory geodatabase}}
Creating a memory Geodatabase
publicvoidCreateMemoryGeodatabaseSnippet(){// Create the memory connection properties to connect to default memory geodatabaseMemoryConnectionPropertiesmemoryConnectionProperties=new MemoryConnectionProperties();// Alternatively create the memory connection properties to connect to memory geodatabase named as 'InterimMemoryGeodatabase'// MemoryConnectionProperties memoryConnectionProperties = new MemoryConnectionProperties("InterimMemoryGeodatabase");// Creates the new memory geodatabase if it does not exist or connects to an existing one if it already existsusing(Geodatabasegeodatabase=new Geodatabase(memoryConnectionProperties)){// Create additional schema here}}
Deleting a memory Geodatabase
publicvoidDeleteMemoryGeodatabaseSnippet(){// Create the memory connection properties to connect to default memory geodatabaseMemoryConnectionPropertiesmemoryConnectionProperties=new MemoryConnectionProperties();// Delete the memory geodatabase
SchemaBuilder.DeleteGeodatabase(memoryConnectionProperties);}
Creating a File Geodatabase
publicvoidCreateFileGeodatabaseSnippet(){// 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
publicvoidDeleteFileGeodatabaseSnippet(){// 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);}
Creating a Mobile Geodatabase
publicvoidCreateMobileGeodatabase(){// Create a MobileGeodatabaseConnectionPath with the name of the mobile geodatabase you wish to createMobileGeodatabaseConnectionPathmobileGeodatabaseConnectionPath=new MobileGeodatabaseConnectionPath(new Uri(@"C:\Path-To-Mobile-Geodatabase\YourName.geodatabase"));// Create and use the mobile geodatabaseusing(Geodatabasegeodatabase= SchemaBuilder.CreateGeodatabase(mobileGeodatabaseConnectionPath)){// Create additional schema here}}
Deleting a Mobile Geodatabase
publicvoidDeleteMobileGeodatabase(){// Create a MobileGeodatabaseConnectionPath with the name of the mobile geodatabase you wish to deleteMobileGeodatabaseConnectionPathmobileGeodatabaseConnectionPath=new MobileGeodatabaseConnectionPath(new Uri(@"C:\Path-To-Mobile-Geodatabase\YourName.geodatabase"));// Delete the mobile geodatabase
SchemaBuilder.DeleteGeodatabase(mobileGeodatabaseConnectionPath);}
Creating a Range domain
publicvoidCreateRangeDomainSnippet(Geodatabasegeodatabase){// Create a range description with minimum value = 0 and maximum value = 1000RangeDomainDescriptionrangeDomainDescriptionMinMax=new RangeDomainDescription("RangeDomain_0_1000",
FieldType.Integer,0,1000){Description="Domain value ranges from 0 to 1000"};SchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Create a range domain
schemaBuilder.Create(rangeDomainDescriptionMinMax);
schemaBuilder.Build();}
Creating a CodedValue domain
publicvoidCreateCodedDomainSnippet(Geodatabasegeodatabase){// Create a CodedValueDomain description for water pipesCodedValueDomainDescriptioncodedValueDomainDescription=new CodedValueDomainDescription("WaterPipeTypes", FieldType.String,newSortedList<object,string>{{"C_1","Copper"},{"S_2","Steel"}}){SplitPolicy= SplitPolicy.Duplicate,MergePolicy= MergePolicy.DefaultValue
};SchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Create a coded value domain CodedValueDomainTokencodedValueDomainToken= schemaBuilder.Create(codedValueDomainDescription);
schemaBuilder.Build();}
Creating a FeatureDataset
publicvoidCreateFeatureDatasetSnippet(Geodatabasegeodatabase){// Creating a FeatureDataset named as 'Parcel_Information'SchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Create a FeatureDataset named as 'Parcel Information'FeatureDatasetDescriptionfeatureDatasetDescription=new FeatureDatasetDescription("Parcel_Information", SpatialReferences.WGS84);
schemaBuilder.Create(featureDatasetDescription);// Build statusboolbuildStatus= schemaBuilder.Build();// Build errorsif(!buildStatus){IReadOnlyList<string>errors= schemaBuilder.ErrorMessages;}}
Deleting a FeatureDataset
publicvoidDeleteFeatureDatasetSnippet(Geodatabasegeodatabase){// Deleting a FeatureDataset named as 'Parcel_Information'FeatureDatasetDefinitionfeatureDatasetDefinition= geodatabase.GetDefinition<FeatureDatasetDefinition>("Parcel_Information");FeatureDatasetDescriptionfeatureDatasetDescription=new FeatureDatasetDescription(featureDatasetDefinition);SchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Delete an existing feature dataset named as 'Parcel_Information'
schemaBuilder.Delete(featureDatasetDescription);
schemaBuilder.Build();}
Renaming a FeatureDataset
publicvoidRenameFeatureDatasetSnippet(Geodatabasegeodatabase){// Renaming a FeatureDataset from 'Parcel_Information' to 'Parcel_Information_With_Tax_Jurisdiction'stringoriginalDatasetName="Parcel_Information";stringdatasetRenameAs="Parcel_Information_With_Tax_Jurisdiction";FeatureDatasetDefinitionoriginalDatasetDefinition=
geodatabase.GetDefinition<FeatureDatasetDefinition>(originalDatasetName);FeatureDatasetDescriptionoriginalFeatureDatasetDescription=new FeatureDatasetDescription(originalDatasetDefinition);SchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Rename the existing FeatureDataset, 'Parcel_Information' to 'Parcel_Information_With_Tax_Jurisdiction'
schemaBuilder.Rename(originalFeatureDatasetDescription, datasetRenameAs);
schemaBuilder.Build();}
Creating a FeatureDataset with a FeatureClass in one operation
publicvoidCreateFeatureDatasetWithFeatureClassSnippet(Geodatabasegeodatabase){// Creating a FeatureDataset named as 'Parcel_Information' and a FeatureClass with name 'Parcels' in one operationstringfeatureDatasetName="Parcel_Information";stringfeatureClassName="Parcels";SchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Create a FeatureDataset tokenFeatureDatasetDescriptionfeatureDatasetDescription=new FeatureDatasetDescription(featureDatasetName, SpatialReferences.WGS84);FeatureDatasetTokenfeatureDatasetToken= schemaBuilder.Create(featureDatasetDescription);// Create a FeatureClass descriptionFeatureClassDescriptionfeatureClassDescription=new FeatureClassDescription(featureClassName,newList<FieldDescription>(){new FieldDescription("Id", FieldType.Integer),new FieldDescription("Address", FieldType.String)},new ShapeDescription(GeometryType.Point, SpatialReferences.WGS84));// Create a FeatureClass inside a FeatureDatasetFeatureClassTokenfeatureClassToken= schemaBuilder.Create(new FeatureDatasetDescription(featureDatasetToken), featureClassDescription);// Build statusboolbuildStatus= schemaBuilder.Build();// Build errorsif(!buildStatus){IReadOnlyList<string>errors= schemaBuilder.ErrorMessages;}}
Creating a FeatureClass in existing FeatureDataset
publicvoidCreateFeatureClassInsideFeatureDatasetSnippet(Geodatabasegeodatabase){// Creating a FeatureClass named as 'Tax_Jurisdiction' in existing FeatureDataset with name 'Parcels_Information'stringfeatureDatasetName="Parcels_Information";stringfeatureClassName="Tax_Jurisdiction";// Create a FeatureClass descriptionFeatureClassDescriptionfeatureClassDescription=new FeatureClassDescription(featureClassName,newList<FieldDescription>(){new FieldDescription("Tax_Id", FieldType.Integer),new FieldDescription("Address", FieldType.String)},new ShapeDescription(GeometryType.Point, SpatialReferences.WGS84));FeatureDatasetDefinitionfeatureDatasetDefinition= geodatabase.GetDefinition<FeatureDatasetDefinition>(featureDatasetName);SchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Create a FeatureClass inside a FeatureDataset using a FeatureDatasetDefinition
schemaBuilder.Create(new FeatureDatasetDescription(featureDatasetDefinition), featureClassDescription);// Build statusboolbuildStatus= schemaBuilder.Build();// Build errorsif(!buildStatus){IReadOnlyList<string>errors= schemaBuilder.ErrorMessages;}}
Adding a FeatureClass to a FeatureDataset
publicvoidAddFeatureClassToFeatureDatasetSnippet(Geodatabasegeodatabase){// Adding a FeatureClass with name 'Tax_Jurisdiction' into a FeatureDataset named as 'Parcels_Information'stringfeatureDatasetName="Parcels_Information";stringfeatureClassNameToAdd="Tax_Jurisdiction";FeatureDatasetDefinitionfeatureDatasetDefinition= geodatabase.GetDefinition<FeatureDatasetDefinition>(featureDatasetName);FeatureDatasetDescriptionfeatureDatasetDescription=new FeatureDatasetDescription(featureDatasetDefinition);FeatureClassDefinitionfeatureClassDefinition= geodatabase.GetDefinition<FeatureClassDefinition>(featureClassNameToAdd);FeatureClassDescriptionfeatureClassDescription=new FeatureClassDescription(featureClassDefinition);SchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Add the 'Tax_Jurisdiction' FeatureClass to the 'Parcels_Information' FeatureDataset
schemaBuilder.AddFeatureClass(featureDatasetDescription, featureClassDescription);booladdStatus= schemaBuilder.Build();if(!addStatus){IReadOnlyList<string>errors= schemaBuilder.ErrorMessages;}}
Renaming a Table
publicvoidRenameTableSnippet(Geodatabasegeodatabase){//Renaming a table from 'Original_Table' to 'Renamed_Table'stringtableToBeRenamed="Original_Table";stringtableRenameAs="Renamed_Table";TableDefinitiontableDefinition= geodatabase.GetDefinition<TableDefinition>(tableToBeRenamed);SchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Table rename
schemaBuilder.Rename(new TableDescription(tableDefinition), tableRenameAs);
schemaBuilder.Build();}
Adding fields to a FeatureClass
publicvoidAddFieldsInFeatureClassSnippet(Geodatabasegeodatabase){// Adding following fields to the 'Parcels' FeatureClass// Global ID// Parcel_ID// Tax_Code// Parcel_Address// The FeatureClass to add fieldsstringfeatureClassName="Parcels";FeatureClassDefinitionoriginalFeatureClassDefinition= geodatabase.GetDefinition<FeatureClassDefinition>(featureClassName);FeatureClassDescriptionoriginalFeatureClassDescription=new FeatureClassDescription(originalFeatureClassDefinition);// The four new fields to add on the 'Parcels' FeatureClassFieldDescriptionglobalIdField= FieldDescription.CreateGlobalIDField();FieldDescriptionparcelIdDescription=new FieldDescription("Parcel_ID", FieldType.GUID);FieldDescriptiontaxCodeDescription= FieldDescription.CreateIntegerField("Tax_Code");FieldDescriptionaddressDescription= FieldDescription.CreateStringField("Parcel_Address",150);List<FieldDescription>fieldsToAdd=newList<FieldDescription>{ globalIdField, parcelIdDescription,
taxCodeDescription, addressDescription };// Add new fields on the new FieldDescription listList<FieldDescription>modifiedFieldDescriptions=newList<FieldDescription>(originalFeatureClassDescription.FieldDescriptions);
modifiedFieldDescriptions.AddRange(fieldsToAdd);// The new FeatureClassDescription with additional fieldsFeatureClassDescriptionmodifiedFeatureClassDescription=new FeatureClassDescription(originalFeatureClassDescription.Name,
modifiedFieldDescriptions, originalFeatureClassDescription.ShapeDescription);SchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Update the 'Parcels' FeatureClass with newly added fields
schemaBuilder.Modify(modifiedFeatureClassDescription);boolmodifyStatus= schemaBuilder.Build();if(!modifyStatus){IReadOnlyList<string>errors= schemaBuilder.ErrorMessages;}}
Adding a Field that uses a domain
publicvoidAddFieldWithDomainSnippet(Geodatabasegeodatabase){// Adding a field,'PipeType', which uses the coded value domain to the 'Pipes' FeatureClass//The FeatureClass to add fieldstringfeatureClassName="Pipes";SchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Create a CodedValueDomain description for water pipesCodedValueDomainDescriptionpipeDomainDescription=new CodedValueDomainDescription("WaterPipeTypes", FieldType.String,newSortedList<object,string>{{"C_1","Copper"},{"S_2","Steel"}}){SplitPolicy= SplitPolicy.Duplicate,MergePolicy= MergePolicy.DefaultValue
};// Create a coded value domain tokenCodedValueDomainTokencodedValueDomainToken= schemaBuilder.Create(pipeDomainDescription);// Create a new description from domain tokenCodedValueDomainDescriptioncodedValueDomainDescription=new CodedValueDomainDescription(codedValueDomainToken);// Create a field named as 'PipeType' using a domain descriptionFieldDescriptiondomainFieldDescription=new FieldDescription("PipeType", FieldType.String);
domainFieldDescription.SetDomainDescription(codedValueDomainDescription);//Retrieve existing information for 'Pipes' FeatureClassFeatureClassDefinitionoriginalFeatureClassDefinition= geodatabase.GetDefinition<FeatureClassDefinition>(featureClassName);FeatureClassDescriptionoriginalFeatureClassDescription=new FeatureClassDescription(originalFeatureClassDefinition);// Add domain field on existing fieldsList<FieldDescription>modifiedFieldDescriptions=newList<FieldDescription>(originalFeatureClassDescription.FieldDescriptions){ domainFieldDescription };// Create a new description with updated fields for 'Pipes' FeatureClass FeatureClassDescriptionfeatureClassDescription=new FeatureClassDescription(originalFeatureClassDescription.Name, modifiedFieldDescriptions,
originalFeatureClassDescription.ShapeDescription);// Update the 'Pipes' FeatureClass with domain field
schemaBuilder.Modify(featureClassDescription);// Build statusboolbuildStatus= schemaBuilder.Build();// Build errorsif(!buildStatus){IReadOnlyList<string>errors= schemaBuilder.ErrorMessages;}}
Removing fields from a Table
publicvoidRemoveFieldTableSnippet(Geodatabasegeodatabase){// Removing all fields from 'Parcels' table except following // Tax_Code// Parcel_Address// The table to remove fieldsstringtableName="Parcels";TableDefinitiontableDefinition= geodatabase.GetDefinition<TableDefinition>(tableName);IReadOnlyList<Field>fields= tableDefinition.GetFields();// Existing fields from 'Parcels' tableFieldtaxCodeField= fields.First(f => f.Name.Equals("Tax_Code"));FieldparcelAddressField= fields.First(f => f.Name.Equals("Parcel_Address"));FieldDescriptiontaxFieldDescription=new FieldDescription(taxCodeField);FieldDescriptionparcelAddressFieldDescription=new FieldDescription(parcelAddressField);// Fields to retain in modified tableList<FieldDescription>fieldsToBeRetained=newList<FieldDescription>(){
taxFieldDescription, parcelAddressFieldDescription
};// New description of the 'Parcels' table with the 'Tax_Code' and 'Parcel_Address' fieldsTableDescriptionmodifiedTableDescription=new TableDescription(tableName, fieldsToBeRetained);SchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Remove all fields except the 'Tax_Code' and 'Parcel_Address' fields
schemaBuilder.Modify(modifiedTableDescription);
schemaBuilder.Build();}
Creating an annotation feature class
publicvoidCreateStandAloneAnnotationFeatureClass(Geodatabasegeodatabase,SpatialReferencespatialReference){// Creating a Cities annotation feature class// with following user defined fields// Name // GlobalID// Annotation feature class namestringannotationFeatureClassName="CitiesAnnotation";// Create user defined attribute fields for annotation feature class FieldDescriptionglobalIDFieldDescription= FieldDescription.CreateGlobalIDField();FieldDescriptionnameFieldDescription= FieldDescription.CreateStringField("Name",255);// Create a list of all field descriptionsList<FieldDescription>fieldDescriptions=newList<FieldDescription>{ globalIDFieldDescription, nameFieldDescription };// Create a ShapeDescription objectShapeDescriptionshapeDescription=new ShapeDescription(GeometryType.Polygon, spatialReference);// Create general placement properties for Maplex engine CIMMaplexGeneralPlacementPropertiesgeneralPlacementProperties=new CIMMaplexGeneralPlacementProperties
{AllowBorderOverlap=true,PlacementQuality= MaplexQualityType.High,DrawUnplacedLabels=true,InvertedLabelTolerance=1.0,RotateLabelWithDisplay=true,UnplacedLabelColor=new CIMRGBColor
{R=0,G=255,B=0,Alpha=0.5f// Green}};// Create general placement properties for Standard engine//CIMStandardGeneralPlacementProperties generalPlacementProperties =// new CIMStandardGeneralPlacementProperties// {// DrawUnplacedLabels = true,// InvertedLabelTolerance = 3.0,// RotateLabelWithDisplay = true,// UnplacedLabelColor = new CIMRGBColor// {// R = 255, G = 0, B = 0, Alpha = 0.5f // Red// } // };// Create annotation label classes// Green labelCIMLabelClassgreenLabelClass=new CIMLabelClass
{Name="Green",ExpressionTitle="Expression-Green",ExpressionEngine= LabelExpressionEngine.Arcade,Expression="$feature.OBJECTID",ID=1,Priority=0,Visibility=true,TextSymbol=new CIMSymbolReference
{Symbol=new CIMTextSymbol(){Angle=45,FontType= FontType.Type1,FontFamilyName="Tahoma",FontEffects= FontEffects.Normal,HaloSize=2.0,Symbol=new CIMPolygonSymbol
{SymbolLayers=new CIMSymbolLayer[]{new CIMSolidFill
{Color= CIMColor.CreateRGBColor(0,255,0)}},UseRealWorldSymbolSizes=true}},MaxScale=0,MinScale=0,SymbolName="TextSymbol-Green"},StandardLabelPlacementProperties=new CIMStandardLabelPlacementProperties
{AllowOverlappingLabels=true,LineOffset=1.0},MaplexLabelPlacementProperties=new CIMMaplexLabelPlacementProperties
{AlignLabelToLineDirection=true,AvoidPolygonHoles=true}};// Blue labelCIMLabelClassblueLabelClass=new CIMLabelClass
{Name="Blue",ExpressionTitle="Expression-Blue",ExpressionEngine= LabelExpressionEngine.Arcade,Expression="$feature.OBJECTID",ID=2,Priority=0,Visibility=true,TextSymbol=new CIMSymbolReference
{Symbol=new CIMTextSymbol(){Angle=45,FontType= FontType.Type1,FontFamilyName="Consolas",FontEffects= FontEffects.Normal,HaloSize=2.0,Symbol=new CIMPolygonSymbol
{SymbolLayers=new CIMSymbolLayer[]{new CIMSolidFill
{Color= CIMColor.CreateRGBColor(0,0,255)}},UseRealWorldSymbolSizes=true}},MaxScale=0,MinScale=0,SymbolName="TextSymbol-Blue"},StandardLabelPlacementProperties=new CIMStandardLabelPlacementProperties
{AllowOverlappingLabels=true,LineOffset=1.0},MaplexLabelPlacementProperties=new CIMMaplexLabelPlacementProperties
{AlignLabelToLineDirection=true,AvoidPolygonHoles=true}};// Create a list of labelsList<CIMLabelClass>labelClasses=newList<CIMLabelClass>{ greenLabelClass, blueLabelClass };// Create an annotation feature class description object to describe the feature class to createAnnotationFeatureClassDescriptionannotationFeatureClassDescription=new AnnotationFeatureClassDescription(annotationFeatureClassName, fieldDescriptions, shapeDescription,
generalPlacementProperties, labelClasses){IsAutoCreate=true,IsSymbolIDRequired=false,IsUpdatedOnShapeChange=true};// Create a SchemaBuilder objectSchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Add the creation of the Cities annotation feature class to the list of DDL tasks
schemaBuilder.Create(annotationFeatureClassDescription);// Execute the DDLboolsuccess= schemaBuilder.Build();// Inspect error messagesif(!success){IReadOnlyList<string>errorMessages= schemaBuilder.ErrorMessages;//etc.}}
Creating a feature-linked annotation feature class
publicvoidCreateFeatureLinkedAnnotationFeatureClass(Geodatabasegeodatabase,SpatialReferencespatialReference){// Creating a feature-linked annotation feature class between water pipe and valve in water distribution network// with following user defined fields// PipeName // GlobalID// Annotation feature class namestringannotationFeatureClassName="WaterPipeAnnotation";// Create user defined attribute fields for annotation feature classFieldDescriptionpipeGlobalID= FieldDescription.CreateGlobalIDField();FieldDescriptionnameFieldDescription= FieldDescription.CreateStringField("Name",255);// Create a list of all field descriptionsList<FieldDescription>fieldDescriptions=newList<FieldDescription>{ pipeGlobalID, nameFieldDescription };// Create a ShapeDescription objectShapeDescriptionshapeDescription=new ShapeDescription(GeometryType.Polygon, spatialReference);// Create general placement properties for Maplex engine CIMMaplexGeneralPlacementPropertiesgeneralPlacementProperties=new CIMMaplexGeneralPlacementProperties
{AllowBorderOverlap=true,PlacementQuality= MaplexQualityType.High,DrawUnplacedLabels=true,InvertedLabelTolerance=1.0,RotateLabelWithDisplay=true,UnplacedLabelColor=new CIMRGBColor
{R=255,G=0,B=0,Alpha=0.5f}};// Create annotation label classes// Green labelCIMLabelClassgreenLabelClass=new CIMLabelClass
{Name="Green",ExpressionTitle="Expression-Green",ExpressionEngine= LabelExpressionEngine.Arcade,Expression="$feature.OBJECTID",ID=1,Priority=0,Visibility=true,TextSymbol=new CIMSymbolReference
{Symbol=new CIMTextSymbol(){Angle=45,FontType= FontType.Type1,FontFamilyName="Tahoma",FontEffects= FontEffects.Normal,HaloSize=2.0,Symbol=new CIMPolygonSymbol
{SymbolLayers=new CIMSymbolLayer[]{new CIMSolidFill
{Color= CIMColor.CreateRGBColor(0,255,0)}},UseRealWorldSymbolSizes=true}},MaxScale=0,MinScale=0,SymbolName="TextSymbol-Green"},StandardLabelPlacementProperties=new CIMStandardLabelPlacementProperties
{AllowOverlappingLabels=true,LineOffset=1.0},MaplexLabelPlacementProperties=new CIMMaplexLabelPlacementProperties
{AlignLabelToLineDirection=true,AvoidPolygonHoles=true}};// Blue labelCIMLabelClassblueLabelClass=new CIMLabelClass
{Name="Blue",ExpressionTitle="Expression-Blue",ExpressionEngine= LabelExpressionEngine.Arcade,Expression="$feature.OBJECTID",ID=2,Priority=0,Visibility=true,TextSymbol=new CIMSymbolReference
{Symbol=new CIMTextSymbol(){Angle=45,FontType= FontType.Type1,FontFamilyName="Consolas",FontEffects= FontEffects.Normal,HaloSize=2.0,Symbol=new CIMPolygonSymbol
{SymbolLayers=new CIMSymbolLayer[]{new CIMSolidFill
{Color= CIMColor.CreateRGBColor(0,0,255)}},UseRealWorldSymbolSizes=true}},MaxScale=0,MinScale=0,SymbolName="TextSymbol-Blue"},StandardLabelPlacementProperties=new CIMStandardLabelPlacementProperties
{AllowOverlappingLabels=true,LineOffset=1.0},MaplexLabelPlacementProperties=new CIMMaplexLabelPlacementProperties
{AlignLabelToLineDirection=true,AvoidPolygonHoles=true}};// Create a list of labelsList<CIMLabelClass>labelClasses=newList<CIMLabelClass>{ greenLabelClass, blueLabelClass };// Create linked feature description// Linked feature class namestringlinkedFeatureClassName="WaterPipe";// Create fields for water pipeFieldDescriptionwaterPipeGlobalID= FieldDescription.CreateGlobalIDField();FieldDescriptionpipeName= FieldDescription.CreateStringField("PipeName",255);// Create a list of water pipe field descriptionsList<FieldDescription>pipeFieldDescriptions=newList<FieldDescription>{ waterPipeGlobalID, pipeName };// Create a linked feature class descriptionFeatureClassDescriptionlinkedFeatureClassDescription=new FeatureClassDescription(linkedFeatureClassName, pipeFieldDescriptions,new ShapeDescription(GeometryType.Polyline, spatialReference));// Create a SchemaBuilder objectSchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Add the creation of the linked feature class to the list of DDL tasksFeatureClassTokenlinkedFeatureClassToken= schemaBuilder.Create(linkedFeatureClassDescription);// Create an annotation feature class description object to describe the feature class to createAnnotationFeatureClassDescriptionannotationFeatureClassDescription=new AnnotationFeatureClassDescription(annotationFeatureClassName, fieldDescriptions, shapeDescription,
generalPlacementProperties, labelClasses,new FeatureClassDescription(linkedFeatureClassToken)){IsAutoCreate=true,IsSymbolIDRequired=false,IsUpdatedOnShapeChange=true};// Add the creation of the annotation feature class to the list of DDL tasks
schemaBuilder.Create(annotationFeatureClassDescription);// Execute the DDLboolsuccess= schemaBuilder.Build();// Inspect error messagesif(!success){IReadOnlyList<string>errorMessages= schemaBuilder.ErrorMessages;//etc.}}
Creating an annotation feature class inside feature dataset
publicvoidCreateAnnotationFeatureClassUsingExistingAnnotationFeatureClassInDataset(Geodatabasegeodatabase){// Create a Cities annotation feature class inside Places feature dataset using existing annotation feature class // Feature dataset namestringfeatureDatasetName="Places";// Annotation feature class namestringannotationFeatureClassName="CitiesAnnotation";// Create a SchemaBuilder objectSchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);// Open existing annotation feature class nameusing(AnnotationFeatureClassexistingAnnotationFeatureClass= geodatabase.OpenDataset<AnnotationFeatureClass>("ExistingAnnotationFeatureClass")){// Create Feature dataset descriptionFeatureDatasetDescriptionfeatureDatasetDescription=new FeatureDatasetDescription(featureDatasetName, existingAnnotationFeatureClass.GetDefinition().GetSpatialReference());// Add the creation of the Places dataset to DDL taskFeatureDatasetTokenfeatureDatasetToken= schemaBuilder.Create(featureDatasetDescription);// Create an annotation feature class description using existing annotation feature classAnnotationFeatureClassDescriptionannotationFeatureClassDescription=new AnnotationFeatureClassDescription(annotationFeatureClassName, existingAnnotationFeatureClass.GetDefinition()){IsAutoCreate=true,IsSymbolIDRequired=false,IsUpdatedOnShapeChange=true};// Add the creation of the Cities annotation feature class inside Places feature dataset
schemaBuilder.Create(new FeatureDatasetDescription(featureDatasetToken), annotationFeatureClassDescription);// Execute the DDLboolsuccess= schemaBuilder.Build();// Inspect error messagesif(!success){IReadOnlyList<string>errorMessages= schemaBuilder.ErrorMessages;//etc.}}}
Creating the memory geodatabase
public Geodatabase GetMemoryGeodatabase(){// Creates the default memory geodatabase if not exist or connects to an existing one if already existsGeodatabasememoryGeodatabase=new Geodatabase(new MemoryConnectionProperties());// Creates schemaSchemaBuilderschemaBuilder=new SchemaBuilder(memoryGeodatabase);
schemaBuilder.Create(new TableDescription("MyTable",newList<FieldDescription>()));
schemaBuilder.Build();returnmemoryGeodatabase;}
Spatial query filter with DE9-IM spatial relationships
publicvoidFindSpatiallyRelatedFeaturesUsingDE9IMPredicate(Geodatabasegeodatabase,FeatureClasspolygonFeatureClass,FeatureClasspolylineFeatureClass){using(RowCursorpolygonRowCursor= polygonFeatureClass.Search(new QueryFilter())){if(polygonRowCursor.MoveNext()){using(FeaturepolygonFeature= polygonRowCursor.Current as Feature){// DE9IM predicate string to find overlapping featuresstringoverlappingDE9IM="1*T***T**";SpatialQueryFilterspatialQueryFilter=new SpatialQueryFilter(){FilterGeometry= polygonFeature.GetShape(),SpatialRelationship= SpatialRelationship.Relation,SpatialRelationshipDescription=overlappingDE9IM};using(RowCursoroverlappingPolyline= polylineFeatureClass.Search(spatialQueryFilter)){while(overlappingPolyline.MoveNext()){// Overlapping polylines on the polygon}}}}}}
Check if table is versioned
publicboolIsTableVersioned(Geodatabasegeodatabase,stringtableName){using(Tabletable= geodatabase.OpenDataset<Table>(tableName)){// Check table version typeRegistrationTyperegistrationType= table.GetRegistrationType();if(registrationType== RegistrationType.Versioned){returntrue;}}returnfalse;}
Creating a table with index from scratch
publicvoidCreatingTableWithIndex(SchemaBuilderschemaBuilder){FieldDescriptionnameFieldDescription= FieldDescription.CreateStringField("Name",50);FieldDescriptionaddressFieldDescription= FieldDescription.CreateStringField("Address",200);// Creating a feature class, 'Buildings' with two fieldsTableDescriptiontableDescription=new TableDescription("Buildings",newList<FieldDescription>(){ nameFieldDescription, addressFieldDescription });// Enqueue DDL operation to create a tableTableTokentableToken= schemaBuilder.Create(tableDescription);// Creating an attribute index named as 'Idx'AttributeIndexDescriptionattributeIndexDescription=new AttributeIndexDescription("Idx",new TableDescription(tableToken),newList<string>{ nameFieldDescription.Name, addressFieldDescription.Name });// Enqueue DDL operation to create an attribute index
schemaBuilder.Create(attributeIndexDescription);// Execute build indexes operationboolisBuildSuccess= schemaBuilder.Build();}
Adding indexes in pre-existing dataset
publicvoidAddingIndexes(SchemaBuilderschemaBuilder,FeatureClassDefinitionfeatureClassDefinition){// Field names to add in the attribute indexstringfieldName= featureClassDefinition.GetFields().First(f => f.AliasName.Contains("Name")).Name;stringfieldAddress= featureClassDefinition.GetFields().First(f => f.AliasName.Contains("Address")).Name;// Creating an attribute index with index name 'Idx' and two participating fields' nameAttributeIndexDescriptionattributeIndexDescription=new AttributeIndexDescription("Idx",new TableDescription(featureClassDefinition),newList<string>{ fieldName, fieldAddress });// Enqueue DDL operation for an attribute index creation
schemaBuilder.Create(attributeIndexDescription);// Creating the spatial index SpatialIndexDescriptionspatialIndexDescription=new SpatialIndexDescription(new FeatureClassDescription(featureClassDefinition));// Enqueue DDL operation for the spatial index creation
schemaBuilder.Create(spatialIndexDescription);// Execute build indexes operationboolisBuildSuccess= schemaBuilder.Build();if(!isBuildSuccess){IReadOnlyList<string>errors= schemaBuilder.ErrorMessages;// Iterate and handle errors }}
Removing attribute index
publicvoidRemoveAttributeIndex(SchemaBuilderschemaBuilder,FeatureClassDefinitionfeatureClassDefinition,stringattributeIndexName){// Find a index to be removed
ArcGIS.Core.Data.Index indexToRemove= featureClassDefinition.GetIndexes().First(f => f.GetName().Equals(attributeIndexName));// Index description of the index to be removed AttributeIndexDescriptionindexDescriptionToRemove=new AttributeIndexDescription(indexToRemove,new TableDescription(featureClassDefinition));// Enqueue the DDL operation to remove index
schemaBuilder.Delete(indexDescriptionToRemove);// Execute the delete index operationboolisDeleteIndexSuccess= schemaBuilder.Build();}
Removing spatial index
publicvoidRemoveSpatialIndex(SchemaBuilderschemaBuilder,FeatureClassDefinitionfeatureClassDefinition){// Create a spatial description SpatialIndexDescriptionspatialIndexDescription=new SpatialIndexDescription(new FeatureClassDescription(featureClassDefinition));// Enqueue the DDL operation to remove index
schemaBuilder.Delete(spatialIndexDescription);// Execute the delete index operationboolisDeleteIndexSuccess= schemaBuilder.Build();}
Modifying domain
publicvoidModifyDomain(Geodatabasegeodatabase,stringcodedValueDomainName="Pipe"){SchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);CodedValueDomaincodedValueDomain= geodatabase.GetDomains().First(f => f.GetName().Equals(codedValueDomainName))as CodedValueDomain;CodedValueDomainDescriptioncodedValueDomainDescription=new CodedValueDomainDescription(codedValueDomain);// Update domain description
codedValueDomainDescription.Description ="Water Pipe Domain";// Adding code/value pair
codedValueDomainDescription.CodedValuePairs.Add("C","Copper");
schemaBuilder.Modify(codedValueDomainDescription);// To modify the orders of coded value domain// schemaBuilder.Modify(codedValueDomainDescription,SortBy.Name,SortOrder.Ascending);
schemaBuilder.Build();}
publicvoidDeleteDomain(Geodatabasegeodatabase,stringdomainNameToBeDeleted="PipeMaterial"){SchemaBuilderschemaBuilder=new SchemaBuilder(geodatabase);CodedValueDomaincodedValueDomain= geodatabase.GetDomains().First(f => f.GetName().Equals(domainNameToBeDeleted))as CodedValueDomain;CodedValueDomainDescriptioncodedValueDomainDescription=new CodedValueDomainDescription(codedValueDomain);// Deleting a coded value domain
schemaBuilder.Delete(codedValueDomainDescription);
schemaBuilder.Build();}
Creating table with subtypes
publicvoidCreateTableWithSubtypes(SchemaBuilderschemaBuilder){// Creating a 'Building' table with the subtype field 'BuildingType'FieldDescriptionbuildingType=new FieldDescription("BuildingType", FieldType.Integer);FieldDescriptionbuildingName=new FieldDescription("Name", FieldType.String);TableDescriptiontableDescription=new TableDescription("Building",newList<FieldDescription>{ buildingName, buildingType });// Add the building type subtype with three subtypes - Business, Marketing, Security
tableDescription.SubtypeFieldDescription =new SubtypeFieldDescription(buildingType.Name,newDictionary<int,string>{{1,"Business"},{2,"Marketing"},{3,"Security"}}){DefaultSubtypeCode=3// Assigning 'Security' building type as the default subtype};
schemaBuilder.Create(tableDescription);
schemaBuilder.Build();}
Removing subtype field designation
publicvoidDeleteSubtypeField(SchemaBuilderschemaBuilder,FeatureClassDefinitionfeatureClassDefinition){FeatureClassDescriptionfeatureClassDescription=new FeatureClassDescription(featureClassDefinition);// Set subtype field to null to remove the subtype field designation
featureClassDescription.SubtypeFieldDescription =null;
schemaBuilder.Modify(featureClassDescription);
schemaBuilder.Build();}
Modifying subtypes
publicvoidModifySubtypes(SchemaBuilderschemaBuilder,TableDefinitiontableDefinition){TableDescriptiontableDescription=new TableDescription(tableDefinition);// Remove the first subtype from the tableIReadOnlyList<Subtype>subtypes= tableDefinition.GetSubtypes();
tableDescription.SubtypeFieldDescription.Subtypes.Remove(subtypes.First().GetCode());// Adding a new subtype, 'Utility', in the existing table
tableDescription.SubtypeFieldDescription.Subtypes.Add(4,"Utility");// Assigning 'Utility' subtype as the default subtype
tableDescription.SubtypeFieldDescription.DefaultSubtypeCode =4;
schemaBuilder.Modify(tableDescription);
schemaBuilder.Build();}
Creating relationship class
publicvoidCreateRelationshipWithRelationshipRules(SchemaBuilderschemaBuilder){// Creating a 'BuildingType' table with two fields - BuildingType and BuildingTypeDescriptionFieldDescriptionbuildingType= FieldDescription.CreateIntegerField("BuildingType");FieldDescriptionbuildingTypeeDescription= FieldDescription.CreateStringField("BuildingTypeDescription",100);TableDescriptionbuildingTypeDescription=new TableDescription("BuildingType",newList<FieldDescription>(){ buildingType, buildingTypeeDescription });TableTokenbuildingtypeToken= schemaBuilder.Create(buildingTypeDescription);// Creating a 'Building' feature class with three fields - BuildingId, Address, and BuildingTypeFieldDescriptionbuildingId= FieldDescription.CreateIntegerField("BuildingId");FieldDescriptionbuildingAddress= FieldDescription.CreateStringField("Address",100);FieldDescriptionusageSubType= FieldDescription.CreateIntegerField("UsageSubtype");FeatureClassDescriptionfeatureClassDescription=new FeatureClassDescription("Building",newList<FieldDescription>{ buildingId, buildingAddress, buildingType, usageSubType },new ShapeDescription(GeometryType.Polygon, SpatialReferences.WGS84));// Set subtype details (optional)
featureClassDescription.SubtypeFieldDescription =new SubtypeFieldDescription(usageSubType.Name,newDictionary<int,string>{{1,"Marketing"},{2,"Utility"}});FeatureClassTokenbuildingToken= schemaBuilder.Create(featureClassDescription);// Creating a 1:M relationship between the 'Building' feature class and 'BuildingType' tableRelationshipClassDescriptionrelationshipClassDescription=new RelationshipClassDescription("BuildingToBuildingType",new FeatureClassDescription(buildingToken),new TableDescription(buildingtypeToken),
RelationshipCardinality.OneToMany, buildingType.Name, buildingType.Name){RelationshipType= RelationshipType.Composite
};// Adding relationship rules for the 'Marketing' subtype
relationshipClassDescription.RelationshipRuleDescriptions.Add(new RelationshipRuleDescription(1,null));
schemaBuilder.Create(relationshipClassDescription);
schemaBuilder.Build();}
Creating attributed relationship class
publicvoidCreateAttributedRelationship(SchemaBuilderschemaBuilder){// Creating a 'BuildingType' table with two fields - BuildingType and BuildingTypeDescriptionFieldDescriptionbuildingType= FieldDescription.CreateIntegerField("BuildingType");FieldDescriptionbuildingTypeeDescription= FieldDescription.CreateStringField("BuildingTypeDescription",100);TableDescriptionbuildingTypeDescription=new TableDescription("BuildingType",newList<FieldDescription>(){ buildingType, buildingTypeeDescription });TableTokenbuildingtypeToken= schemaBuilder.Create(buildingTypeDescription);// Creating a 'Building' feature class with three fields - BuildingId, Address, and BuildingTypeFieldDescriptionbuildingId= FieldDescription.CreateIntegerField("BuildingId");FieldDescriptionbuildingAddress= FieldDescription.CreateStringField("Address",100);FeatureClassDescriptionfeatureClassDescription=new FeatureClassDescription("Building",newList<FieldDescription>{ buildingId, buildingAddress, buildingType },new ShapeDescription(GeometryType.Polygon, SpatialReferences.WGS84));FeatureClassTokenbuildingToken= schemaBuilder.Create(featureClassDescription);// Creating M:M relationship between the 'Building' feature class and 'BuildingType' tableAttributedRelationshipClassDescriptionattributedRelationshipClassDescription=new AttributedRelationshipClassDescription("BuildingToBuildingType",new FeatureClassDescription(buildingToken),new TableDescription(buildingtypeToken), RelationshipCardinality.ManyToMany,"OBJECTID","BuildingID","OBJECTID","BuildingTypeID");// Adding optional attribute field in the intermediate table - 'OwnershipPercentage' field
attributedRelationshipClassDescription.FieldDescriptions.Add(FieldDescription.CreateIntegerField("OwnershipPercentage"));
schemaBuilder.Create(attributedRelationshipClassDescription);
schemaBuilder.Build();}
Add relationship rules to a relationship class
publicvoidModifyRelationshipClass(SchemaBuilderschemaBuilder,AttributedRelationshipClassDefinitionattributedRelationshipClassDefinition){AttributedRelationshipClassDescriptionattributedRelationshipClassDescription=new AttributedRelationshipClassDescription(attributedRelationshipClassDefinition);// Update the relationship split policy
attributedRelationshipClassDescription.RelationshipSplitPolicy = RelationshipSplitPolicy.UseDefault;// Add field in the intermediate table
attributedRelationshipClassDescription.FieldDescriptions.Add(FieldDescription.CreateIntegerField("RelationshipStatus"));// Add relationship rules based on subtypes,if available// Assuming origin class has subtype with code 1
attributedRelationshipClassDescription.RelationshipRuleDescriptions.Add(new RelationshipRuleDescription(1,null));// Enqueue modify operation
schemaBuilder.Modify(attributedRelationshipClassDescription);// Execute modify DDL operation
schemaBuilder.Build();}
Adding/Removing Relationship class in/out of a feature dataset
publicvoidMoveRelationshipClass(SchemaBuilderschemaBuilder,FeatureDatasetDefinitionfeatureDatasetDefinition,RelationshipClassDefinitionrelationshipClassDefinition){FeatureDatasetDescriptionfeatureDatasetDescription=new FeatureDatasetDescription(featureDatasetDefinition);RelationshipClassDescriptionrelationshipClassDescription=new RelationshipClassDescription(relationshipClassDefinition);// Remove relationship class from the feature dataset
schemaBuilder.RemoveRelationshipClass(featureDatasetDescription, relationshipClassDescription);// Add relationship class inside the feature dataset// schemaBuilder.AddRelationshipClass(featureDatasetDescription, relationshipClassDescription);
schemaBuilder.Build();}
Modifying annotation labels and symbols
publicvoidModifyAnnotationLabelAndSymbols(SchemaBuilderschemaBuilder,AnnotationFeatureClassDefinitionannotationFeatureClassDefinition){AnnotationFeatureClassDescriptionannotationFeatureClassDescription=new AnnotationFeatureClassDescription(annotationFeatureClassDefinition);IReadOnlyList<CIMLabelClass>labelClasses= annotationFeatureClassDescription.LabelClasses;// Adding a new annotation label class List<CIMLabelClass>modifiedLabelClasses=newList<CIMLabelClass>(labelClasses);
modifiedLabelClasses.Add(new CIMLabelClass(){Name="RedSymbol",TextSymbol=new CIMSymbolReference
{Symbol=new CIMTextSymbol(){Angle=45,FontType= FontType.Type1,FontFamilyName="Arial",FontEffects= FontEffects.Normal,HaloSize=2.0,Symbol=new CIMPolygonSymbol {SymbolLayers=new CIMSymbolLayer[]{new CIMSolidFill {Color= CIMColor.CreateRGBColor(255,0,0)}},UseRealWorldSymbolSizes=true}},MaxScale=0,MinScale=0,SymbolName="TextSymbol-RED"},});// Adding a new symbol
annotationFeatureClassDescription.Symbols.Add(new CIMSymbolIdentifier(){ID=1001,Name="ID_10001",Symbol=new CIMTextSymbol(){Angle=43,FontEffects= FontEffects.Subscript,FontType= FontType.TTOpenType,FontStyleName="Regular",FontFamilyName="Tahoma",TextCase= TextCase.Allcaps
}});// Modify annotation feature class AnnotationFeatureClassDescriptionmodifiedAnnotationFeatureClassDescription=new AnnotationFeatureClassDescription(annotationFeatureClassDescription.Name, annotationFeatureClassDescription.FieldDescriptions, annotationFeatureClassDescription.ShapeDescription, annotationFeatureClassDescription.GeneralPlacementProperties, modifiedLabelClasses);// Enqueue modify
schemaBuilder.Modify(modifiedAnnotationFeatureClassDescription);// DDL execute
schemaBuilder.Build();}
privatevoidModifyExistingField(SchemaBuilderschemaBuilder,TableDefinitiontableDefinition,stringfieldNameToBeModified="PropertyAddress"){Fieldfield= tableDefinition.GetFields().FirstOrDefault(f => f.Name.Contains(fieldNameToBeModified));// Update field's alias name and lengthFieldDescriptionfieldDescription=new FieldDescription(field){AliasName="Physical Property Address",Length=50};// Update the default value
fieldDescription.SetDefaultValue("123 Main St");// Enqueue modify operation
schemaBuilder.Modify(new TableDescription(tableDefinition), field.Name, fieldDescription);// Execute DDL
schemaBuilder.Build();}