// get the model tool's parameter syntax from the model's helpstringinput_roads=@"C:\data\Input.gdb\PlanA_Roads";stringbuff_dist_field="Distance";// use values from a fieldstringinput_vegetation=@"C:\data\Input.gdb\vegetation";stringoutput_data=@"C:\data\Output.gdb\ClippedFC2";// the model name is ExtractVegetationstringtool_path=@"C:\data\MB\Models.tbx\ExtractVegetation";varargs= Geoprocessing.MakeValueArray(input_roads, buff_dist_field, input_vegetation, output_data);varresult=await Geoprocessing.ExecuteToolAsync(tool_path, args);
stringinput_data=@"C:\data\data.gdb\Population";stringout_pdf=@"C:\temp\Reports.pdf";stringfield_name="INCOME";// use defaults for other parameters - no need to pass any valuevararguments= Geoprocessing.MakeValueArray(input_data, out_pdf, field_name);stringtoolpath=@"C:\data\WorkflowTools.tbx\MakeHistogram";
Geoprocessing.OpenToolDialog(toolpath, arguments);
Open the Geoprocessing Tool Pane for a specific Tool
// For a System toolbox, to identify the specific tool to show, use// either:// o "ToolboxName.ToolName" - eg "analysis.Buffer"// o "Fullpath to Toolbox.tbx\Toolname" - eg:// "C:\ArcGIS\Resources\ArcToolBox\Toolboxes\Analysis Tools.tbx\Buffer"// note:// For legacy purposes, the convention "ToolName_ToolBox" is also supported so,// o "Buffer_analysis" would also work//// For a custom toolbox, the full path must be provided. So, for example,// given the custom toolbox "DeepThought.tbx" containing a python script tool// called "Answer", installed at "C:\Data\DeepThought-ProAddin\Toolboxes\toolboxes",// the full path would be:// o "C:\Data\DeepThought-ProAddin\Toolboxes\toolboxes\DeepThought.tbx\Answer"//Open the Buffer Tool GP Dialog - use either the full path or just //use "ToolboxName.ToolName"varpath=@"C:\ArcGIS\Resources\ArcToolBox\Toolboxes\Analysis Tools.tbx";varfull_tool_name= System.IO.Path.Combine(path,"Buffer");varshort_tool_name="analysis.Buffer";vartool_name= short_tool_name;//or full_tool_namevarextent= MapView.Active.Extent;varval_array=await QueuedTask.Run(()=>{varrect= GeometryEngine.Instance.Scale(extent, extent.Center,0.25,0.25)as Envelope;varpoly= PolygonBuilderEx.CreatePolygon(rect, rect.SpatialReference);vargeom=newList<object>(){ poly };return Geoprocessing.MakeValueArray(newobject[]{ geom,null,@"1000 Meters"});});//Call OpenToolDialog on the UI thread!
Geoprocessing.OpenToolDialog(tool_name, val_array,null,false);
Get Geoprocessing project items
vargpItems= CoreModule.CurrentProject.Items.OfType<GeoprocessingProjectItem>();// go through all the available toolboxesforeach(var gpItem in gpItems){varitemsInsideToolBox= gpItem.GetItems();// then for each toolbox list the tools insideforeach(var toolItem in itemsInsideToolBox){stringnewTool= String.Join(";",newstring[]{ toolItem.Path, toolItem.Name });// do something with the newTool// for example, add to a list to track or use them later}}
Stop a feature class created with GP from automatically adding to the map
// However, settings in Pro App's Geoprocessing Options will override option set in code// for example, in Pro App's Options > Geoprocessing dialog, if you check 'Add output datasets to an open map'// then the output WILL BE added to history overriding settings in codevarCopyfeaturesParams= Geoprocessing.MakeValueArray("C:\\data\\Input.gdb\\PlanA_Roads","C:\\data\\Input.gdb\\Roads_copy");IGPResultgpResult=await Geoprocessing.ExecuteToolAsync("management.CopyFeatures", CopyfeaturesParams,null,null,null, GPExecuteToolFlags.None);
GPExecuteToolFlags.AddToHistory will add the execution messages to History
// However, settings in Pro App's Geoprocessing Options will override option set in code// for example, if in Options > Geoprocessing dialog, if you uncheck 'Write geoprocessing operations to Geoprocessing History'// then the output will not be added to history.varargs2= Geoprocessing.MakeValueArray("C:\\data\\Vegetation.shp","NewField","TEXT");varresult2=await Geoprocessing.ExecuteToolAsync("management.AddField", args2,null,null,null, GPExecuteToolFlags.AddToHistory);
Multi Ring Buffer
//The data referenced in this snippet can be downloaded from the arcgis-pro-sdk-community-samples repo//https://github.com/Esri/arcgis-pro-sdk-community-samplesasyncTask<IGPResult>CreateRings(EditingTemplatecurrentTemplate){varparamsArray= Geoprocessing.MakeValueArray(currentTemplate.MapMember.Name,@"C:\Data\FeatureTest\FeatureTest.gdb\Points_MultipleRingBuffer",newList<string>{"1000","2000"},"Meters","Distance","ALL","FULL");IGPResultringsResult=await Geoprocessing.ExecuteToolAsync("Analysis.MultipleRingBuffer", paramsArray);varmessages=string.IsNullOrEmpty(gpResult.ReturnValue)?$@"Error in gp tool: {gpResult.ErrorMessages}":$@"Ok: {gpResult.ReturnValue}";returnringsResult;}
Non-blocking execution of a Geoprocessing tool
//The data referenced in this snippet can be downloaded from the arcgis-pro-sdk-community-samples repo//https://github.com/Esri/arcgis-pro-sdk-community-samplesstringin_data=@"C:\tools\data.gdb\cities";stringcities_buff=@"E:\data\data.gdb\cities_2km";varvalueArray= Geoprocessing.MakeValueArray(in_data, cities_buff,"2000 Meters");// to let the GP tool run asynchronously without blocking the main thread// use the GPThread option of GPExecuteToolFlasgs//GPExecuteToolFlagsflags= GPExecuteToolFlags.GPThread;// instruct the tool run non-blocking GPThreadIGPResultbufferResult=await Geoprocessing.ExecuteToolAsync("Analysis.Buffer", valueArray,null,null,null, flags);
How to pass parameter with multiple or complex input values
varenvironments= Geoprocessing.MakeEnvironmentArray(overwriteoutput:true);stringtoolName="Snap_edit";// or use edit.Snap// Snap tool takes multiple inputs each of which has// Three (3) parts: a feature class or layer, a string value and a distance// Each part is separated by a semicolon - you can get example of sytax from the tool documentation pagevarsnapEnv=@"'C:/SnapProject/fgdb.gdb/line_1' END '2 Meters';'C:/SnapProject/fgdb.gdb/points_1' VERTEX '1 Meters';'C:/SnapProject/fgdb.gdb/otherline_1' END '20 Meters'";varinfc=@"C:/SnapProject/fgdb.gdb/poly_1";varsnapParams= Geoprocessing.MakeValueArray(infc, snapEnv);GPExecuteToolFlagstokens= GPExecuteToolFlags.RefreshProjectItems | GPExecuteToolFlags.GPThread | GPExecuteToolFlags.AddToHistory;IGPResultsnapResult=await Geoprocessing.ExecuteToolAsync(toolName, parameters, environments,null,null, tokens);//return gpResult;
How to pass native objects as parameter values to run geoprocessing tool
stringtool2="analysis.Buffer";List<MapPoint>list=newList<MapPoint>();
list.Add(MapPointBuilderEx.CreateMapPoint(1.0,1.0));
list.Add(MapPointBuilderEx.CreateMapPoint(1.0,2.0));
list.Add(MapPointBuilderEx.CreateMapPoint(2.0,2.0));
list.Add(MapPointBuilderEx.CreateMapPoint(2.0,1.0));MultipointmultiPoint= MultipointBuilderEx.CreateMultipoint(list);varspatial_ref= SpatialReferenceBuilder.CreateSpatialReference(3857);varargs3=await QueuedTask.Run(()=>{return Geoprocessing.MakeValueArray(multiPoint,"memory\\Buffers","800 meters");});varenv1= Geoprocessing.MakeEnvironmentArray(outputCoordinateSystem: spatial_ref);varmessages=newList<string>();// list to collect all output messagesvarcts=new CancellationTokenSource();await Geoprocessing.ExecuteToolAsync(tool2, args3, env1, cts.Token);
How to access Geoprocessing History
stringopenProjectPath=@"D\DATA\IGPHistoryItemTestProject\IGPHistoryItemTestProject.aprx";await Project.OpenAsync(openProjectPath);MapProjectItemmapProjItem= Project.Current.GetItems<MapProjectItem>().FirstOrDefault(item => item.Name.Equals("Map", StringComparison.CurrentCultureIgnoreCase));varmap=await QueuedTask.Run(()=> mapProjItem.GetMap());varftrLayer= map.Layers[0]as FeatureLayer;stringtool1="management.GetCount";varargs1= Geoprocessing.MakeValueArray(ftrLayer);varenv= Geoprocessing.MakeEnvironmentArray(overwriteoutput:true);GPExecuteToolFlagsexecuteFlags= GPExecuteToolFlags.AddToHistory;vart=await Geoprocessing.ExecuteToolAsync(tool1, args1, env,null,null, executeFlags);IEnumerable<IGPHistoryItem>hisItems= Project.Current.GetProjectItemContainer(Geoprocessing.HistoryContainerKey)asIEnumerable<IGPHistoryItem>;StringhitemID="";StringhitemToolPath="";IGPResulthitemGPResult=null;DateTimehitemTimeStamp;foreach(var hitem in hisItems){// common IGPHistoryItem and Item propertieshitemID=(hitem as Item).ID;hitemToolPath= hitem.ToolPath;hitemGPResult= hitem.GPResult;hitemTimeStamp= hitem.TimeStamp;}
How to use Geoprocessing public event
ArcGIS.Desktop.Core.Events.GPExecuteToolEvent.Subscribe(e =>{stringid= e.ID;// Same as history IDif(e.IsStarting ==false)// Execute completed_= e.GPResult.ReturnValue; System.Windows.MessageBox.Show("event triggered.");});await Geoprocessing.ExecuteToolAsync("management.GetCount", Geoprocessing.MakeValueArray(@"c:\shape_file.shp"));
Parameter Value Array
Add Geometry via MakeValueArray to GP Tool parameter lists
vartool_name="analysis.Clip";varextent= MapView.Active.Extent;varsel_layer= MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault(l => l.Name =="GreatLakes");if(sel_layer==null)return;vargdb= Project.Current.DefaultGeodatabasePath;varout_fc= System.IO.Path.Combine(gdb,"clipped_lakes_out");varval_array=await QueuedTask.Run(()=>{varrect= GeometryEngine.Instance.Scale(extent, extent.Center,0.5,0.5)as Envelope;varclip_poly= PolygonBuilderEx.CreatePolygon(rect, rect.SpatialReference);//Add the geometry to a list before calling MakeValueArray//Envelope and Geometry types are supportedvargeom=newList<object>(){ clip_poly };return Geoprocessing.MakeValueArray(newobject[]{ sel_layer, geom, out_fc });});
Geoprocessing.ExecuteToolAsync(tool_name, val_array,null,null,null, GPExecuteToolFlags.InheritGPOptions);
Geoprocessing Options
Get GeoprocessingOptions
//These options are for behavior of interactive GP tools _only_.varoverwrite_gp= ApplicationOptions.GeoprocessingOptions.OverwriteExistingDatasets;varremove_gp= ApplicationOptions.GeoprocessingOptions.RemoveOverwrittenLayers;varaddoutput_gp= ApplicationOptions.GeoprocessingOptions.AddOutputDatasetsToOpenMap;varhistory_gp= ApplicationOptions.GeoprocessingOptions.WriteGPOperationsToHistory;
Set GeoprocessingOptions
//Note: changing these options modifies behavior of interactive GP tools _only_.//Use the ArcGIS.Desktop.Core.Geoprocessing.GPExecuteToolFlags enum parameter//to modify the behavior of Geoprocessing.ExecuteToolAsync(...)//Note: setting GeoprocessingOptions requires the QueuedTask
QueuedTask.Run(()=>{ ApplicationOptions.GeoprocessingOptions.SetOverwriteExistingDatasets(true); ApplicationOptions.GeoprocessingOptions.SetRemoveOverwrittenLayers(false); ApplicationOptions.GeoprocessingOptions.SetAddOutputDatasetsToOpenMap(true); ApplicationOptions.GeoprocessingOptions.SetWriteGPOperationsToHistory(false);});