Run a geoprocessing task

A geoprocessing service contains one or more geoprocessing tasks. A geoprocessing task is a geoprocessing tool running on a service and its execution and outputs are managed by the service. You can run these tools from an ArcGIS Runtime app using classes in the Esri.ArcGISRuntime.Tasks.Geoprocessing namespace.

Steps to run a geoprocessing task at a high level:

  1. Create a GeoprocessingTask using full URL to the target geoprocessing task endpoint.
  2. Create GeoprocessingParameters providing corresponding GeoprocessingExecutionType.
  3. Create GeoprocessingParameter(s) as required, and add them to GeoprocessingParameters.Inputs() where key is the name of the parameter and value is created parameter.
  4. Set environment variables on GeoprocessingParameters if needed.
  5. Create GeoprocessingJob by calling the job creation method on the geoprocessing task, using the parameters created previously.
  6. Listen for job changed status and message changes on the GeoprocessingJob.
  7. Run the geoprocessing job and if it completes successfully, get the GeoprocessingResult.
  8. Handle returned values accordingly. Output parameters are accessed as a dictionary on GeoprocessingResult where key is the name of the output parameter and the value is returned parameter. If the geoprocessing service is configured to use a result map service then the result may also contain a map image layer that has been created for you.

Creating a geoprocessing task

GeoprocessingTask is the main component when running geoprocessing tasks which is used to run a single geoprocessing task. The target is defined by providing URL to the target REST endpoint.

The format for a geoprocessing task URL is http://<gpservice-url>/<taskName>. The endpoint for a task called 'BufferPoints' hosted on 'myserver', for example, would be something like:

https://myserver/ArcGIS/rest/services/BufferPoints/GPServer/BufferPoints

GeoprocessingTask hotspotTask = 
   new GeoprocessingTask(
      new Uri("http://sampleserver6.arcgisonline.com/arcgis/rest/services/911CallsHotspot/GPServer/911%20Calls%20Hotspot";));

Creating input parameters

GeoprocessingParameters contains input parameters and environment variables. Required input parameters are defined by the geoprocessing task. Environment variables are common geoprocessing variables that guide how the service works.

When GeoprocessingParameters is created, it needs to know the execution type of the task. This defines which REST endpoint the GeoprocessingJob is using when the task is executed. This value needs to match the one defined in the used service.

GeoprocessingParameters.Inputs() is a dictionary that contains all the parameters that are sent to the service. The key of the item is the name of the parameter and the value contains the GeoprocessingParameter. When parameters are provided to the geoprocessing task their parameter name and type needs to match the one defined in a task. At a minimum all parameters that are set as required on the task must be provided to run the task successfully.

You can also provide a set of optional environment variables. These control general settings for the service, such as whether the Z and M values are returned in the result, or which spatial reference to use for the results. For example, if you are visualizing the results of the analysis on the map, requesting the results in the same spatial reference as the map view uses removes the need for the client to reproject the results before adding them to the map view.

GeoprocessingParameters hotspotParameters = new GeoprocessingParameters(GeoprocessingExecutionType.AsynchronousSubmit);


// Construct used query
var queryString = string.Format("(\"DATE\" > date '{0} 00:00:00' AND \"DATE\" < date '{1} 00:00:00')",
    fromDate.ToString("yyyy-MM-dd"),
    toDate.ToString("yyyy-MM-dd"));

// Add query that contains the date range and the days of the week that are used in analysis
hotspotParameters.Inputs.Add("Query", new GeoprocessingString(queryString));

Task execution types

When working with geoprocessing services, you must be aware of the execution type that the service was published with. This execution type can be found on the service's REST page. There are multiple execution types that define how geoprocessing tasks run on a server:

  • Execute (defined as esriExecutionTypeSynchronous in task page)

    Synchronous execution is designed for fast-running tasks and they are run synchronously on the server. The client sends a request asynchronously to the service and waits for the response. This means these types of services use less resources on the server. When targeting a geoprocessing service that is exposed using this type, GeoprocessingParameters needs to be created using GeoprocessingExecutionType.SynchronousExecute.

  • Submit (defined as esriExecutionTypeAsynchronous in task page)

    Asynchronous services are best suited for long running jobs and are run using asynchronous model on the server. For asynchronous tasks, the server returns a job ID that the client uses to poll for the task status. When the job is completed, the results are fetched separately from the job result endpoints. When targeting a geoprocessing service that is exposed using this type, GeoprocessingParameters needs to be created using GeoprocessingExecutionType.AsynchronousSubmit.

If a geoprocessing tool is published from ArcGIS Desktop with a map server result to visually represent each geodataset output parameter as a layer then the geoprocessing server (GPServer) will have an accompanying dynamic map server of the same name for presenting the results. This map service's symbology is based on the symbology of the output layer that resulted from running the geoprocessing tool in ArcGIS Desktop during the publishing process. See Defining output symbology for geoprocessing tasks for additional information on setting the symbology for a result map service.

GeoprocessingJob, which does the communication between the client and the service, knows which REST endpoint to use based on the execution type that was given as a parameter for GeoprocessingParameters and it has to match the execution type on the service. If the value isn't correct then an exception is thrown when the task is run.

Parameters

Geoprocessing tasks usually have input and output parameters. These parameters are defined when the geoprocessing task is authored and can be seen in geoprocessing task page in the services directory. Each parameter of a task has a set of descriptive properties that help you understand the parameter and provide appropriate value for the successful execution of the task.

