Working with ArcObjects code snippets


In this topic


About working with ArcObjects code snippets

This topic includes ArcObjects code examples for some of the common tasks needed for custom applications to work. Keep in mind the following when using the code examples in this topic:
  • Contain snippets in a try/catch block for them to work.
  • Snippets can be used with ArcGIS Engine and ArcGIS Server; however, the way new objects are instantiated differs when using these code examples with ArcGIS Server. For more information, see Create objects on the server in this topic.
  • Since these snippets are showing ArcGIS Engine usage (which is stateful) they should only be used with non-pooled server objects. Snippets suitable for pooled server objects (non-stateful usage) are noted.
  • Complete and more detailed versions of the code snippets are available from the Code Exchange on the ESRI Developer Network (EDN) Web site.

Initialize an ArcGIS Engine application

An ArcGIS Engine based application must initialize certain environment variables and check out a license before it executes.
  • Initialize environment variables and acquire an ArcGIS Engine license. See the following code example:
[Java]
EngineInitializer.initializeEngine();
AoInitialize aoInit = new AoInitialize();
aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine);
  • If you are working with the ArcGIS controls (visual Java beans found in the com.esri.arcgis.beans.xxxx packages), the initialization code looks like the following code example:
[Java]
EngineInitializer. initializeVisualBeans();
AoInitialize aoInit = new AoInitialize();
aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine);
  • If your application requires the use of an extension product, such as Spatial Analyst or 3D Analyst, check these licenses also. This code cannot precede the initial license checkout. See the following code example:
[Java]
aoInit.initialize(esriLicenseExtensionCode.esriLicenseExtensionCodeSpatialAnalyst);
aoInit.initialize(esriLicenseExtensionCode.esriLicenseExtensionCode3DAnalyst);

Connect to ArcGIS Server

This code shows how to connect to ArcGIS Server, impersonate a user, and create a blank server context.
  • Initialize ArcObjects for Server usage, where domain is the authenticating domain, user is a user in the agsadmin or agsuser group, and password is the password for the user. See the following code example:
[Java]
new ServerInitializer().initializeServer(domain, user, password);
  • Connect to the host machine where the ArcGIS Server Object Manager is running, get the server object manager (SOM), and create an empty context. See the following code example:
[Java]
ServerConnection connection = new ServerConnection();
connection.connect(host);
IServerObjectManager som = connection.getServerObjectManager();
sc = som.createServerContext("", "");

Create objects on the server

Server objects have a different syntax since they are created remotely.
  • In an ArcGIS Engine based application, create a point with the following code example:
[Java]
Point point = new Point();
  • In an ArcGIS Server based application, create the point as shown in the following code example:
[Java]
Point point = new Point(context.createObject(Point.getClsid()));
  • Creating a proxy is similar. See the following code example:
[Java]
IPoint point = new IPointProxy(context.createObject(Point.getClsid()));

Open a map document

When you programmatically open a map document, you can access all the information defined in a map (.mxd) file. In this case, mapLocation is the fully qualified path to the map document, including the .mxd file extension. See the following code example:
[Java]
MapDocument mapDocument = new MapDocument();
if (mapDocument.isPresent(mapLocation)){
    mapDocument.open(mapLocation, "");
}

Open a shapefile

In the following code example, the .shp file extension is not used when specifying the name of the shapefile to open:
[Java]
ShapefileWorkspaceFactory wsf = new ShapefileWorkspaceFactory();
Workspace work = new Workspace(wsf.openFromFile(location, 0));
IFeatureClass featureClass = work.openFeatureClass("NameOfYourShapefile");

Open a dBASE file

In the following code example, pathToFile is the path to the folder holding the .dbf file. Additionally, the .dbf file extension must be included when specifying the name of the dBASE file.
[Java]
ShapefileWorkspaceFactory shapefileWorkspaceFactory = new ShapefileWorkspaceFactory()
    ;
Workspace workspace = new Workspace(shapefileWorkspaceFactory.openFromFile
    (pathToFile, 0));
Table table = new Table(workspace.openTable(fileName));

Open a SDE connection with the server API

The following code example uses ArcObjects to connect directly to ArcSDE and get datasets rather than using the MapServer object to get the ArcSDE layers in a map.
  • Create a WorkspaceFactory object in the server's context. See the following code example:
