Walkthrough: Consuming a geoprocessing model tool in .NET (ArcObjects .NET 10.6 SDK)
ArcObjects Help for .NET developers > Developing with ArcGIS > Learning ArcObjects > Using geoprocessing > Walkthrough: Consuming a geoprocessing model tool in .NET (ArcObjects .NET 10.6 SDK)

Consuming a geoprocessing model tool in .NET


Summary
This topic shows the required steps to run a geoprocessing model tool in a .NET Visual Studio project. The same process also applies to a script tool.

In this topic


Project description

This topic consists of the following main areas:
  • Creating the custom model tool—A custom model tool is created in ModelBuilder. This custom tool performs a common geoprocessing function that demonstrates a moderate level of complexity. The model finds all golf courses within a radius of airports and creates a dataset.
  • Consuming the custom model tool—Once the model tool is tested, create a Visual Studio project to run the model in a console application.

Creating the custom model tool

Sample data can be found in <your ArcGIS Developer Kit install location>\Samples\ArcObjectsNET\AirportsAndGolf\data. This topic assumes you have copied the data folder to a new location on your hard drive at C:\AirportsAndGolf. Make sure you have the following files in the C:\AirportsAndGolf\data location:
  • airportgolf.mxd—Use this map document to test the model.
  • Find Golf Courses.tbx—Custom toolbox containing the custom model tool and a script tool (Validate Input), which is embedded in the model.
  • validateinput.py—Source Python script for the Validate Input script tool.
  • golf.gdb—Geodatabase containing the input data.
If you chose the default install option for the ArcObjects software development kit (SDK) for the Microsoft .NET Framework, the sample data can be found in C:\Program Files\ArcGIS\DeveloperKit10.1\Samples\data\AirportsAndGolf.
  1. Open the airportgolf.mxd map document from your local folder to explore the model tool in ArcMap. The Airports and Golf feature classes of the golf.gdb geodatabase are already added to the map as layers. Click to expand the Find Golf Courses toolbox (if not open) in the Catalog tree. See the following screen shot:

  2. Right-click the Golf Finder model and select Edit. The model opens in Edit mode. See the following diagram:

    • Airports is buffered with the Buffer distance. The letter "P" means they are model parameters and the values will be input by the user. Validate Input is a script tool that takes Airports as input and ensures the input is a Point feature layer. This tool is added to show how you can weave script tools with system tools in ModelBuilder.
    • The output of the Buffer tool is passed to the Identity tool as identity features and golf courses as input features. The Identity tool updates golf courses with the attributes of the Airport Buffer features if a golf course is in the buffered zone of an airport. If any golf course is not within any buffered zone, the record of that course has a value of –1 for the Airport Buffer feature ID (FID).
    • The Select tool filters only those golf courses that are near any of the airports, that is, fall within the buffer zone of one of the airports. The output of the Select tool is a model parameter, the value of which will be entered by the user.
  3. Close ModelBuiler.
For more information on how to create tools with ModelBuilder, see What is ModelBuilder? in the ArcGIS Desktop Help system.
  1. Examine the model parameters. In the Catalog tree of the airportgolf map document, double-click the Golf Finder model, which opens as a tool. See the following screen shot:


    The model variables with the letter "P" have become tool parameters. All four parameters are required as indicated by the green dots on the preceding screen shot. Next, you will look closer at the tool's parameters.
  2. Close the Golf Finder tool.
  3. Right-click the Golf Finder model in the Catalog tree and select Properties. See the following screen shot:



  4. When you select Properties on the preceding screen shot, the Golf Finder Properties dialog box appears. Click the Parameters tab on the dialog box. This dialog box is important if you want to change the parameter's order or set the filter with a parameter value. See the following screen shot:


  5. Click the Environments tab.
  6. Click the Values button. The Environment Settings dialog box appears. Add the path for golf.gdb in the Scratch Workspace text box. See the following screen shot:


  7. Close all dialog boxes. You will now run the tool to test whether it works.