When parameters are provided to the geoprocessing task their parameter name and type needs to match the one defined in a task. At a minimum all parameters that are set as required on the task must be provided to run the task successfully

The significance of each property is described below

Parameter direction

Every parameter has a direction which is defined in the parameter information. This information helps you identify whether the parameter is an input or output parameter.

When the task is executed, the client needs to provide values for the input parameters only. Output parameters are returned from the task when the job has been run successfully.

Output parameters are always returned from a geoprocessing task in a dictionary.

Parameter data types

The data type of the parameter specifies the type of value that the client must provide for the parameter. The value of a parameter can be as simple as a string, long, double, Boolean or date. Or, it can be a set of features or records or a raster file. For example, if the task is expecting to have a raster input parameter, you need to provide a geoprocessing raster parameter in a GeoprocessingParameters.Inputs() collection to execute the tool successfully.

Here is a list of ArcGIS Runtime geoprocessing parameter types and which types they correspond to the service.

Required and optional parameters

Parameters can be defined as: required, required with default value, optional, or derived. When the parameter is required but doesn't have default value defined, the parameter must be provided when the geoprocessing task is executed. If the default value is defined, then you can override that value by providing a new parameter in a GeoprocessingParameters.Inputs() dictionary. Optional parameters can be provided in the same manner. Derived means that the you do not enter a value for the parameter. Derived types are always output parameters.

ArcGIS Runtime parameter typesCorresponding REST typesNote

GeoprocessingString

GPString

A string. If ChoiceList is defined in a parameter then the value must match one of the items in the list

GeoprocessingDouble

GPDouble

A decimal value approximately between -2.2E308 to 1.7E308

GeoprocessingLong

GPLong

An integer value between −2,147,483,648 to 2,147,483,647

GeoprocessingBoolean

GPBoolean

True or false

GeoprocessingDate

GPDate

A date value

GeoprocessingLinearUnit

GPLinearUnit

A value that has a distance value and its unit of measurement such as kilometers or meters

GeoprocessingDataFile

GPDataFile

References a file such as .txt, .pdf, .csv, and so on. Supported data types are controlled by the used service. Can reference a file that is uploaded to the service using Uploads capability

GeoprocessingRaster

GPRasterData

References a single raster file such as .tif or .jpg, and so on.

Can reference a raster that is uploaded to the service using Uploads capability.

GeoprocessingRaster

GPRasterDataLayer

Super set of GPRasterData that supports showing values on result map server.

GeoprocessingFeatures

GPRecordSet

A set of Features that represents rows and columns. Doesn't have a geometry or spatial reference.

Can reference a file that has the features serialized.

GeoprocessingFeatures

GPFeatureRecordSetLayer

A set of Features that have a geometry, spatial reference and attributes.

Can reference a file that has the features serialized.

GeoprocessingMultiValue

GPMultiValue

An array of geoprocessing parameters of the same data type

Running the task and handling the results

The targeted geoprocessing task is run using GeoprocessingJob which is responsible handling the communication between the client and the service. GeoprocessingJob is created using GeoprocessingTask and GeoprocessingParameters, and it can be started by calling Start. GeoprocessingJob also provides an awaitable task which runs the job and returns the results when the task is completed successfully. If any errors occurs while the job is running, an exception is thrown. The error can be also retrieved directly from the GeoprocessingJob.

// Create job that handles the communication between the application and the geoprocessing task
GeoprocessingJob hotspotJob = _hotspotTask.CreateJob(hotspotParameters);
try
{
    // Execute analysis and wait for the results
    GeoprocessingResult analysisResult = await _hotspotJob.GetResultAsync();
 
    // Do something with the results 
}
catch (TaskCanceledException cancelledException)
{
    // This is thrown if the task is cancelled.
}
catch (Exception exception)
{
    // Handle properly            
}

Results as a map image layer

The result map server is a dynamic map service that accompanies a geoprocessing service to visualize the geoprocessing results. If this is enabled in the geoprocessing task, then theGeoprocessingResult.MapImageLayer might be populated for you. The visualization of the layer is determined by the symbology on the geoprocessing service.

This functionality is available on the geoprocessing services that has execution type of submit with result map server functionality enabled.

// Execute analysis and wait for the results
GeoprocessingResult analysisResult = await _hotspotJob.GetResultAsync();
// Add layers to the map view
MyMapView.Map.OperationalLayers.Add(analysisResult.MapImageLayer);

In case where GeoprocessingResult.MapImageLayer is populated in the results and the geoprocessing result outputs contain GeoprocessingFeatures parameters, features aren't automatically downloaded to the client to avoid unnecessary traffic between the service and the client. If you need to download the features, you can get the features explicitly from the results.

// Get output features from the results
GeoprocessingFeatures outputFeatures = analysisResult.Outputs["Output_Features"] as GeoprocessingFeatures;
// Check if the features can be loaded from the service
if (outputFeatures.CanGetOutputFeatures)
{
    // Load features from the service 
    await outputFeatures.GetOutputFeaturesAsync();
    foreach (var feature in outputFeatures.Features)
    {
        // For example add features to the graphic overlay
    }
}

Downloading geoprocessing data files and rasters

If GeoprocessingDataFiles or GeoprocessingRasters are used as output parameters, they have a URL specified to the location of the output file. This file can be downloaded to the client device easily by using an awaitable task.

// Get output raster from the results
GeoprocessingRaster outputRaster = analysisResult.Outputs["Hotspot_Raster"] as GeoprocessingRaster;
// Download output to the given file path
string fullFilePath = await outputRaster.GetFileAsync("Full file path or folder path");

Related topics