[Java]
IWorkspaceFactory pWorkspaceFactory = new IWorkspaceFactoryProxy
    (context.createObject("esriDataSourcesGDB.SdeWorkspaceFactory"));
  • Create an instance of a PropertySet for an Oracle ArcSDE connection. The PropertySet acts as an array of keyed values that ArcSDE uses from which to collect the connection values. See the following code example:
[Java]
PropertySet propSet = new PropertySet(context.createObject("esrisystem.PropertySet"))
    ;
propSet.setProperty("SERVER", "pine");
propSet.setProperty("INSTANCE", "9091");
propSet.setProperty("DATABASE", "");
propSet.setProperty("USER", "map");
propSet.setProperty("PASSWORD", "map");
propSet.setProperty("VERSION", "SDE.DEFAULT");
  • Open the ArcSDE workspace and get a handle to the workspace through the WorkspaceFactory, passing in the PropertySet. See the following code example:
[Java]
IWorkspace ws = pWorkspaceFactory.open(propSet, 0);
You now have a connection to the database through a Workspace object (ws). In the following code example, the feature datasets are listed out:
[Java]
IEnumDataset dsenum = ws.getDatasets(esriDatasetType.esriDTFeatureDataset);
IDataset ds = dsenum.next();
while (ds != null){
    System.out.println(ds.getName());
    ds = dsenum.next();
}

Open a CAD file

In the following code example, the method for opening a workspace is different than in other examples (in this example, you work with a WorkspaceName). All of the workspace factories in the com.esri.arcgis.datasourcesfile package can be referenced as a factory. The proper suffix must be included in the fileName.
[Java]
WorkspaceName workspaceName = new WorkspaceName();
workspaceName.setWorkspaceFactoryProgID("esriDataSourcesFile.CadWorkspaceFactory");
workspaceName.setPathName(filePath);
CadDrawingName cadDrawingName = new CadDrawingName();
cadDrawingName.setName(fileName);
cadDrawingName.setWorkspaceNameByRef(workspaceName);
CadLayer cadLayer = new CadLayer(cadDrawingName.open());

Open a TIN coverage

The following code example opens a triangulated irregular network (TIN) from a file. TIN coverages, like all coverages, are a folder and not a file name.
[Java]
Tin tin = new Tin();
tin.init(tinPathAndTinName);

Open a raster dataset

Depending on the type of raster you are opening, the suffix may or may not be needed. For a grid raster, specify the path name including the grid directory. For a .tif or .img file, specify the suffix in the fileName. See the following code example:
[Java]
RasterWorkspaceFactory rasterWorkspaceFactory = new RasterWorkspaceFactory();
RasterWorkspace rasterWorkspace = new RasterWorkspace
    (rasterWorkspaceFactory.openFromFile(directoryName, 0));
rasterDataset = new RasterDataset(rasterWorkspace.openRasterDataset(fileName));

Open a personal geodatabase

A personal geodatabase can only be opened on a Microsoft Windows computer. Include the .mdb suffix for the file. See the following code example:
[Java]
AccessWorkspaceFactory wsf = new AccessWorkspaceFactory();
Workspace wspace = new Workspace(wsf.openFromFile(fileName, 0));
FeatureClass featureClass = new FeatureClass(wspace.openFeatureClass("AFeatureClass")
    );

Get a layer from a map

Since a map document can contain multiple maps, the getMap method requires an int for choosing a map. The same concept applies to layers in a map. See the following code example:
[Java]
Map map = new Map(mapDocument.getMap(0));
FeatureLayer layer0 = new FeatureLayer(map.getLayer(0));

Create a layer from a feature class

The following example assumes you have opened a feature class, such as from a shapefile or a personal geodatabase. After setting the feature class for a layer, add the layer to a map.
[Java]
FeatureLayer featureLayer = new FeatureLayer();
featureLayer.setFeatureClassByRef(yourFeatureClass);
map.addLayer(featureLayer);

Work with the attributes of a feature class

The following code example assumes you have opened a feature class, such as from a shapefile or a personal geodatabase.
  • Get the feature cursor from the feature class and loop through all the field names.
[Java]
IFeatureCursor featureCursor = featureClass.search(null, true);
IFields fields = featureCursor.getFields();
int fieldCount = fields.getFieldCount();
for (int i = 0; i < fieldCount; i++){
    IField fieldI = fields.getField(i);
    String fieldName = fieldI.getName();
    System.out.print(fieldName + "\t");
}