Before you run the tool, make sure the overwriteOutput is set to true. In ArcMap, under the Geoprocessing menu, select Geoprocessing Options. Make sure the Overwrite the output of geoprocessing operations check box is selected. Also, clear the Enable check box under the Background Processing area if you want to see the progress dialog box when the tool is running.
When a variable is specified as a parameter, the letter "P" appears near the upper-right area of that variable.
  1. Right-click the Distance [value or field] parameter, click Rename, then type BufferDistance on the Rename dialog box. 
  2. Double-click the BufferDistance parameter, specify an initial linear unit of 26400 for testing the model, then specify Feet as the unit type.
There are 5,280 feet in a mile. The model performs a buffer of five miles (5280 * 5=26400). 
Specifying a linear unit in the model does not mean it is hard-coded when programming against the model in Visual Studio. Setting the linear unit allows easy testing of the initial parameters in ArcMap and ensures the model is correct before it is consumed in Visual Studio.

Running the custom model tool in ArcMap

Complete the following steps to run the model tool:
  1. Double-click Golf Finder on the Catalog tree to open the tool. On the Golf Finder dialog box, specify the parameters as follows:
    1. Airports parameter—Select the Airports layer from the drop-down list.
    2. Buffer distance—Type 8 in the Linear Unit text box and select Miles from the Linear Unit drop-down list.
    3. Golf courses—Select the Golf layer from the drop-down list.
    4. Golf courses near airports—Type C:\AirportsAndGolf\data\golf.gdb\nearbygolfcourses.
    See the following screen shot:

  2. Click OK to run the tool. When the tool executes successfully, a new layer (nearbygolfcourses) is added to the table of contents (TOC) in ArcMap.
If the tool fails, view the error messages on the results window. If the results window is not visible, click Results under the Geoprocessing menu in ArcMap.
If the results are not added to the TOC, make sure the Add results of geoprocessing operations to the display check box is selected on the Geoprocessing Options dialog box.
  • The resulting output attribute resembles the following screen shot. It shows which golf course is within the buffer distance of which airport. For example, Ridgewood Golf Course is within eight miles of the Cincinnati Muni airport.



    The tool is now ready to be consumed in a .NET application.
An error appears if the Overwrite the outputs of geoprocessing operations check box on the Geoprocessing Options dialog box is not selected, and you rerun the model. Delete outputs from the previous run or select the Overwrite the outputs of geoprocessing operations check box.
You can rerun the model from the results window. For more information, see Using geoprocessing options to control tool execution and Using the Results window in the ArcGIS Desktop Help system. To rerun the tool, double-click the tool-specific result node.

Consuming the custom model tool

You will now create a console application to test the model tool. You can set the parameter values in the application or read them from an Extensible Markup Language (XML) file. In this example, the parameters are set within the application. Next, write the code for the console application and test the results.

Creating a console application using the ArcGIS template IDE features

Complete the following steps to create a console application using integrated development environment (IDE) features:
  1. Start Visual Studio.
  2. Click File and click New Project. The New Project dialog box appears.
  3. On the New Project dialog box, click to expand the ArcGIS node in the Project types pane.
  4. Click the Extending ArcObjects node.
  5. Click Console Application (Desktop) or Console Application (Engine) under the Templates pane.
