执行GP工具

// Copyright 2012 ESRI
// 
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
// 
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
// 
// See the use restrictions.
// 

/*
 
 * copyfeatures.cs : This C# sample uses the Geoprocessor class in conjunction with geoprocessing tools classes to
 * execute a series of geoprocessing tools. This sample will extract features to a new feature class based on a
 * location and an attribute query.

*/

using System;
using System.Collections;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.DataManagementTools;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.AnalysisTools;

namespace copyfeatures
{
    class copyfeatures
    {
        [STAThread]
        static void Main(string[] args)
        {

            if (!ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Engine))
            {
                if (!ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop))
                {
                    System.Windows.Forms.MessageBox.Show("This application could not load the correct version of ArcGIS.");
                    return;
                }
            }

            LicenseInitializer aoLicenseInitializer = new LicenseInitializer();
            if (!aoLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeEngine, esriLicenseProductCode.esriLicenseProductCodeBasic, esriLicenseProductCode.esriLicenseProductCodeStandard, esriLicenseProductCode.esriLicenseProductCodeAdvanced },
            new esriLicenseExtensionCode[] { esriLicenseExtensionCode.esriLicenseExtensionCodeNetwork }))
            {
                System.Windows.Forms.MessageBox.Show("This application could not initialize with the correct ArcGIS license and will shutdown. LicenseMessage: " + aoLicenseInitializer.LicenseMessage());
                aoLicenseInitializer.ShutdownApplication();
                return;
            }

            // Run the geoprocessing code
            SelectFeaturesAndRunCopyFeatures();

            aoLicenseInitializer.ShutdownApplication();

        }


        private static void SelectFeaturesAndRunCopyFeatures()
        {
            ///
            // STEP 1: Make feature layers using the MakeFeatureLayer tool for the inputs to the SelectByLocation tool.
            ///

            // Initialize the Geoprocessor 
            Geoprocessor GP = new Geoprocessor();

            // Initialize the MakeFeatureLayer tool
            MakeFeatureLayer makefeaturelayer = new MakeFeatureLayer();
            makefeaturelayer.in_features = @"C:\data\nfld.gdb\wells";
            makefeaturelayer.out_layer = "Wells_Lyr";
            RunTool(GP, makefeaturelayer, null);

            makefeaturelayer.in_features = @"C:\data\nfld.gdb\bedrock";
            makefeaturelayer.out_layer = "bedrock_Lyr";
            RunTool(GP, makefeaturelayer, null);

            ///
            // STEP 2: Execute SelectLayerByLocation using the feature layers to select all wells that intersect the bedrock geology.
            ///

            // Initialize the SelectLayerByLocation tool
            SelectLayerByLocation SelectByLocation = new SelectLayerByLocation();

            SelectByLocation.in_layer = "Wells_Lyr";
            SelectByLocation.select_features = "bedrock_Lyr";
            SelectByLocation.overlap_type = "INTERSECT";
            RunTool(GP, SelectByLocation, null);

            /
            // STEP 3: Execute SelectLayerByAttribute to select all wells that have a well yield > 150 L/min.
            /

            // Initialize the SelectLayerByAttribute tool
            SelectLayerByAttribute SelectByAttribute = new SelectLayerByAttribute();

            SelectByAttribute.in_layer_or_view = "Wells_Lyr";
            SelectByAttribute.selection_type = "NEW_SELECTION";
            SelectByAttribute.where_clause = "WELL_YIELD > 150";
            RunTool(GP, SelectByAttribute, null);

            
            // STEP 4: Execute CopyFeatures tool to create a new feature class of wells with well yield > 150 L/min.
            

            // Initialize the CopyFeatures tool
            CopyFeatures CopyFeatures = new CopyFeatures();

            CopyFeatures.in_features = "Wells_Lyr";
            CopyFeatures.out_feature_class = @"C:\data\nfld.gdb\high_yield_wells";


            RunTool(GP, CopyFeatures, null);
        }


        private static void RunTool(Geoprocessor geoprocessor, IGPProcess process, ITrackCancel TC)
        {
    
            // Set the overwrite output option to true
            geoprocessor.OverwriteOutput = true;

            // Execute the tool            
            try
            {
                geoprocessor.Execute(process, null);
                ReturnMessages(geoprocessor);

            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
                ReturnMessages(geoprocessor);
            }
        }

        // Function for returning the tool messages.
        private static void ReturnMessages(Geoprocessor gp)
        {
            if (gp.MessageCount > 0)
            {
                for (int Count = 0; Count <= gp.MessageCount - 1; Count++)
                {
                    Console.WriteLine(gp.GetMessage(Count));
                }
            }

        }
    }
}