System.out.println();
  • Use the feature cursor to iterate over all elements in the feature class, printing the values of the fields. All field types are shown in the following code example. Simple values are printed as strings. Complex elements are shown as the type name.
[Java]
IFeature feature = featureCursor.nextFeature();
while (feature != null){
    StringBuffer row = new StringBuffer();
    for (int i = 0; i < fieldCount; i++){
        int fieldType = feature.getFields().getField(i).getType();
        switch (fieldType){
            case esriFieldType.esriFieldTypeDate:
            case esriFieldType.esriFieldTypeDouble:
            case esriFieldType.esriFieldTypeGlobalID:
            case esriFieldType.esriFieldTypeGUID:
            case esriFieldType.esriFieldTypeInteger:
            case esriFieldType.esriFieldTypeOID:
            case esriFieldType.esriFieldTypeSingle:
            case esriFieldType.esriFieldTypeSmallInteger:
            case esriFieldType.esriFieldTypeString:
                row.append(feature.getValue(i) + "\t");
                break;
            case esriFieldType.esriFieldTypeBlob:
                row.append("(blob)" + "\t");
                break;
            case esriFieldType.esriFieldTypeGeometry:
                row.append("(geometry)" + "\t");
                break;
            case esriFieldType.esriFieldTypeRaster:
                row.append("(raster)" + "\t");
                break;
        }
    }
    if (row.length() > 0){
        System.out.println(row);
    }
    feature = featureCursor.nextFeature();
}

Create a query filter

Query filters allow you to use attribute data to create a subset of your original data. They are used for many different tasks in ArcObjects, such as selecting features in a layer or creating a subset of the features and performing an operation on those features.
A spatial filter implements IQueryFilter so you can also use a query filter in a spatial query. When creating a query based upon a string attribute, enclose your string condition in single quotes (for exampe, "name='ESRI'").
See the following code example:
[Java]
QueryFilter queryFilter = new QueryFilter();
queryFilter.setWhereClause("Attribute=value");

Select features from a layer based on attributes

When you have a query filter, use it to select features in a layer. The second parameter of the selectFeatures method allows you to determine the type of selection to perform, such as create a new selection set, append the selection to the current selection set, and so on. See the following code example:
[Java]
layer.selectFeatures(queryfilter, esriSelectionResultEnum.esriSelectionResultNew,
    false);
int numberOfSelectedFeatures = map.getSelectionCount();

Perform a spatial query on a map

A spatial filter, which also implements IQueryFilter, searches a feature class for all the features that satisfy the spatial relation with an IGeometry. There are many objects that implement IGeometry, such as Point, MultiPoint, Line, and so on. The list of spatial relations can be found in esriSpatialRelEnum. See the following code example:
[Java]
SpatialFilter spatialFilter = new SpatialFilter();
spatialFilter.setGeometryByRef(searchGeometry);
String shapeFieldString = featureClass.getShapeFieldName();
spatialFilter.setGeometryField(shapeFieldString);
spatialFilter.setSpatialRel(spatialRelation);
if ((whereClause == null)){
    spatialFilter.setWhereClause("");
}

else{
    spatialFilter.setWhereClause(whereClause);
}

featureCursor = featureClass.search(spatialFilter, false);

Buffer off selected features

The map used in the following code example must have selected features to get the selected feature from the map.
[Java]
MapSelection mapSelection = new MapSelection(map.getFeatureSelection());
mapSelection.reset();
IFeature feature = mapSelection.next();
While all the higher order geometries, such as Point, MultiPoint, Line, and Polygon implement ITopologicalOperator, the following code example only uses the interface object. In this way, you can perform this operation without worrying about the feature returned by the getShape method. The buffer method returns an IGeometry (which is always a polygon). This geometry can then be used in any method requiring an IGeometry.
[Java]
ITopologicalOperator topologicalOperator = new ITopologicalOperatorProxy
    (feature.getShape());
Polygon bufferGeometry = new Polygon(topologicalOperator.buffer(bufferDistance));

Add items to the graphic container of a map