The nodes are available for the language you work with (that is, VB .NET or C#). This topic shows screen shots for C#, but the code required to complete the topic is provided in both VB .NET and C#.
The ArcGIS console application you choose depends on the products you have on your machine. If you have the ArcGIS Engine Developer Kit, use the Console Application (Engine). If you have ArcGIS for Desktop (Basic, Standard, or Advanced) use the Console Application (Desktop). The only differences will be your assembly and licensing choices on the ArcGIS Project Window dialog box. While the screen shots in this topic uses the Console Application (Desktop), the Console Application (Engine) also works with this code.
  1. On the New Project dialog box, type GeoprocessingInDotNet in the Name text field. See the following screen shot:

  2. Click OK. The ArcGIS Project Wizard appears.
  3. On the ArcGIS Project Wizard, add the following ArcGIS assemblies:

    ESRI.ArcGIS.Geoprocessing
    ESRI.ArcGIS.System
    ESRI.ArcGIS.Version

    See the following screen shot :


  4. Depending on the template you chose, you might see different groupings for the ArcGIS assemblies when the Add Reference sections show on the ArcGIS Project Wizard. Use the Filter by icon (on the preceding screen shot) to change to Products to view all of the ArcGIS assemblies.
  5. Click Next.
  6. Select the check box for the product for which you have a license.
  7. Click Finish to complete the wizard.
Only a basic ArcGIS Engine level of licensing is required in this topic. If you do not have ArcGIS Engine, but you have ArcGIS Desktop installed, choose the Basic level of licensing.

Adding code to the Visual Studio project

The following code examples are automatically added to the project:
[C#]
using System;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geoprocessing;


namespace GeoprocessingInDotNet
{
    class Program
    {
        private static LicenseInitializer m_AOLicenseInitializer=new
            GeoprocessingInDotNet.LicenseInitializer();
        [STAThread()] static void Main(string[] args)
        {
            //ESRI License Initializer generated code.
            m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[]
            {
                esriLicenseProductCode.esriLicenseProductCodeAdvanced
            }
            , new esriLicenseExtensionCode[]{}
            );

            // .... your code here.

            //ESRI License Initializer generated code.
            //Do not make any call to ArcObjects after ShutDownApplication().
            m_AOLicenseInitializer.ShutdownApplication();
        }
    }
}
[VB.NET]
Imports ESRI.ArcGIS.esriSystem
Imports ESRI.ArcGIS.Geoprocessing;


Module Module1

Private m_AOLicenseInitializer As LicenseInitializer=New WalkthroughVBNet.LicenseInitializer()
<STAThread()> _
           Sub Main()
    'ESRI License Initializer generated code.
    m_AOLicenseInitializer.InitializeApplication(New esriLicenseProductCode() {esriLicenseProductCode.esriLicenseProductCodeAdvanced}, _
                                                 New esriLicenseExtensionCode() {})
    
    ' ... your code here.
    
    'ESRI License Initializer generated code.
    'Do not make any call to ArcObjects after ShutDownApplication().
    m_AOLicenseInitializer.ShutdownApplication()
End Sub

End Module
  1. Load the active version to the project. Add ESRI.ArcGIS.Version as a reference to your project (type this line before the license initialization code). See the following code example:
[C#]
// Load the product code and version to the version manager.
//
ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
[VB.NET]
' Load the product code and version to the version manager.
'
ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop)
  1. Add the geoprocessing code between the InitializeApplication and ShutdownApplication codes. See the following code example:
[C#]
using System;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geoprocessing;

namespace GeoprocessingInDotNet2008
{
    class Program
    {
        private static LicenseInitializer m_AOLicenseInitializer=new
            GeoprocessingInDotNet2008.LicenseInitializer();
        [STAThread()] static void Main(string[] args)
        {

            // Load the product code and version to the version manager.
            ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);

            //ESRI License Initializer generated code.
            m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[]
            {
                esriLicenseProductCode.esriLicenseProductCodeAdvanced
            }
            , new esriLicenseExtensionCode[]{}
            );

            // Create geoprocessor. Overwrite true will replace existing output.
            IGeoProcessor2 gp=new GeoProcessorClass();
            gp.OverwriteOutput=true;

            // Get the workspace from the user.
            Console.WriteLine(
                "Enter the path to folder where you copied the data folder.");
            Console.WriteLine("Example: C:\\AirportsAndGolf\\data");
            Console.Write(">");
            string wks=Console.ReadLine();

            // Set the workspace to the value the user entered.
            gp.SetEnvironmentValue("workspace", wks + "\\" + "golf.gdb");

            // Add the custom toolbox to the geoprocessor.
            gp.AddToolbox(wks + "\\" + "Find Golf Courses.tbx");

            // Create a variant. Data is in the workspace.
            IVariantArray parameters=new VarArrayClass();
            parameters.Add("Airports");
            parameters.Add("8 Miles");
            parameters.Add("Golf");
            parameters.Add("GolfNearAirports");

            object sev=null;

            try
            {
                gp.Execute("GolfFinder", parameters, null);
                Console.WriteLine(gp.GetMessages(ref sev));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                string errorMsgs=gp.GetMessages(ref sev);
                Console.WriteLine(errorMsgs);
            }
            finally
            {
                Console.WriteLine("Hit Enter to quit");
                Console.ReadLine(); // Pause the console to view messages.
            }

            //ESRI License Initializer generated code.
            //Do not make any call to ArcObjects after ShutDownApplication().
            m_AOLicenseInitializer.ShutdownApplication();

        }
    }
}
[VB.NET]
Imports ESRI.ArcGIS.esriSystem
Imports ESRI.ArcGIS.Geoprocessing
Module Module1
Private m_AOLicenseInitializer As LicenseInitializer=New GeoprocessingInDotNet2008.LicenseInitializer()
<STAThread()> _
           Sub Main()
    
    ' Load the product code and version to the version manager.
    ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop)
    
    'ESRI License Initializer generated code.
    m_AOLicenseInitializer.InitializeApplication(New esriLicenseProductCode() {esriLicenseProductCode.esriLicenseProductCodeAdvanced}, _
                                                 New esriLicenseExtensionCode() {})
    
    ' Create geoprocessor. Overwrite true will replace existing output.
    Dim gp As IGeoProcessor2=New GeoProcessor()
    gp.OverwriteOutput=True
    
    ' Get the workspace from the user.
    Console.WriteLine("Enter the path to folder where you copied the data folder.")
    Console.WriteLine("Example: C:\\AirportsAndGolf\\data")
    Console.Write(">")
    Dim wks As String=Console.ReadLine()
    
    ' Set the workspace to the value the user entered.
    gp.SetEnvironmentValue("workspace", wks + "\golf.gdb")
    
    ' Add the custom toolbox to the geoprocessor.
    gp.AddToolbox(wks + "\Find Golf Courses.tbx")
    
    ' Create a variant. Data is in the workspace.
    Dim parameters As IVariantArray=New VarArray()
    parameters.Add("Airports")
    parameters.Add("8 Miles")
    parameters.Add("Golf")
    parameters.Add("GolfNearAirports")
    
    Dim sev As Object=Nothing
    
    Try
    gp.Execute("GolfFinder", parameters, Nothing)
    Console.WriteLine(gp.GetMessages(sev))
    Catch ex As Exception
    Console.WriteLine(ex.Message)
    Dim errorMsgs As String=gp.GetMessages(sev)
    Console.WriteLine(errorMsgs)
    Finally
    Console.WriteLine("Hit Enter to quit")
    Console.ReadLine() ' Pause the console to view messages.
    End Try
    
    'ESRI License Initializer generated code.
    'Do not make any call to ArcObjects after ShutDownApplication().
    m_AOLicenseInitializer.ShutdownApplication()
    
End Sub

End Module

Testing the code

Complete the following steps to test the code and process the application:
  1. Start Visual Studio.
  2. Click the Start Debugging  button and test the application. The application processes and returns the output. See the following screen shot:



See Also:

A quick tour of executing tools with ModelBuilder
How to run a geoprocessing tool
Sample: Consuming a geoprocessing custom model in .NET




To use the code in this topic, reference the following assemblies in your Visual Studio project. In the code files, you will need using (C#) or Imports (VB .NET) directives for the corresponding namespaces (given in parenthesis below if different from the assembly name):

Development licensing Deployment licensing
ArcGIS Desktop Basic ArcGIS Desktop Basic
ArcGIS Desktop Standard ArcGIS Desktop Standard
ArcGIS Desktop Advanced ArcGIS Desktop Advanced
Engine Developer Kit Engine