Using ArcObjects as tool input


Summary
As discussed in the topic The role of geoprocessing in developing applications, one common misconception is that geoprocessing tools can only deal with pathname strings for feature data. This topic shows how to use interface objects such as IFeatureClass, IName, workspace, spatial reference, and other ArcObjects as tool input.


Using ArcObjects reference

The ArcObjects that can be passed to a parameter depends on the parameter of the tool. Specific information of a parameter can be found in the tool’s reference page. See Using a tool reference page for more information.
IFeatureClass, ILayer, IName, and IDataset objects can be used to define the input to any tool that accepts a feature class or feature layer. Additionally, an IRasterDataset object can be used as input to any tool that accepts a raster dataset or raster layer. An IFeatureWorkspace object can be passed if the parameter accepts a catalog path. An ITable or IStandAloneTable object can be used instead of a database file format (DBF) or geodatabase table. An ISpatialReference object can be passed if the data type of the parameter is Coordinate System.
A tool that updates an existing dataset, such as the Append tool, can have the output dataset defined using an ArcObjects component, such as IFeatureClass, because Append doesn’t have an output dataset; the dataset it is updating is an input to the tool.
In the following code example, the Buffer tool takes an IFeatureClass object as input features. As the tool creates a new feature class, a catalog path must be used for output.
[C#]
public void IFeatureClassAsInput(IFeatureClass pFC, string buff_dist)
{
    // Create the geoprocessor.
    IGeoProcessor2 gp = new GeoProcessorClass();
    gp.OverwriteOutput = true;

    // Create variant array and populate with parameter values.
    IVariantArray parameters = new VarArrayClass();
    parameters.Add(pFC);
    parameters.Add(@"C:\temp\poitns_buff.shp");
    parameters.Add(buff_dist);

    // Execute the tool.
    gp.Execute("Buffer_analysis", parameters, null);
}

The following code example shows a map document with an ILayer object joined to an ITable object. For the field parameters, you could pass IField objects instead of string field names.
[C#]
public void AddJoinWithILayerITable(string sMap, ITable pTable)
{
    IGeoProcessor2 gp = new GeoProcessorClass();
    IMapDocument pMapDoc = new MapDocumentClass();
    pMapDoc.Open(sMap, "");
    IMap pMap = pMapDoc.get_Map(0);
    ILayer pLayer = pMap.get_Layers(null, true).Next();
    IVariantArray parameters = new VarArrayClass();
    parameters.Add(pLayer);
    parameters.Add("BEAT"); // in_field
    parameters.Add(pTable);
    parameters.Add("BEAT"); // join_field
    gp.Execute("AddJoin_management", parameters, null);
}

Although a newly created output must be passed as a catalog path, a parameter expecting a workspace can be populated with an IWorkspace object. In the following code example, the Create Feature Dataset tool also accepts an ISpatialReference object as input:
[C#]
public void createFeatureDataset(IWorkspace workspace, ISpatialReference spatialRef)
{
    try
    {
        IVariantArray parameters = new VarArrayClass();
        parameters.Add(workspace);
        parameters.Add("Rivers");
        parameters.Add(spatialRef);
        gp.Execute("CreateFeatureDataset_management", parameters, null);
    }
    catch (Exception ex)
    {
        object sev = null;
        string msgs = gp.GetMessages(ref sev);
    }
}

Using in_memory workspace

You can use  in_memory workspace for intermediate tool outputs. Avoid using in_memory workspace for large datasets, as memory is always a limitation. See Using in_memory workspace for more information.
Some tools (for example, the Project tool) do not accept in_memory as output workspace. Check the tool’s reference page to make sure the tool allows in_memory workspace.
[C#]
public void InMemoryWorkspaceTest(IArray points)
{
    IGeoProcessor2 gp = new GeoProcessorClass();

    IGPUtilities3 util = new GPUtilitiesClass();
    gp.OverwriteOutput = true;

    IVariantArray parameters = new VarArrayClass();
    parameters.Add("in_memory");
    parameters.Add("Parks");
    parameters.Add("POINT");
    parameters.Add(@"C:\gpqa\mytools\append\wells.gdb\well_1a");

    IGeoProcessorResult result = (IGeoProcessorResult)gp.Execute(
        "CreateFeatureclass_management", parameters, null);

    IGPValue gpVal = result.GetOutput(0);
    string inmemfc = gpVal.GetAsText();

    IFeatureClass pFC = util.OpenFeatureClassFromString(inmemfc);
    IFeatureBuffer buff = pFC.CreateFeatureBuffer();
    IFeatureCursor cur = pFC.Insert(true);

    object featureOID;
    ESRI.ArcGIS.Geometry.IPoint pt;
    for (int i = 0; i < points.Count; i++)
    {
        pt = new ESRI.ArcGIS.Geometry.PointClass();
        pt = (Point)points.get_Element(i);
        buff.Shape = pt;
        featureOID = cur.InsertFeature(buff);
    }
    cur.Flush();

    parameters.RemoveAll();
    parameters.Add(result.GetOutput(0).GetAsText());
    parameters.Add(@"C:\sdk\data\testdata.gdb\in_mem_out");

    gp.Execute("CopyFeatures_management", parameters, null);
}

Using Feature Set and Record Set

Geoprocessing also provides Feature Set and Record Set data types to hold features and records in memory. The only use of Feature Set is to send features to a geoprocessing server. Using these types programmatically is complicated. A better option is to create an in_memory feature class using a geoprocessing tool such as Create Feature Class.
The following code example executes the BestPath service on bdhost ArcGIS Server in the gp/Routing. The service has one parameter of Feature Set type. It loads the incoming IFeatureClass object to a Feature Set and then passes it to the server tool. For more information, see An overview of geoprocessing with ArcGIS for Server.
[C#]
public void FeatureSetUsingServer(IFeatureClass pFC)
{
    IGeoProcessor2 gp = new GeoProcessorClass();

    gp.AddToolbox(@"http://bdhost/arcgis/services;gp/Routing");
    ITable table = (ITable)pFC;
    IRecordSetInit rsInit = new RecordSetClass();

    IQueryFilter2 qf = new QueryFilterClass();
    rsInit.SetSourceTable(table, qf); // Load fc.

    IRecordSet rs = rsInit as IRecordSet;
    IGPRecordSet gprs = new GPFeatureRecordSetLayerClass();

    gprs.RecordSet = rs;

    IVariantArray params = new VarArrayClass();
    parameters.Add(gprs);
    IGeoProcessorResult result;
    try
    {
        result = (IGeoProcessorResult)gp.Execute("BestPath", params, null);
        while (result.Status != esriJobStatus.esriJobSucceeded)
            System.Threading.Thread.Sleep(250);
        // Do next task with result.GetOutput(0).
    }
    catch (Exception ex)
    {
        object sev = null;
        string messages = gp.GetMessages(ref sev);
    }
}




How to run a geoprocessing tool



Running a geoprocessing tool

Each geoprocessing tool has a fixed set of parameters that provide the tool with the information it needs for execution. Tools usually have input parameters that define the dataset or datasets that will typically be used to generate new output data. Parameters have the following important properties:
  • Name—Each tool parameter has a unique name.
  • Type—The type of data expected, such as a feature class, integer, string, and raster.
  • Required—Either a value must be provided for a parameter, or it is optional.
Each tool has a documentation page known as a tool reference page. For more information about parameters, see  Interpreting a tool reference page.
When a tool is used in a program, its parameter values must be set correctly so it can execute when the program runs. The documentation of each tool clearly defines its parameters and properties. Once a valid set of parameter values is provided, the tool is ready to be executed.
Parameters are specified as strings or objects. Strings are text values that uniquely identify a parameter value, such as a path to a dataset or a keyword. Most tool parameters can be specified as a simple string. However, complex parameters, such as a spatial reference, can be easier to specify with an object. Each tool has its own parameter types. To get complete information on a particular tool, review the tool reference page. Interpreting a tool reference page explains how to read a tool reference page and extract information to use in .NET.
You can run a geoprocessing tool by using the Geoprocessing library methods or by the geoprocessor managed assembly methods. For information about the basic differences between the two approaches, see  Executing tools. In both cases, the  Execute method of the geoprocessor is called.
The Execute method uses a null reference instead of an  ITrackCancel interface. The ITrackCancel interface provides access to properties and methods that determine if a cancellation has been executed by the user and also allows developers to specify what actions constitute a cancellation. Both approaches are elaborated with the following examples.

Using the geoprocessing assembly

The geoprocessing assembly is the Component Object Model (COM) interop of the Geoprocessing type library. The Execute method of the IGeoProcessor2 interface of the library is used to run a tool.
The following are the generic steps to execute a tool:
  1. Add a reference to ESRI.ArcGIS.Geoprocessing to your project. This is the only reference you need if you use the geoprocessing assembly.
  2. Create the geoprocessor object.
  3. Add the path to the custom toolbox if you are running a custom tool.
  4. Create an IVariantArray and populate it with tool parameter values. The IVariantArray is available through the esriSystem library.
  5. Call the Execute method on the geoprocessor.
The process is the same if you run a system tool or a custom tool.
Make sure you maintain the order of parameters as specified in the tool reference page when populating the variant array. Follow the syntax section of the tool reference page (see link at the bottom), it shows the correct ordering of parameters.
If you want to skip an optional parameter, just add an empty string to the variant array in correct order. For example, if a tool's third, fourth and fifth parameters are optional and you want to pass value only to the fifth parameter, then you have to pass empty strings to the third and fourth parameters to maintain correct ordering.
Passing an empty string instructs the tool to use the default value of that parameter.
Do not follow the tool's dialog box to get the order of parameters; follow the tool's Help page (browse to Interpreting a tool reference page link at the end). Parameters are arranged on a tool dialog box by "display order" not by the actual order.
Executing a system tool
The following code example shows the execution of the Buffer tool from the Analysis toolbox. The required parameters for the tool are defined. In this case, strings are used to define the input, output, and buffer distance properties, so the call to the tool is easier to read.
[C#]
using System;
using System.Threading;
// Add references to esriSystem for licensing and IVariantArray.
using ESRI.ArcGIS.esriSystem;
// Add a reference to the geoprocessing namespace.
using ESRI.ArcGIS.Geoprocessing;

// Call this method from your main.
private static void RunBuffer()
{
    // Create the geoprocessor.
    IGeoProcessor2 gp = new GeoProcessorClass();
    gp.OverwriteOutput = true;

    IGeoProcessorResult result = new GeoProcessorResultClass();

    // Create a variant array to hold the parameter values.
    IVariantArray parameters = new VarArrayClass();

    object sev = null;

    try
    {
        // Populate the variant array with parameter values.
        parameters.Add(@"C:\data\california.gdb\cities");
        parameters.Add(@"C:\data\california.gdb\cities_buff");
        parameters.Add("1000 Meters");

        // Execute the tool.
        result = gp.Execute("Buffer_analysis", parameters, null);

        // Wait until the execution completes.
        while (result.Status == esriJobStatus.esriJobExecuting)
            Thread.Sleep(1000);
        // Wait for 1 second.

        // Print geoprocessring messages.
        Console.WriteLine(gp.GetMessages(ref sev));
    }

    catch (Exception ex)
    {
        // Print a generic exception message.
        Console.WriteLine(ex.Message);

        // Print geoprocessing execution error messages.
        Console.WriteLine(gp.GetMessages(ref sev));
    }
}

Executing a custom tool
In addition to using the existing tools and toolboxes provided by Esri, you can also execute custom tools, such as model tools and script tools, that exist in custom toolboxes. The process is the same for system or custom tools when you use IGeoProcessor2.Execute. As all system toolboxes are readily available to the geoprocessor, you do not need to add the toolbox to the geoprocessor. However, you must add the custom toolbox to the geoprocessor using the  AddToolboxmethod.
The following code example shows how to execute the CalculateBestPath custom tool in the BestPath.tbx toolbox:
The only difference between running a system tool and a custom tool is adding the custom toolbox to the geoprocessor. For more information on system and custom tools, see  Essential geoprocessing vocabulary in the ArcGIS Desktop Help system.
[C#]
public void SampleCalculateBestPathToolGping()
{
    // Initialize the geoprocessor.
    IGeoProcessor2 gp = new GeoProcessorClass();

    // Add the BestPath toolbox.
    gp.AddToolbox(@"C:\SanDiego\BestPath.tbx");

    // Generate the array of parameters.
    IVariantArray parameters = new VarArrayClass();
    parameters.Add(@"C:\SanDiego\source.shp");
    parameters.Add(@"C:\SanDiego\destination.shp");
    parameters.Add(@"C:\SanDiego\bestpath.shp");

    object sev = null;
    try
    {
        // Execute the model tool by name.
        gp.Execute("CalculateBestPath", parameters, null);

        Console.WriteLine(gp.GetMessages(ref sev));
    }
    catch (Exception ex)
    {
        // Print geoprocessing execution error messages.
        Console.WriteLine(gp.GetMessages(ref sev));
    }
}

Always surround your code with try-catch blocks, because the Execute method throws an exception if the tool fails to run.

Using the geoprocessor managed assembly

The following are the general steps to run a tool:
  1. Add a reference to ESRI.ArcGIS.Geoprocessor. You may also need to add the ESRI.ArcGIS.Geoprocessing assembly if you want to use, for example, the result object or list datasets.
  2. Additionally, add a reference to the toolbox assembly to which the tool belongs. If you use more than one tool from different toolboxes, also add managed assemblies for those toolboxes.
  3. Create the geoprocessor object.
  4. Add the path to the custom toolbox if you are running a custom tool.
  5. Create a tool process object and set the parameter values.
  6. Call the Execute method on the geoprocessor.
Executing a system tool with managed assembly
In the following code example, the Buffer tool is executed with the same parameter values by using the managed assemblies:
[C#]
// Add the geoprocessor namespace.
using ESRI.ArcGIS.Geoprocessor;
// Add the toolbox assembly.
using ESRI.ArcGIS.AnalysisTools;

public void SampleBufferTool()
{

    // Create the geoprocessor. 
    Geoprocessor GP = new Geoprocessor();

    // Create the tool process object.
    ESRI.ArcGIS.AnalysisTools.Buffer bufferTool = new
        ESRI.ArcGIS.AnalysisTools.Buffer();

    // Set parameter values.
    bufferTool.in_features = @"D:\St_Johns\data.mdb\roads";
    bufferTool.out_feature_class = @"D:\St_Johns\data.mdb\roads_Buffer";
    bufferTool.buffer_distance_or_field = "distance";

    object sev = null;
    try
    {
        // Execute the tool.
        GP.Execute(bufferTool, null);

        Console.WriteLine(GP.GetMessages(ref sev));
    }
    catch (Exception ex)
    {
        // Print geoprocessing execution error messages.
        Console.WriteLine(GP.GetMessages(ref sev));
    }

}

Executing a custom tool with managed assembly
Custom toolboxes do not have any managed assembly. Therefore, the simplest way to run a custom tool is by using IVariantArray and executing the tool by name. The Execute method of the geoprocessor is overloaded and has an additional argument list that allows you to execute a tool by specifying the tool name, the parameters of the tool, and the ITrackCancel interface. First, add your custom toolbox to the geoprocessor using the AddToolbox method. See the following code example:
[C#]
public void SampleCalculateBestPathTool()
{

    // Initialize the geoprocessor.
    Geoprocessor GP = new Geoprocessor();

    // Add the BestPath toolbox.
    GP.AddToolbox(@"C:\SanDiego\BestPath.tbx");

    // Generate the array of parameters.
    IVariantArray parameters = new VarArrayClass();
    parameters.Add(@"C:\SanDiego\source.shp");
    parameters.Add(@"C:\SanDiego\destination.shp");
    parameters.Add(@"C:\SanDiego\bestpath.shp");

    object sev = null;
    try
    {
        // Execute the model tool by name.
        GP.Execute("CalculateBestPath", parameters, null);

        Console.WriteLine(GP.GetMessages(ref sev));
    }
    catch (Exception ex)
    {
        // Print geoprocessing execution error messages.
        Console.WriteLine(GP.GetMessages(ref sev));
    }

}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值