Graphic layers are generally used to display items on a map. While it is quicker to draw items in a graphic container, this results in reduced functionality. The items on a graphic layer are elements and not features. There are many different objects that implement IElement, ranging from GifPictureElement to Text3DElement. Placing graphic elements on a globe is not supported at 9.1 but will be supported with 9.2.
The following code example illustrates how to take a feature and use it to create an element:
[Java]
Point point = new Point();
point.setX( - 100.00);
point.setY(40);
MarkerElement markerElement = new MarkerElement();
markerElement.setGeometry(point);
map.addElement(markerElement, 0);

Project data from one coordinate system to another

Spatial data is collected using a spatial reference system, either geographic coordinates (degree, minutes, seconds) or projected coordinates, for example, universal transverse Mercator (UTM). In addition, there are different spherical models of the earth (datums). Taking data from one spatial reference system to another is a projection. There are numerous spatial reference systems available in ArcObjects.
The following code example takes data from a geographic coordinate system with the North American Datum of 1927 (NAD1927) to UTM zone 13 North with the North American Datum of 1983 (NAD 1983).
  • Make a spatial reference environment that implements a spatial reference factory, create the spatial reference and apply it to an object implementing IGeometry. In this case, a Point is projected. See the following code example:
[Java]
Point point = new Point();
point.setX( - 100.00);
point.setY(40);
SpatialReferenceEnvironment sRefEnv = new SpatialReferenceEnvironment();
ISpatialReference incomingCoordSystem = sRefEnv.createGeographicCoordinateSystem
    (esriSRGeoCSType.esriSRGeoCS_NAD1927);
point.setSpatialReferenceByRef(incomingCoordSystem);
  • Create the spatial reference for the projected coordinate system. Since the datums are also changing, specify a datum conversion. Finally, the point is projected. See the following code example.
[Java]
ISpatialReference outgoingCoordSystem = sRefEnv.createProjectedCoordinateSystem
    (esriSRProjCSType.esriSRProjCS_NAD1983UTM_13N);
NADCONTransformation datumConversion = new NADCONTransformation
    (sRefEnv.createGeoTransformation
    (esriSRGeoTransformation2Type.esriSRGeoTransformation_NAD_1927_TO_NAD_1983_NADCON));
point.projectEx(outgoingCoordSystem, esriTransformDirection.esriTransformForward,
    datumConversion, false, 0, 0);

Open an InMemoryWorkspace and create a feature class

Use an InMemoryWorkspaceFactory to connect to a temporary workspace stored in memory. These workspaces are commonly used to hold the results of an analysis operation or to hold objects in memory before persisting them to disk. When the last reference to the workspace is released, the workspace is destroyed and the memory released.
Feature classes contained within InMemory workspaces support the full geodatabase model and can be used in conjunction with cursors, selections, and so on. However, InMemory workspaces do not support all aspects of the geodatabase model; advanced datasets such as topology and geometric networks are not supported. The following code example shows how to create a feature class in an InMemory workspace.
[Java]
// Create an InMemory workspace factory.
IWorkspaceFactory workspaceFactory = new InMemoryWorkspaceFactory();

// Create a new InMemory geodatabase.
IWorkspaceName workspaceName = workspaceFactory.create("", "MyWorkspace", null, 0);

// Cast for IName.
IName name = (IName)workspaceName;

// Open a reference to the access workspace through the name object.
IWorkspace inmemWor = new IWorkspaceProxy(name.open());

// Cast the IWorkspace to a FeatureWorkspace.
IFeatureWorkspace featWork = new IFeatureWorkspaceProxy(inmemWor);

// Create the fields collection and fields for the feature class.
Fields flds = new Fields();

GeometryDef gdef = new GeometryDef();
gdef.setGeometryType(com.esri.arcgis.geometry.esriGeometryType.esriGeometryPoint);
ISpatialReference sr = new UnknownCoordinateSystem();
sr.setDomain(34.0,  - 118.0, 35.0,  - 120.0);
gdef.setSpatialReferenceByRef(sr);

Field fld = new Field();
fld.setType(esriFieldType.esriFieldTypeGeometry);
fld.setName("Shape");
fld.setGeometryDefByRef(gdef);

Field fld1 = new Field();
fld1.setName("Field1");
fld1.setType(esriFieldType.esriFieldTypeDouble);

flds.addField(fld);
flds.addField(fld1);

// Create the feature class.
FeatureClass fc = new FeatureClass(featWork.createFeatureClass("strikes", flds, null,
    null, com.esri.arcgis.geodatabase.esriFeatureType.esriFTSimple, "Shape", ""));