ArcGIS Pro 3.8 API Reference Guide
ArcGIS.Core.Data Namespace / Geodatabase Class / OpenDataset<T> Method
The type of dataset to open.
The name of the dataset to open.
Example

In This Topic
    OpenDataset<T> Method (Geodatabase)
    In This Topic
    Gets a specific Dataset instance associated with name of type T in the geodatabase. This method must be called on the MCT. Use QueuedTask.Run.
    Syntax
    public T OpenDataset<T>( 
       string name
    )
    where T: Dataset
    Public Function OpenDataset(Of T As Dataset)( _
       ByVal name As String _
    ) As T

    Parameters

    name
    The name of the dataset to open.

    Type Parameters

    T
    The type of dataset to open.

    Return Value

    A specific Dataset instance corresponding to type T.
    Exceptions
    ExceptionDescription

    No valid geodatabase has been opened prior to calling this operation.

    -or-

    The dataset type corresponding to T is not supported (see DatasetType).

    -or-

    Using AttributedRelationshipClass as T to open a dataset whose type is actually DatasetType.RelationshipClass.

    A geodatabase-related exception has occurred. For example, the name is invalid.
    Example
    Opening datasets from Geodatabase
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        {
          using (Table table = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.EmployeeInfo"))
          {
          }
    
          // Open a featureClass (within a feature dataset or outside a feature dataset).
          using (FeatureClass featureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.AddressPoint"))
          {
          }
    
          // Open a FeatureClass as a Table which will return the Table reference.
          using (Table featureClassAsTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.AddressPoint"))
          {
            // But it is really a FeatureClass object.
            FeatureClass featureClassOpenedAsTable = featureClassAsTable as FeatureClass;
          }
    
          // Open a FeatureDataset.
          using (FeatureDataset featureDataset = geodatabase.OpenDataset<FeatureDataset>("LocalGovernment.GDB.Address"))
          {
          }
    
          // Open a RelationshipClass.  Just as you can open a FeatureClass as a Table, you can also open an AttributedRelationshipClass as a RelationshipClass.
          using (RelationshipClass relationshipClass = geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.AddressPointHasSiteAddresses"))
          {
          }
        }
      });
    }
    Opening datasets from a Feature Service by Layer ID
    {
      //Url examples for (federated) feature services
      //(federated by ref on portal)
      var url =
          @"https://portal.example.com/server/rest/services/FeatureServiceName/FeatureServer";
      //(federated by value - Hosted - on portal)
      //https://portal.example.com/server/rest/services/Hosted/FeatureServiceName/FeatureServer
    
      await QueuedTask.Run(() =>
      {
        var uri = new Uri(url, UriKind.Absolute);
        using (var fs_db = new ArcGIS.Core.Data.Geodatabase(new ServiceConnectionProperties(uri)))
        {
          using (FeatureClass featureClass = fs_db.OpenDataset<FeatureClass>("0"))
          {
            // Use the feature class opened from layer ID 0.
          }
    
          using (Table table = fs_db.OpenDataset<Table>("4"))
          {
            // Use the table opened from layer ID 4.
          }
    
          using (AttributedRelationshipClass attributedRelationshipClass =
              fs_db.OpenDataset<AttributedRelationshipClass>("5"))
          {
            // Use the attributed relationship class opened from layer ID 5.
          }
    
          try
          {
            string idOfLayerWhichIsNotTable = "3";
            fs_db.OpenDataset<Table>(idOfLayerWhichIsNotTable);
          }
          catch (InvalidOperationException)
          {
            // Handle Exception.
          }
        }
      });
    }
    Searching a Table using QueryFilter
    {
      await QueuedTask.Run(() =>
      {
        try
        {
          using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
          using (Table table = geodatabase.OpenDataset<Table>("EmployeeInfo"))
          {
            QueryFilter queryFilter = new QueryFilter
            {
              WhereClause = "COSTCTRN = 'Information Technology'",
              SubFields = "KNOWNAS, OFFICE, LOCATION",
              PostfixClause = "ORDER BY OFFICE"
            };
    
            using (RowCursor rowCursor = table.Search(queryFilter, false))
            {
              while (rowCursor.MoveNext())
              {
                using (Row row = rowCursor.Current)
                {
                  string location = Convert.ToString(row["LOCATION"]);
                  string knownAs = Convert.ToString(row["KNOWNAS"]);
                }
              }
            }
          }
        }
        catch (GeodatabaseFieldException fieldException)
        {
          // One of the fields in the where clause might not exist. There are multiple ways this can be handled:
          // Handle error appropriately
        }
      });
    }
    Searching a Table for non-Latin characters
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (Table table = geodatabase.OpenDataset<Table>("TableWithChineseCharacters"))
        {
          // This will fail with many database systems that expect Latin characters by default
          string incorrectWhereClause = "颜色 = '绿'";
    
          // 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 class
          string nationalStringPrefix = "";
          SQLSyntax sqlSyntax = geodatabase.GetSQLSyntax();
          nationalStringPrefix = sqlSyntax.GetSupportedStrings(SQLStringType.NationalStringPrefix).First();
    
          // This Where clause will work
          QueryFilter queryFilter = new QueryFilter()
          {
            WhereClause = "颜色 = " + nationalStringPrefix + "'绿'"
          };
        }
      });
    }
    Searching a FeatureClass using SpatialQueryFilter
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (FeatureClass schoolBoundaryFeatureClass = 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.
          SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter
          {
            WhereClause = "DISTRCTNAME = 'Indian Prairie School District 204'",
            FilterGeometry = new PolygonBuilderEx(new List<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 (RowCursor indianPrairieCursor = schoolBoundaryFeatureClass.Search(spatialQueryFilter, false))
          {
            while (indianPrairieCursor.MoveNext())
            {
              using (Feature feature = (Feature)indianPrairieCursor.Current)
              {
                // Process the feature. For example...
                Console.WriteLine(feature.GetObjectID());
              }
            }
          }
        }
      });
    }
    Selecting Rows from a Table
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (Table enterpriseTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost"))
        {
          QueryFilter anotherQueryFilter = new QueryFilter { WhereClause = "FLOOR = 1 AND WING = 'E'" };
    
          // For Selecting all matching entries.
          using (Selection anotherSelection = 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 (Selection onlyOneSelection = enterpriseTable.Select(anotherQueryFilter, SelectionType.ObjectID, SelectionOption.OnlyOne))
          {
          }
    
          // This can be used to obtain a empty selection which can be used as a container to combine results from different selections.
          using (Selection emptySelection = enterpriseTable.Select(anotherQueryFilter, SelectionType.ObjectID, SelectionOption.Empty))
          {
          }
    
          // If you want to select all the records in a table.
          using (Selection allRecordSelection = enterpriseTable.Select(null, SelectionType.ObjectID, SelectionOption.Normal))
          {
          }
        }
      });
    }
    Selecting Features from a FeatureClass
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite"))
        {
          List<Coordinate2D> newCoordinates = new List<Coordinate2D>
          {
            new Coordinate2D(1021570, 1880583),
            new Coordinate2D(1028730, 1880994),
            new Coordinate2D(1029718, 1875644),
            new Coordinate2D(1021405, 1875397)
          };
    
          SpatialQueryFilter spatialFilter = new SpatialQueryFilter
          {
            WhereClause = "FCODE = 'Park'",
            FilterGeometry = new PolygonBuilderEx(newCoordinates).ToGeometry(),
            SpatialRelationship = SpatialRelationship.Crosses
          };
    
          // For Selecting all matching entries.
          using (Selection anotherSelection = 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 (Selection onlyOneSelection = enterpriseFeatureClass.Select(spatialFilter, SelectionType.ObjectID, SelectionOption.OnlyOne))
          {
          }
    
          // This can be used to obtain an empty selction which can be used as a container to combine results from different selections.
          using (Selection emptySelection = enterpriseFeatureClass.Select(spatialFilter, SelectionType.ObjectID, SelectionOption.Empty))
          {
          }
    
          // If you want to select all the records in a table.
          using (Selection allRecordSelection = enterpriseFeatureClass.Select(null, SelectionType.ObjectID, SelectionOption.Normal))
          {
          }
        }
      });
    }
    Using SQLSyntax to form platform agnostic queries
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("C:\\Data\\LocalGovernment.gdb"))))
        using (FeatureClass featureClass = geodatabase.OpenDataset<FeatureClass>("FacilitySite"))
        {
          SQLSyntax sqlSyntax = geodatabase.GetSQLSyntax();
          string substringFunctionName = sqlSyntax.GetFunctionName(SQLFunction.Substring);
          string upperFunctionName = sqlSyntax.GetFunctionName(SQLFunction.Upper);
          string substringfunction = string.Format("{0}({1}(FCODE, 1, 6)) = 'SCHOOL'", upperFunctionName,
            substringFunctionName);
    
          QueryFilter queryFilter = new QueryFilter
          {
            WhereClause = substringfunction
          };
          using (Selection selection =
                 featureClass.Select(queryFilter, SelectionType.ObjectID, SelectionOption.Normal))
          {
            // work with the selection.
          }
        }
      });
    }
    Fulltext search query
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (Table table = geodatabase.OpenDataset<Table>("WaterPipeInfo"))
        using (TableDefinition tableDefinition = table.GetDefinition())
        {
          bool supportsFullText = geodatabase.GetDatastoreProperties().SupportsFullTextIndex;
          if (!supportsFullText)
          {
            return;
          }
    
          IReadOnlyList<Index> indexes = tableDefinition.GetIndexes();
          IReadOnlyList<Field> fieldsToSearch = indexes.First().GetFields();
    
          FullTextSearchTermExpression searchRepairStatus = new FullTextSearchTermExpression()
          {
            SearchFields = fieldsToSearch[0].Name,
            SearchTerm = "Repaired",
            SearchType = FullTextSearchType.Simple
          };
    
          FullTextSearchTermExpression searchPipeMaterial = new FullTextSearchTermExpression()
          {
            SearchFields = fieldsToSearch[1].Name,
            SearchTerm = "Copper",
            SearchType = FullTextSearchType.Simple
          };
    
          FullTextOrExpression repairedOrCopperEx = new FullTextOrExpression(searchRepairStatus, searchPipeMaterial);
    
          QueryFilter queryfilter = new QueryFilter
          {
            FullTextExpression = repairedOrCopperEx,
            Offset = 1,
            RowCount = 20,
            PostfixClause = "Order By Size"
          };
    
          using (RowCursor rowCursor = table.Search(queryfilter, false))
          {
            // Use row cursor ...
          }
        }
      });
    }
    Joining a file geodatabase feature class to an Oracle database query layer feature class with a virtual relationship class
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("C:\\Data\\LocalGovernment.gdb"))))
        using (Database database = new Database(new DatabaseConnectionProperties(EnterpriseDatabaseType.Oracle)
        {
          AuthenticationMode = AuthenticationMode.DBMS,
          Instance = "instance",
          User = "user",
          Password = "password",
          Database = "database"
        }))
    
        using (FeatureClass leftFeatureClass = geodatabase.OpenDataset<FeatureClass>("Hospital"))
        using (Table rightTable = database.OpenTable(database.GetQueryDescription("FacilitySite")))
        {
          Field originPrimaryKey = leftFeatureClass.GetDefinition().GetFields()
            .FirstOrDefault(field => field.Name.Equals("facilityId"));
    
          Field destinationForeignKey = rightTable.GetDefinition().GetFields()
            .FirstOrDefault(field => field.Name.Equals("hospitalID"));
    
          VirtualRelationshipClassDescription description = new VirtualRelationshipClassDescription(
            originPrimaryKey, destinationForeignKey, RelationshipCardinality.OneToOne);
    
          using (RelationshipClass relationshipClass = leftFeatureClass.RelateTo(rightTable, description))
          {
            JoinDescription joinDescription = new JoinDescription(relationshipClass)
            {
              JoinDirection = JoinDirection.Forward,
              JoinType = JoinType.LeftOuterJoin
            };
    
            Join join = new Join(joinDescription);
    
            using (Table joinedTable = join.GetJoinedTable())
            {
              // Perform operation on joined table.
            }
          }
        }
      });
    }
    Joining two tables from different geodatabases
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase sourceGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("Path \\ to \\Geodatabase \\ one"))))
        using (Geodatabase destinationGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri("Path \\ to \\Geodatabase \\ two"))))
        using (Table sourceTable = sourceGeodatabase.OpenDataset<Table>("State"))
        using (Table destinationTable = destinationGeodatabase.OpenDataset<Table>("Cities"))
        {
          Field primaryKeyField = sourceTable.GetDefinition().GetFields()
            .FirstOrDefault(field => field.Name.Equals("State.State_Abbreviation"));
          Field foreignKeyField = destinationTable.GetDefinition().GetFields()
            .FirstOrDefault(field => field.Name.Equals("Cities.State"));
    
          VirtualRelationshipClassDescription virtualRelationshipClassDescription = new VirtualRelationshipClassDescription(primaryKeyField, foreignKeyField,
              RelationshipCardinality.OneToMany);
    
          using (RelationshipClass relationshipClass = sourceTable.RelateTo(destinationTable, virtualRelationshipClassDescription))
          {
            JoinDescription joinDescription = new JoinDescription(relationshipClass)
            {
              JoinDirection = JoinDirection.Forward,
              JoinType = JoinType.InnerJoin,
              TargetFields = sourceTable.GetDefinition().GetFields()
            };
    
            using (Join join = new Join(joinDescription))
            {
              Table joinedTable = join.GetJoinedTable();
    
              //Process the joined table. For example ..
              using (RowCursor cursor = joinedTable.Search())
              {
                while (cursor.MoveNext())
                {
                  using (Row row = cursor.Current)
                  {
                    // Use Row
                  }
                }
              }
            }
          }
        }
      });
    }
    Illustrate version conflict information from a reconcile operation
    {
      Task GetVersionConflictsInfoInUpdateDeleteTypeAsync(
        ServiceConnectionProperties featureServiceConnectionProperties,
        string featureClassName) => QueuedTask.Run(() =>
      {
        // To illustrate the conflict between versions,
        // the feature is updated in the child version and deleted in the parent version.
    
        long featureObjectIDForEdit = Int64.MinValue;
    
        // Get branch versioned service
        using (Geodatabase fsGeodatabase = new Geodatabase(featureServiceConnectionProperties))
        using (VersionManager versionManager = fsGeodatabase.GetVersionManager())
        using (Version defaultVersion = versionManager.GetDefaultVersion())
        using (Geodatabase defaultGeodatabase = defaultVersion.Connect())
        using (FeatureClass defaultFeatureClass = defaultGeodatabase.OpenDataset<FeatureClass>(featureClassName))
        using (FeatureClassDefinition defaultFeatureClassDefinition = defaultFeatureClass.GetDefinition())
        {
          // Create a feature in the default version to edit in a branch
          defaultGeodatabase.ApplyEdits(() =>
          {
            using (RowBuffer rowBuffer = defaultFeatureClass.CreateRowBuffer())
            {
              rowBuffer["NAME"] = "Loblolly Pine";
              rowBuffer["TREEAGE"] = 1;
              rowBuffer[defaultFeatureClassDefinition.GetShapeField()] = new MapPointBuilderEx(new Coordinate2D(1, 1),
                SpatialReferenceBuilder.CreateSpatialReference(4152, 0)).ToGeometry();
    
              using (Feature feature = defaultFeatureClass.CreateRow(rowBuffer))
              {
                featureObjectIDForEdit = feature.GetObjectID();
              }
            }
          });
          // Add newly created feature in the filter
          QueryFilter queryFilter = new QueryFilter { ObjectIDs = new List<long> { featureObjectIDForEdit } };
    
          // Create a branch version
          VersionDescription versionDescription = new VersionDescription("UpdateDeleteConflictType",
            "Update-Delete version conflict type", VersionAccessType.Public);
    
          // Edit the feature in the branch
          using (Version editVersion = versionManager.CreateVersion(versionDescription))
          using (Geodatabase branchGeodatabase = editVersion.Connect())
          using (FeatureClass featureClass = branchGeodatabase.OpenDataset<FeatureClass>(featureClassName))
          using (RowCursor rowCursor = featureClass.Search(queryFilter, false))
          {
            branchGeodatabase.ApplyEdits(() =>
            {
              while (rowCursor.MoveNext())
              {
                using (Row row = rowCursor.Current)
                {
                  row["TREEAGE"] = 100;
                  row["NAME"] = $"{row["Name"]}_EditInBranch";
                  row.Store();
                }
              }
            });
    
            // Delete the feature from the default version
            defaultGeodatabase.ApplyEdits(() =>
            {
              defaultFeatureClass.DeleteRows(queryFilter);
            });
    
            // Reconcile options
            ReconcileOptions reconcileOptions = new ReconcileOptions(defaultVersion)
            {
              ConflictResolutionType = ConflictResolutionType.FavorEditVersion,
              ConflictDetectionType = ConflictDetectionType.ByRow,
              ConflictResolutionMethod = ConflictResolutionMethod.Continue
            };
    
            // Reconcile with default
            ReconcileResult reconcileResult = editVersion.Reconcile(reconcileOptions);
    
            // Check for conflicts
            bool hasConflictsReconcileResults = reconcileResult.HasConflicts;
            bool hasConflictsAfterReconcile = editVersion.HasConflicts();
    
            // Fetch conflicts
            IReadOnlyList<Conflict> conflictsAfterReconcile = editVersion.GetConflicts();
    
            // Iterate conflicts
            foreach (Conflict conflict in conflictsAfterReconcile)
            {
              // Object ID of row where conflict occurs
              long objectId = conflict.ObjectID;
    
              ConflictType conflictType = conflict.ConflictType;
    
              IReadOnlyList<FieldValue> ancestorVersionValues = conflict.AncestorVersionValues;
              object nameAncestor = ancestorVersionValues.FirstOrDefault(f => f.FieldName.Contains("NAME")).Value;
              object treeAgeAncestor =
                ancestorVersionValues.FirstOrDefault(f => f.FieldName.Contains("TREEAGE")).Value;
    
              IReadOnlyList<FieldValue> childVersionValues = conflict.ChildVersionValues;
              object nameChild = childVersionValues.FirstOrDefault(f => f.FieldName.Contains("NAME")).Value;
              object treeAgeChild = childVersionValues.FirstOrDefault(f => f.FieldName.Contains("TREEAGE")).Value;
    
              IReadOnlyList<FieldValue> parentVersionValues = conflict.ParentVersionValues;
    
              IReadOnlyList<Field> originalFields = defaultFeatureClassDefinition.GetFields();
    
              string datasetName = conflict.DatasetName;
            }
          }
        }
      });
    }
    Creating a Row
    {
      await QueuedTask.Run(() =>
      {
        string message = String.Empty;
        bool creationResult = false;
        EditOperation editOperation = new EditOperation();
    
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (Table enterpriseTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost"))
        {
          // Declare the callback here. We are not executing it .yet.
          editOperation.Callback(context =>
          {
            TableDefinition tableDefinition = enterpriseTable.GetDefinition();
            int assetNameIndex = tableDefinition.FindField("ASSETNA");
    
            using (RowBuffer rowBuffer = enterpriseTable.CreateRowBuffer())
            {
              // Either the field index or the field name can be used in the indexer.
              rowBuffer[assetNameIndex] = "wMain";
              rowBuffer["COST"] = 700;
              rowBuffer["ACTION"] = "Open Cut";
    
              // subtype value for "Abandon".
              rowBuffer[tableDefinition.GetSubtypeField()] = 3;
    
              using (Row row = 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 (GeodatabaseException exObj)
          {
            message = exObj.Message;
          }
        }
    
        if (!string.IsNullOrEmpty(message))
        {
          Debug.WriteLine(message);
        }
      });
    }
    Creating a Feature
    {
      await QueuedTask.Run(() =>
      {
        string message = String.Empty;
        bool creationResult = false;
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite"))
        {
          //Declare the callback here. We are not executing it yet
          EditOperation editOperation = new EditOperation();
          editOperation.Callback(context =>
          {
            FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition();
            int facilityIdIndex = facilitySiteDefinition.FindField("FACILITYID");
    
            using (RowBuffer rowBuffer = 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   Attractions Subtype.
              rowBuffer[facilitySiteDefinition.GetSubtypeField()] = 820;
    
              List<Coordinate2D> newCoordinates = new List<Coordinate2D>
              {
                  new Coordinate2D(1021570, 1880583),
                  new Coordinate2D(1028730, 1880994),
                  new Coordinate2D(1029718, 1875644),
                  new Coordinate2D(1021405, 1875397)
              };
    
              rowBuffer[facilitySiteDefinition.GetShapeField()] = new PolygonBuilderEx(newCoordinates).ToGeometry();
    
              using (Feature feature = 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 (GeodatabaseException exObj)
          {
            message = exObj.Message;
          }
        }
    
        if (!string.IsNullOrEmpty(message))
        {
          Debug.WriteLine(message);
        }
      });
    }
    Modifying a Row
    {
      await QueuedTask.Run(() =>
      {
        string message = String.Empty;
        bool modificationResult = false;
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (Table enterpriseTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost"))
        {
          EditOperation editOperation = new EditOperation();
          editOperation.Callback(context =>
          {
            QueryFilter openCutFilter = new QueryFilter { WhereClause = "ACTION = 'Open Cut'" };
    
            using (RowCursor rowCursor = enterpriseTable.Search(openCutFilter, false))
            {
              TableDefinition tableDefinition = enterpriseTable.GetDefinition();
              int subtypeFieldIndex = tableDefinition.FindField(tableDefinition.GetSubtypeField());
    
              while (rowCursor.MoveNext())
              {
                using (Row row = rowCursor.Current)
                {
                  // In order to update the Map and/or the attribute table.
                  // Has to be called before any changes are made to the row.
                  context.Invalidate(row);
    
                  row["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 (GeodatabaseException exObj)
          {
            message = exObj.Message;
          }
        }
    
        if (!string.IsNullOrEmpty(message))
        {
          Debug.WriteLine(message);
        }
      });
    }
    Modifying a Feature
    {
      await QueuedTask.Run(() =>
      {
        string message = String.Empty;
        bool modificationResult = false;
    
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite"))
        {
          FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition();
    
          int ownTypeIndex = facilitySiteDefinition.FindField("OWNTYPE");
          int areaIndex = facilitySiteDefinition.FindField(facilitySiteDefinition.GetAreaField());
    
          EditOperation editOperation = new EditOperation();
          editOperation.Callback(context =>
          {
            QueryFilter queryFilter = new QueryFilter
            {
              WhereClause = "FCODE = 'Hazardous Materials Facility' AND OWNTYPE = ' '"
            };
    
            using (RowCursor rowCursor = enterpriseFeatureClass.Search(queryFilter, false))
            {
              while (rowCursor.MoveNext())
              {
                using (Feature feature = (Feature)rowCursor.Current)
                {
                  // In order to update the Map and/or the attribute table.
                  // Has to be called before any changes are made to the row
                  context.Invalidate(feature);
    
                  // Transfer all Hazardous Material Facilities to the City.
                  feature[ownTypeIndex] = "Municipal";
    
                  if (Convert.ToDouble(feature[areaIndex]) > 50000)
                  {
                    // Set the Shape of the feature to whatever you need.
                    List<Coordinate2D> newCoordinates = new List<Coordinate2D>
                    {
                        new Coordinate2D(1021570, 1880583),
                        new Coordinate2D(1028730, 1880994),
                        new Coordinate2D(1029718, 1875644),
                        new Coordinate2D(1021405, 1875397)
                    };
    
                    feature.SetShape(new 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 (GeodatabaseException exObj)
          {
            message = exObj.Message;
          }
        }
    
        if (!string.IsNullOrEmpty(message))
        {
          Debug.WriteLine(message);
        }
      });
    }
    Deleting a Row/Feature
    {
      await QueuedTask.Run(() =>
      {
        string message = String.Empty;
        bool deletionResult = false;
    
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (Table enterpriseTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.piCIPCost"))
        {
          EditOperation editOperation = new EditOperation();
          editOperation.Callback(context =>
          {
            QueryFilter openCutFilter = new QueryFilter { WhereClause = "ACTION = 'Open Cut'" };
    
            using (RowCursor rowCursor = enterpriseTable.Search(openCutFilter, false))
            {
              while (rowCursor.MoveNext())
              {
                using (Row row = rowCursor.Current)
                {
                  // In order to update the Map and/or the attribute table. Has to be called before the delete.
                  context.Invalidate(row);
    
                  row.Delete();
                }
              }
            }
          }, enterpriseTable);
    
          try
          {
            deletionResult = editOperation.Execute();
            if (!deletionResult)
            {
              message = editOperation.ErrorMessage;
            }
          }
          catch (GeodatabaseException exObj)
          {
            message = exObj.Message;
          }
        }
    
        if (!string.IsNullOrEmpty(message))
        {
          Debug.WriteLine(message);
        }
      });
    }
    Adding Attachments
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (FeatureClass parkFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.Park"))
        {
          QueryFilter filter = new QueryFilter { WhereClause = "NUMPARKING > 0" };
    
          using (RowCursor parkingCursor = parkFeatureClass.Search(filter, false))
          {
            while (parkingCursor.MoveNext())
            {
              using (MemoryStream stream = CreateMemoryStreamFromContentsOf("Sample.xml"))
              {
                Attachment attachment = new Attachment("Sample.xml", "text/xml", stream);
    
                using (Row row = parkingCursor.Current)
                {
                  long attachmentId = row.AddAttachment(attachment);
                }
              }
            }
          }
        }
      });
      // Helper method to read a file into a memory stream
      MemoryStream CreateMemoryStreamFromContentsOf(String fileNameWithPath)
      {
        MemoryStream memoryStream = new MemoryStream();
    
        using (FileStream file = new FileStream(fileNameWithPath, FileMode.Open, FileAccess.Read))
        {
          byte[] bytes = new byte[file.Length];
          file.Read(bytes, 0, (int)file.Length);
          memoryStream.Write(bytes, 0, (int)file.Length);
        }
    
        return memoryStream;
      }
    }
    Updating Attachments
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (FeatureClass landUseCaseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.LandUseCase"))
        {
          QueryFilter filter = new QueryFilter { WhereClause = "CASETYPE = 'Rezoning'" };
    
          using (RowCursor landUseCursor = landUseCaseFeatureClass.Search(filter, false))
          {
            while (landUseCursor.MoveNext())
            {
              using (Feature rezoningUseCase = (Feature)landUseCursor.Current)
              {
                IReadOnlyList<Attachment> rezoningAttachments = rezoningUseCase.GetAttachments();
                IEnumerable<Attachment> filteredAttachments = rezoningAttachments.Where(attachment => !attachment.GetName().Contains("rezoning"));
    
                foreach (Attachment attachmentToUpdate in filteredAttachments)
                {
                  attachmentToUpdate.SetName(attachmentToUpdate.GetName().Replace(".pdf", "Rezoning.pdf"));
                  rezoningUseCase.UpdateAttachment(attachmentToUpdate);
                }
              }
            }
          }
        }
      });
    }
    Deleting Attachments
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file\\sdefile.sde"))))
        using (Table inspectionTable = geodatabase.OpenDataset<Table>("luCodeInspection"))
        {
          QueryFilter queryFilter = new QueryFilter { WhereClause = "ACTION = '1st Notice'" };
    
          using (RowCursor cursor = inspectionTable.Search(queryFilter, false))
          {
            while (cursor.MoveNext())
            {
              using (Row currentRow = cursor.Current)
              {
                IReadOnlyList<Attachment> rowAttachments = currentRow.GetAttachments(null, true);
                IEnumerable<Attachment> attachments = rowAttachments.Where(attachment =>
                  attachment.GetContentType().Equals("application/pdf"));
    
                IReadOnlyList<long> attachmentIDs =
                  attachments.Select(attachment => attachment.GetAttachmentID()) as IReadOnlyList<long>;
                IReadOnlyDictionary<long, Exception> failures = currentRow.DeleteAttachments(attachmentIDs);
    
                if (failures.Count > 0)
                {
                  //process errors
                }
              }
            }
          }
        }
      });
    }
    Getting Rows related by RelationshipClass
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
        using (RelationshipClass relationshipClass = geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.luCodeViolationHasInspections"))
        using (FeatureClass violationsFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.luCodeViolation"))
        using (Table inspectionTable = geodatabase.OpenDataset<Table>("LocalGovernment.GDB.luCodeInspection"))
        {
          List<Row> jeffersonAveViolations = new List<Row>();
          QueryFilter queryFilter = new QueryFilter { WhereClause = "LOCDESC LIKE '%Jefferson%'" };
    
          using (RowCursor rowCursor = violationsFeatureClass.Search(queryFilter, false))
          {
            while (rowCursor.MoveNext())
            {
              jeffersonAveViolations.Add(rowCursor.Current);
            }
          }
    
          IReadOnlyList<Row> relatedOriginRows = null;
          IReadOnlyList<Row> relatedDestinationRows = null;
    
          try
          {
            QueryFilter filter = new QueryFilter { WhereClause = "ACTION = '1st Notice'" };
    
            using (Selection selection = inspectionTable.Select(filter, SelectionType.ObjectID, SelectionOption.Normal))
            {
              relatedOriginRows = relationshipClass.GetRowsRelatedToDestinationRows(selection.GetObjectIDs());
            }
    
            bool containsJeffersonAve = relatedOriginRows.Any(row => Convert.ToString(row["LOCDESC"]).Contains("Jefferson"));
    
            List<long> jeffersonAveViolationObjectIds = jeffersonAveViolations.Select(row => row.GetObjectID()).ToList();
    
            relatedDestinationRows = relationshipClass.GetRowsRelatedToOriginRows(jeffersonAveViolationObjectIds);
            bool hasFirstNoticeInspections = relatedDestinationRows.Any(row => Convert.ToString(row["ACTION"]).Contains("1st Notice"));
          }
          finally
          {
            Dispose(jeffersonAveViolations);
            Dispose(relatedOriginRows);
            Dispose(relatedDestinationRows);
          }
        }
      });
    
      void Dispose(IEnumerable<Row> rows)
      {
        foreach (Row row in rows)
        {
          row.Dispose();
        }
      }
    }
    Creating a Relationship
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
        using (RelationshipClass relationshipClass = geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.OverviewToProject"))
        using (FeatureClass projectsFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.CIPProjects"))
        using (FeatureClass overviewFeatureClass = 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.
          string originKeyField = relationshipClass.GetDefinition().GetOriginKeyField();
    
          EditOperation editOperation = 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 (RowBuffer projectsRowBuffer = projectsFeatureClass.CreateRowBuffer())
            using (RowBuffer overviewRowBuffer = overviewFeatureClass.CreateRowBuffer())
            {
              projectsRowBuffer["TOTCOST"] = 500000;
    
              overviewRowBuffer[originKeyField] = "LibraryConstruction";
              overviewRowBuffer["PROJECTMAN"] = "John Doe";
              overviewRowBuffer["FUNDSOUR"] = " ";
    
              using (Row projectsRow = projectsFeatureClass.CreateRow(projectsRowBuffer))
              using (Row overviewRow = overviewFeatureClass.CreateRow(overviewRowBuffer))
              {
                Relationship relationship = 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);
    
          bool editResult = editOperation.Execute();
        }
      });
    }
    Deleting a Relationship
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
        using (RelationshipClass relationshipClass = geodatabase.OpenDataset<RelationshipClass>("LocalGovernment.GDB.luCodeViolationHasInspections"))
        using (FeatureClass violationsFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.luCodeViolation"))
        {
          QueryFilter queryFilter = new QueryFilter { WhereClause = "LOCDESC LIKE '%Jefferson%'" };
    
          using (RowCursor rowCursor = violationsFeatureClass.Search(queryFilter, false))
          {
            if (!rowCursor.MoveNext())
            {
              return;
            }
    
            using (Row jeffersonAveViolation = rowCursor.Current)
            {
              IReadOnlyList<Row> relatedDestinationRows = relationshipClass.GetRowsRelatedToOriginRows(new List<long>
                  { jeffersonAveViolation.GetObjectID() });
    
              try
              {
                EditOperation editOperation = new EditOperation();
                editOperation.Callback(context =>
                {
                  foreach (Row relatedDestinationRow in relatedDestinationRows)
                  {
                    try
                    {
                      relationshipClass.DeleteRelationship(jeffersonAveViolation, relatedDestinationRow);
                    }
                    catch (GeodatabaseRelationshipClassException exception)
                    {
                      Console.WriteLine(exception);
                    }
                  }
                }, relationshipClass);
    
                bool editResult = editOperation.Execute();
              }
              finally
              {
                foreach (Row row in relatedDestinationRows)
                {
                  row.Dispose();
                }
              }
            }
          }
        }
      });
    }
    Using an Insert Cursor
    {
      // Insert Cursors are intended for use in CoreHost applications, not Pro Add-ins
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
        using (Table citiesTable = geodatabase.OpenDataset<Table>("name\\of\\cities_table"))
        {
          geodatabase.ApplyEdits(() =>
          {
            using (InsertCursor insertCursor = citiesTable.CreateInsertCursor())
            using (RowBuffer rowBuffer = 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
    {
      Task CreatingAnAnnotationFeatureAsync(Geodatabase geodatabase) => QueuedTask.Run(() =>
      {
        using (AnnotationFeatureClass annotationFeatureClass = geodatabase.OpenDataset<AnnotationFeatureClass>("Annotation // feature // class // name"))
        using (AnnotationFeatureClassDefinition annotationFeatureClassDefinition = annotationFeatureClass.GetDefinition())
        using (RowBuffer rowBuffer = annotationFeatureClass.CreateRowBuffer())
        using (AnnotationFeature annotationFeature = annotationFeatureClass.CreateRow(rowBuffer))
        {
          annotationFeature.SetAnnotationClassID(0);
          annotationFeature.SetStatus(AnnotationStatus.Placed);
    
          // Get the annotation labels from the label collection
          IReadOnlyList<CIMLabelClass> labelClasses =
            annotationFeatureClassDefinition.GetLabelClassCollection();
    
          // Setup the symbol reference with the symbol id and the text symbol
          CIMSymbolReference cimSymbolReference = new CIMSymbolReference();
          cimSymbolReference.Symbol = labelClasses[0].TextSymbol.Symbol;
          cimSymbolReference.SymbolName = labelClasses[0].TextSymbol.SymbolName;
    
          // Setup the text graphic
          CIMTextGraphic cimTextGraphic = 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();
        }
      });
    }
    Working with Versions
    {
      await QueuedTask.Run(() =>
      {
        using (Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri("path\\to\\sde\\file"))))
        using (VersionManager versionManager = geodatabase.GetVersionManager())
        {
          IReadOnlyList<string> versionNames = versionManager.GetVersionNames();
    
          Version defaultVersion = versionManager.GetDefaultVersion();
    
          string testVersionName = versionNames.First(v => v.Contains("Test"));
          Version testVersion = versionManager.GetVersion(testVersionName);
    
          Version qaVersion = defaultVersion.GetChildren().First(version => version.GetName().Contains("QA"));
    
          Geodatabase qaVersionGeodatabase = qaVersion.Connect();
    
          FeatureClass currentFeatureClass = geodatabase.OpenDataset<FeatureClass>("featureClassName");
          FeatureClass qaFeatureClass = qaVersionGeodatabase.OpenDataset<FeatureClass>("featureClassName");
        }
      });
    }
    Iterate datasets inside a feature dataset
    {
      Task IterateDatasetsFromAFeatureDatasetAsync(Geodatabase geodatabase, string featureDatasetName = "City", string featureClassInFeatureDataset = "Buildings") => QueuedTask.Run(() =>
      {
        // Open a feature dataset
        using (FeatureDataset cityFeatureDataset = geodatabase.OpenDataset<FeatureDataset>(featureDatasetName))
        {
          // Get a feature class definition from a feature dataset
          FeatureClassDefinition buildingsFeatureClassDefinition = cityFeatureDataset.GetDefinition<FeatureClassDefinition>(featureClassInFeatureDataset);
    
          // Iterate dataset definition
          IReadOnlyList<FeatureClassDefinition> cityFeatureClassDefinitions = cityFeatureDataset.GetDefinitions<FeatureClassDefinition>();
          foreach (FeatureClassDefinition cityFeatureClassDefinition in cityFeatureClassDefinitions)
          {
            // Use feature class definition ...
          }
        }
      });
    }
    Creating an annotation feature class inside feature dataset
    {
      Task CreateAnnotationFeatureClassUsingExistingAnnotationFeatureClassInDatasetAsync(
        Geodatabase geodatabase) => QueuedTask.Run(() =>
      {
        // Create a Cities annotation feature class inside Places feature dataset using existing annotation feature class
    
        // Feature dataset name
        string featureDatasetName = "Places";
    
        // Annotation feature class name
        string annotationFeatureClassName = "CitiesAnnotation";
    
        // Create a SchemaBuilder object
        SchemaBuilder schemaBuilder = new SchemaBuilder(geodatabase);
    
        // Open existing annotation feature class name
        using (AnnotationFeatureClass existingAnnotationFeatureClass = geodatabase.OpenDataset<AnnotationFeatureClass>("ExistingAnnotationFeatureClass"))
        {
          // Create Feature dataset description
          FeatureDatasetDescription featureDatasetDescription = new FeatureDatasetDescription(featureDatasetName, existingAnnotationFeatureClass.GetDefinition().GetSpatialReference());
    
          // Add the creation of the Places dataset to DDL task
          FeatureDatasetToken featureDatasetToken = schemaBuilder.Create(featureDatasetDescription);
    
          // Create an annotation feature class description using existing annotation feature class
          AnnotationFeatureClassDescription annotationFeatureClassDescription = 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 DDL
          bool success = schemaBuilder.Build();
    
          // Inspect error messages
          if (!success)
          {
            IReadOnlyList<string> errorMessages = schemaBuilder.ErrorMessages;
            //etc.
          }
        }
      });
    }
    Check if table is versioned
    {
      Task<bool> IsTableVersionedAsync(Geodatabase geodatabase, string tableName) => QueuedTask.Run(() =>
      {
        using (Table table = geodatabase.OpenDataset<Table>(tableName))
        {
          // Check table version type
          RegistrationType registrationType = table.GetRegistrationType();
          if (registrationType == RegistrationType.Versioned)
          {
            return true;
          }
        }
        return false;
      });
    }
    Open raster dataset in a geodatabase
    {
      // Create a FileGeodatabaseConnectionPath using the path to the gdb. Note: This can be a path to a .sde file.
      FileGeodatabaseConnectionPath geodatabaseConnectionPath = new(new Uri(@"C:\Temp\rasters.gdb"));
      // Create a new Geodatabase object using the FileGeodatabaseConnectionPath.
      Geodatabase geodatabase = new(geodatabaseConnectionPath);
      // Open the raster dataset.
      RasterDataset gdbRasterDataset = geodatabase.OpenDataset<RasterDataset>("sample");
    }
    Open a Terrain
    {
      await QueuedTask.Run(() =>
      {
        string path = @"d:\Data\Terrain\filegdb_Containing_A_Terrain.gdb";
        var fileConnection = new FileGeodatabaseConnectionPath(new Uri(path));
    
        using (Geodatabase dataStore = new Geodatabase(fileConnection))
        {
          string dsName = "nameOfTerrain";
    
          using (var dataset = dataStore.OpenDataset<ArcGIS.Core.Data.Analyst3D.Terrain>(dsName))
          {
          }
        }
      });
    }
    Get route information from a polyline feature class with M-values
    {
      static void CreateRouteInfo(Geodatabase geodatabase, string routeFeatureClassName = "Roads", string routeIdFieldName = "RouteID")
      {
        using (FeatureClass routeFeatureClass = geodatabase.OpenDataset<FeatureClass>(routeFeatureClassName))
        using (FeatureClassDefinition routeFeatureClassDefinition = routeFeatureClass.GetDefinition())
        {
          if (routeFeatureClassDefinition.HasM())
          {
            RouteInfo routeInfo = new RouteInfo(routeFeatureClass, routeIdFieldName);
    
            // Process the routeInfo as needed ...
          }
        }
      }
    }
    Get event information
    {
      static void CreateEventInfo(Geodatabase geodatabase, string eventTableName = "Accidents", string routeIdFieldName = "RID", string measureFieldName = "Measure", string offsetFieldName = "Offset")
      {
        using (Table eventTable = geodatabase.OpenDataset<Table>(eventTableName))
        {
          PointEventInfo eventInfo = new PointEventInfo(eventTable, routeIdFieldName, measureFieldName, offsetFieldName);
    
          // Get event type: Point or Line type
          EventType eventTableType = eventInfo.EventType;
        }
      }
    }
    Create a RouteEventSource via dynamic segmentation process for line events
    {
      static void CreateLineEventSource(Geodatabase geodatabase, string routeFeatureClassName = "Roads", string eventTableName = "Accidents", string routeIdFieldName = "RID", string toMeasureFieldName = "toMeasure", string fromMeasureFieldName = "fromMeasure", string offsetFieldName = "Offset")
      {
        using (FeatureClass routesFeatureClass = geodatabase.OpenDataset<FeatureClass>(routeFeatureClassName))
        using (Table eventsTable = geodatabase.OpenDataset<Table>(eventTableName))
        {
          RouteInfo routeInfo = new RouteInfo(routesFeatureClass, routeIdFieldName);
          EventInfo eventInfo = new LineEventInfo(eventsTable, routeIdFieldName, fromMeasureFieldName, toMeasureFieldName, offsetFieldName);
          RouteEventSourceOptions routeEventSourceOptions = new LineEventSourceOptions() { IsPositiveOffsetOnRight = true };
    
          using (RouteEventSource routeEventSource = new RouteEventSource(routeInfo, eventInfo, routeEventSourceOptions))
          using (RouteEventSourceDefinition routeEventSourceDefinition = routeEventSource.GetDefinition())
          {
            // Locating errors
            IReadOnlyList<RouteEventSourceError> errors = routeEventSource.GetErrors();
    
            // Route event source fields
            IReadOnlyList<Field> routeEventSourceFields = routeEventSourceDefinition.GetFields();
    
            // Add RouteEventSource to the ArcGIS Pro map
            FeatureLayerCreationParams layerParams = new FeatureLayerCreationParams(routeEventSource)
            {
              Name = "HighCrashAreas"
            };
    
            LayerFactory.Instance.CreateLayer<FeatureLayer>(layerParams, MapView.Active.Map);
          }
        }
      }
    }
    Locate features along routes
    {
      static void LocateLineFeaturesAlongRoutes(Geodatabase geodatabase, string routeFeatureClassName = "Roads", string eventTableName = "Accidents", string routeIdFieldName = "RID", string toMeasureFieldName = "toMeasure", string fromMeasureFieldName = "fromMeasure")
      {
        // Configure events table
        EventTableConfiguration lineEventTableConfiguration = new LineEventTableConfiguration(eventTableName, routeIdFieldName, fromMeasureFieldName, toMeasureFieldName) { KeepAllFields = true, MDirectionOffset = true };
    
        using (FeatureClass routeFeatureClass = geodatabase.OpenDataset<FeatureClass>(routeFeatureClassName))
        using (FeatureClass highCrashAreaFeatureClass = geodatabase.OpenDataset<FeatureClass>("HighCrashRegion"))
        {
          RouteInfo routeInfo = new RouteInfo(routeFeatureClass, routeIdFieldName);
    
          // Creates an event table inside the geodatabase
          routeInfo.LocateFeatures(highCrashAreaFeatureClass, 0.5, lineEventTableConfiguration);
    
          // Open newly created event table
          using (Table eventTable = geodatabase.OpenDataset<Table>(eventTableName))
          {
            EventInfo eventInfo = new LineEventInfo(eventTable, routeIdFieldName, fromMeasureFieldName, toMeasureFieldName);
    
            // Create RouteEventSource using new event table
            using (RouteEventSource routeEventSource = new RouteEventSource(routeInfo, eventInfo, new LineEventSourceOptions()))
            {
              // Process the routeEventSource as needed ...
            }
          }
        }
      }
    }
    Open topology and process definition
    {
      static void OpenTopologyAndProcessDefinition()
      {
        // Open a geodatabase topology from a file geodatabase and process the topology definition.
        using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\TestData\GrandTeton.gdb"))))
        using (ArcGIS.Core.Data.Topology.Topology topology = geodatabase.OpenDataset<ArcGIS.Core.Data.Topology.Topology>("Backcountry_Topology"))
        {
          ProcessDefinition(geodatabase, topology);
        }
    
        // Open a feature service topology and process the topology definition.
        const string TOPOLOGY_LAYER_ID = "0";
    
        using (Geodatabase geodatabase = new Geodatabase(new ServiceConnectionProperties(new Uri("https://sdkexamples.esri.com/server/rest/services/GrandTeton/FeatureServer"))))
        using (ArcGIS.Core.Data.Topology.Topology topology = geodatabase.OpenDataset<ArcGIS.Core.Data.Topology.Topology>(TOPOLOGY_LAYER_ID))
        {
          ProcessDefinition(geodatabase, topology);
        }
    
        static void ProcessDefinition(Geodatabase geodatabase, ArcGIS.Core.Data.Topology.Topology topology)
        {
          // Similar to the rest of the Definition objects in the Core.Data API, there are two ways to open a dataset's
          // definition -- via the Topology dataset itself or via the Geodatabase.
          using (TopologyDefinition definitionViaTopology = topology.GetDefinition())
          {
            OutputDefinition(geodatabase, definitionViaTopology);
          }
    
          using (TopologyDefinition definitionViaGeodatabase = geodatabase.GetDefinition<TopologyDefinition>("Backcountry_Topology"))
          {
            OutputDefinition(geodatabase, definitionViaGeodatabase);
          }
        }
    
        static void OutputDefinition(Geodatabase geodatabase, TopologyDefinition topologyDefinition)
        {
          Console.WriteLine($"Topology cluster tolerance => {topologyDefinition.GetClusterTolerance()}");
          Console.WriteLine($"Topology Z cluster tolerance => {topologyDefinition.GetZClusterTolerance()}");
    
          IReadOnlyList<string> featureClassNames = topologyDefinition.GetFeatureClassNames();
          Console.WriteLine($"There are {featureClassNames.Count} feature classes that are participating in the topology:");
    
          foreach (string name in featureClassNames)
          {
            // Open each feature class that participates in the topology.
            using (FeatureClass featureClass = geodatabase.OpenDataset<FeatureClass>(name))
            using (FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition())
            {
              Console.WriteLine($"\t{featureClass.GetName()} ({featureClassDefinition.GetShapeType()})");
            }
          }
        }
      }
    }
    Get topology rules
    {
      static void GetTopologyRules()
      {
        using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\TestData\GrandTeton.gdb"))))
        using (ArcGIS.Core.Data.Topology.Topology topology = geodatabase.OpenDataset<ArcGIS.Core.Data.Topology.Topology>("Backcountry_Topology"))
        {
          using (TopologyDefinition topologyDefinition = topology.GetDefinition())
          {
            IReadOnlyList<TopologyRule> rules = topologyDefinition.GetRules();
    
            Console.WriteLine($"There are {rules.Count} topology rules defined for the topology:");
            Console.WriteLine("ID \t Origin Class \t Origin Subtype \t Destination Class \t Destination Subtype \t Rule Type");
    
            foreach (TopologyRule rule in rules)
            {
              Console.Write($"{rule.ID}");
              Console.Write(!String.IsNullOrEmpty(rule.OriginClass) ? $"\t{rule.OriginClass}" : "\t\"\"");
              Console.Write(rule.OriginSubtype != null ? $"\t{rule.OriginSubtype.GetName()}" : "\t\"\"");
              Console.Write(!String.IsNullOrEmpty(rule.DestinationClass) ? $"\t{rule.DestinationClass}" : "\t\"\"");
              Console.Write(rule.DestinationSubtype != null ? $"\t{rule.DestinationSubtype.GetName()}" : "\t\"\"");
              Console.Write($"\t{rule.RuleType}");
              Console.WriteLine();
            }
          }
        }
      }
    }
    Validate topology
    {
      static void ValidateTopology()
      {
        using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\TestData\GrandTeton.gdb"))))
        using (ArcGIS.Core.Data.Topology.Topology topology = geodatabase.OpenDataset<ArcGIS.Core.Data.Topology.Topology>("Backcountry_Topology"))
        {
          // If the topology currently does not have dirty areas, calling Validate() returns an empty envelope.
          ValidationResult result = topology.Validate(new ValidationDescription(topology.GetExtent()));
          Console.WriteLine($"'AffectedArea' after validating a topology that has not been edited => {result.AffectedArea.ToJson()}");
    
          // Now create a feature that purposely violates the "PointProperlyInsideArea" topology rule.  This action will
          // create dirty areas.
          Feature newFeature = null;
    
          try
          {
            // Fetch the feature in the Campsites feature class whose objectID is 2.  Then create a new geometry slightly
            // altered from this and use it to create a new feature.
            using (Feature featureViaCampsites2 = GetFeature(geodatabase, "Campsites", 2))
            {
              Geometry currentGeometry = featureViaCampsites2.GetShape();
              Geometry newGeometry = GeometryEngine.Instance.Move(currentGeometry, (currentGeometry.Extent.XMax / 8), (currentGeometry.Extent.YMax / 8));
    
              using (FeatureClass campsitesFeatureClass = featureViaCampsites2.GetTable())
              using (FeatureClassDefinition definition = campsitesFeatureClass.GetDefinition())
              using (RowBuffer rowBuffer = campsitesFeatureClass.CreateRowBuffer())
              {
                rowBuffer[definition.GetShapeField()] = newGeometry;
    
                geodatabase.ApplyEdits(() => { newFeature = campsitesFeatureClass.CreateRow(rowBuffer); });
              }
            }
    
            // After creating a new feature in the 'Campsites' participating feature class, the topology's state should be
            // "Unanalyzed" because it has not been validated.
            Console.WriteLine($"The topology state after an edit has been applied => {topology.GetState()}");
    
            // Now validate the topology.  The result envelope corresponds to the dirty areas.
            result = topology.Validate(new ValidationDescription(topology.GetExtent()));
            Console.WriteLine($"'AffectedArea' after validating a topology that has just been edited => {result.AffectedArea.ToJson()}");
    
            // After Validate(), the topology's state should be "AnalyzedWithErrors" because the topology currently has errors.
            Console.WriteLine($"The topology state after validate topology => {topology.GetState()}");
    
            // If there are no dirty areas, the result envelope should be empty.
            result = topology.Validate(new ValidationDescription(topology.GetExtent()));
            Console.WriteLine($"'AffectedArea' after validating a topology that has just been validated => {result.AffectedArea.ToJson()}");
          }
          finally
          {
            if (newFeature != null)
            {
              geodatabase.ApplyEdits(() => { newFeature.Delete(); });
              newFeature.Dispose();
            }
          }
    
          // Validate again after deleting the newly-created feature.
          topology.Validate(new ValidationDescription(topology.GetExtent()));
        }
      }
    }
    Process topology errors
    {
      static void ProcessTopologyErrors()
      {
        using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\TestData\GrandTeton.gdb"))))
        using (ArcGIS.Core.Data.Topology.Topology topology = geodatabase.OpenDataset<ArcGIS.Core.Data.Topology.Topology>("Backcountry_Topology"))
        {
          // Get all the errors and exceptions currently associated with the topology.
          IReadOnlyList<TopologyError> allErrorsAndExceptions = topology.GetErrors(new ErrorDescription(topology.GetExtent()));
    
          Console.WriteLine($"errors and exceptions count => {allErrorsAndExceptions.Count}");
          Console.WriteLine("OriginClassName \t OriginObjectID \t DestinationClassName \t DestinationObjectID \t RuleType \t IsException \t Shape type \t Shape width & height \t  Rule ID \t");
    
          foreach (TopologyError error in allErrorsAndExceptions)
          {
            Console.WriteLine(
              $"'{error.OriginClassName}' \t {error.OriginObjectID} \t '{error.DestinationClassName}' \t " +
              $"{error.DestinationObjectID} \t {error.RuleType} \t {error.IsException} \t {error.Shape.GeometryType} \t " +
              $"{error.Shape.Extent.Width},{error.Shape.Extent.Height} \t {error.RuleID}");
          }
        }
      }
    }
    Explore topology graph
    {
      static void ExploreTopologyGraph()
      {
        using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\TestData\GrandTeton.gdb"))))
        using (ArcGIS.Core.Data.Topology.Topology topology = geodatabase.OpenDataset<ArcGIS.Core.Data.Topology.Topology>("Backcountry_Topology"))
        {
          // Build a topology graph using the extent of the topology dataset.
          topology.BuildGraph(topology.GetExtent(), (topologyGraph) =>
          {
            using (Feature campsites12 = GetFeature(geodatabase, "Campsites", 12))
            {
              IReadOnlyList<TopologyNode> topologyNodesViaCampsites12 = topologyGraph.GetNodes(campsites12);
    
              TopologyNode topologyNodeViaCampsites12 = topologyNodesViaCampsites12[0];
    
              IReadOnlyList<TopologyEdge> allEdgesConnectedToNodeViaCampsites12 = topologyNodeViaCampsites12.GetEdges();
              IReadOnlyList<TopologyEdge> allEdgesConnectedToNodeViaCampsites12CounterClockwise = topologyNodeViaCampsites12.GetEdges(false);
    
              foreach (TopologyEdge edgeConnectedToNodeViaCampsites12 in allEdgesConnectedToNodeViaCampsites12)
              {
                TopologyNode fromNode = edgeConnectedToNodeViaCampsites12.GetFromNode();
                TopologyNode toNode = edgeConnectedToNodeViaCampsites12.GetToNode();
    
                bool fromNodeIsTheSameAsTopologyNodeViaCampsites12 = (fromNode == topologyNodeViaCampsites12);
                bool toNodeIsTheSameAsTopologyNodeViaCampsites12 = (toNode == topologyNodeViaCampsites12);
    
                IReadOnlyList<FeatureInfo> leftParentFeaturesBoundedByEdge =
                  edgeConnectedToNodeViaCampsites12.GetLeftParentFeatures();
                foreach (FeatureInfo featureInfo in leftParentFeaturesBoundedByEdge)
                {
                  EnsureShapeIsNotEmpty(featureInfo);
                }
    
                IReadOnlyList<FeatureInfo> leftParentFeaturesNotBoundedByEdge =
                  edgeConnectedToNodeViaCampsites12.GetLeftParentFeatures(false);
                foreach (FeatureInfo featureInfo in leftParentFeaturesNotBoundedByEdge)
                {
                  EnsureShapeIsNotEmpty(featureInfo);
                }
    
                IReadOnlyList<FeatureInfo> rightParentFeaturesBoundedByEdge =
                  edgeConnectedToNodeViaCampsites12.GetRightParentFeatures();
                foreach (FeatureInfo featureInfo in rightParentFeaturesBoundedByEdge)
                {
                  EnsureShapeIsNotEmpty(featureInfo);
                }
    
                IReadOnlyList<FeatureInfo> rightParentFeaturesNotBoundedByEdge =
                  edgeConnectedToNodeViaCampsites12.GetRightParentFeatures(false);
                foreach (FeatureInfo featureInfo in rightParentFeaturesNotBoundedByEdge)
                {
                  EnsureShapeIsNotEmpty(featureInfo);
                }
              }
            }
          });
        }
        static void EnsureShapeIsNotEmpty(FeatureInfo featureInfo)
        {
          using (Feature feature = featureInfo.GetFeature())
          {
            // Process feature ...
          }
        }
      }
    }
    Find closest element from a topology graph
    {
      static void FindClosestElement()
      {
        using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\TestData\GrandTeton.gdb"))))
        using (ArcGIS.Core.Data.Topology.Topology topology = geodatabase.OpenDataset<ArcGIS.Core.Data.Topology.Topology>("Backcountry_Topology"))
        {
          // Build a topology graph using the extent of the topology dataset.
          topology.BuildGraph(topology.GetExtent(), (topologyGraph) =>
          {
            MapPoint queryPointViaCampsites12 = null;
    
            using (Feature campsites12 = GetFeature(geodatabase, "Campsites", 12))
            {
              queryPointViaCampsites12 = campsites12.GetShape() as MapPoint;
            }
    
            double searchRadius = 1.0;
    
            TopologyElement topologyElementViaCampsites12 = topologyGraph.FindClosestElement<TopologyElement>(queryPointViaCampsites12, searchRadius);
            IReadOnlyList<FeatureInfo> parentFeatures = topologyElementViaCampsites12.GetParentFeatures();
    
            Console.WriteLine("The parent features that spawn 'topologyElementViaCampsites12' are:");
            foreach (FeatureInfo parentFeature in parentFeatures)
            {
              Console.WriteLine($"\t{parentFeature.FeatureClassName}; OID: {parentFeature.ObjectID}");
            }
    
            TopologyNode topologyNodeViaCampsites12 = topologyGraph.FindClosestElement<TopologyNode>(queryPointViaCampsites12, searchRadius);
    
            if (topologyNodeViaCampsites12 != null)
            {
              // There exists a TopologyNode nearest to the query point within searchRadius units.
            }
    
            TopologyEdge topologyEdgeViaCampsites12 = topologyGraph.FindClosestElement<TopologyEdge>(queryPointViaCampsites12, searchRadius);
    
            if (topologyEdgeViaCampsites12 != null)
            {
              // There exists a TopologyEdge nearest to the query point within searchRadius units.
            }
          });
        }
      }
    }
    Requirements

    Target Platforms: Windows 11 Home, Pro, Enterprise (64 bit)

    ArcGIS Pro version: 3.0 or higher.
    See Also