/// <summary> /// Converts the given inFeatureClass to a 3d featureclass using the given height field. If out featureclass exist it will be overwritten. /// </summary> /// <param name="inFeatureClass"></param> /// <param name="outFeatureClass"></param> /// <param name="heightField"></param> public static void Convert2dTo3dByAttr(object inFeatureClass, object outFeatureClass, object heightField, object toHeightField = null) { var geoprocessor = new Geoprocessor() { OverwriteOutput = true, AddOutputsToMap = false }; try { Delete(outFeatureClass); FeatureTo3DByAttribute featureTo3D = new FeatureTo3DByAttribute(inFeatureClass, outFeatureClass, heightField) { to_height_field = toHeightField }; geoprocessor.Execute(featureTo3D, null); } catch (Exception) { if (geoprocessor.MessageCount > 0) { string excMessage = null; for (int Count = 0; Count <= geoprocessor.MessageCount - 1; Count++) { excMessage += geoprocessor.GetMessage(Count) + Environment.NewLine; } throw new Exception(excMessage); } } }
/// <summary> /// 在数据集中构建拓扑(GP方法) /// </summary> /// <param name="IN_TopoName">要生成拓扑的名称</param> /// <param name="IN_Tolerance">拓扑容差,可选,默认0.001</param> public void PUB_TopoBuildWithGP(string IN_TopoName, double IN_Tolerance = 0.001) { TP_topoName = IN_TopoName; IWorkspace FeatureWorkSpace = FeatureDataset_Main.Workspace; ITopologyWorkspace TopoWorkSpace = FeatureWorkSpace as ITopologyWorkspace; try//若不存在同名拓扑则添加 { Topology = TopoWorkSpace.OpenTopology(IN_TopoName); CommonClass common = new CommonClass(); common.DeleteTopolgyFromGISDB(Topology); DeleteFeature(TP_topoName); } catch { } CreateTopology Topotool = new CreateTopology();//拓扑GP工具 Topotool.in_dataset = FeatureDataset_Main;; Topotool.out_name = IN_TopoName; Topotool.in_cluster_tolerance = IN_Tolerance; try { GP_Tool.Execute(Topotool, null); Topology = TopoWorkSpace.OpenTopology(IN_TopoName); } catch (COMException comExc) { MessageBox.Show(String.Format("拓扑创建出错: {0} 描述: {1}", comExc.ErrorCode, comExc.Message)); } }
private String RasterAPuntos(string sRasterLayer, string sOutputFC, Geoprocessor gp) { string sCapaMpios_parques_cobertura = "mpios_parques_cobertura"; string sFCCruce = _sigpi.Parametros.RutaGBD + "\\" + sCapaMpios_parques_cobertura; try { RasterToPoint raster2Pnt = new RasterToPoint(sRasterLayer, sOutputFC); raster2Pnt.raster_field = "VALUE"; gp.Execute(raster2Pnt, null); Intersect intersect = new Intersect(); intersect.in_features = sOutputFC + " ; " + sFCCruce; intersect.out_feature_class = sOutputFC.Replace(".shp", "_intersect.shp"); intersect.join_attributes = "NO_FID"; intersect.output_type = "POINT"; gp.Execute(intersect, null); return(intersect.out_feature_class.ToString()); } catch (Exception ex) { throw new Exception("Verifique que exista información para el día seleccionado"); } }
/// <summary> /// Borra los archivos raster del directorio temporal /// </summary> private void BorrarTemporales() { Geoprocessor gp = new Geoprocessor(); gp.SetEnvironmentValue("workspace", System.IO.Path.GetTempPath()); IGpEnumList rasters = gp.ListRasters("*", "All"); Delete del = new Delete(); string sRaster = rasters.Next(); del.data_type = "RasterDataset"; while (sRaster != "") { del.in_data = System.IO.Path.GetTempPath() + "\\" + sRaster; gp.Execute(del, null); sRaster = rasters.Next(); } try { IGpEnumList ws = gp.ListWorkspaces("*", "FileGDB"); string sRutaWs = ws.Next(); del.data_type = ""; while (sRutaWs != "") { del.in_data = sRutaWs; gp.Execute(del, null); sRutaWs = ws.Next(); } MessageBox.Show("Archivos Temporales Borrados"); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// 在数据集中构建拓扑(GP方法) /// </summary> /// <param name="IN_TopoName">要生成拓扑的名称</param> /// <param name="IN_Tolerance">拓扑容差,可选,默认0.001</param> public void PUB_TopoBuildWithGP(string IN_TopoName, double IN_Tolerance = 0.001) { IWorkspace FeatureWorkSpace = FeatureDataset_Main.Workspace; ITopologyWorkspace TopoWorkSpace = FeatureWorkSpace as ITopologyWorkspace; try//若不存在同名拓扑则添加 { Topology = TopoWorkSpace.OpenTopology(IN_TopoName); MessageBox.Show("已存在该拓扑,无法添加!"); } catch { CreateTopology Topotool = new CreateTopology();//拓扑GP工具 Topotool.in_dataset = FeatureDataset_Main;; Topotool.out_name = IN_TopoName; Topotool.in_cluster_tolerance = IN_Tolerance; try { GP_Tool.Execute(Topotool, null); Topology = TopoWorkSpace.OpenTopology(IN_TopoName); } catch (COMException comExc) { MessageBox.Show(String.Format("拓扑创建出错: {0} 描述: {1}", comExc.ErrorCode, comExc.Message)); } } }
// 空间分析:按掩模提取 private void ExtractByMask(object in_raster, object in_mask_data, object out_raster) { ESRI.ArcGIS.SpatialAnalystTools.ExtractByMask pTool = new ESRI.ArcGIS.SpatialAnalystTools.ExtractByMask() { in_raster = in_raster, in_mask_data = in_mask_data, out_raster = out_raster }; GP.Execute(pTool, null); }
static Dictionary <int, int> GetFeatureVertexCount(string fcPath) { Dictionary <int, int> pntCntDict = new Dictionary <int, int>(); Geoprocessor gp = new Geoprocessor { OverwriteOutput = true }; try { AddField addField = new AddField { in_table = fcPath, field_name = "PointCount", field_type = "LONG" }; gp.Execute(addField, null); CalculateField calcField = new CalculateField { in_table = fcPath, field = "PointCount", expression = "!Shape!.pointcount", expression_type = "PYTHON" }; gp.Execute(calcField, null); } catch (COMException) { object sev = 2; Console.WriteLine(gp.GetMessages(ref sev)); } IGPUtilities gpUtilities = new GPUtilitiesClass(); IFeatureClass featClass = gpUtilities.OpenFeatureClassFromString(fcPath); int fieldIndex = featClass.FindField("PointCount"); IQueryFilter qf = new QueryFilterClass { SubFields = "PointCount" }; ICursor cursor = featClass.Search(qf, true) as Cursor; IRow row; while ((row = cursor.NextRow()) != null) { pntCntDict.Add(row.OID, (int)row.Value[fieldIndex]); } return(pntCntDict); }
//Creates raster dataset using GP CreateRasterDataset class static void CreateRasterDS() { try { //Initialize GeoProcessor Geoprocessor geoProcessor = new Geoprocessor(); //Create file geodatabase CreateFileGDB createFileGDB = new CreateFileGDB(); createFileGDB.out_folder_path = outputFolder; createFileGDB.out_name = outFGDB; geoProcessor.Execute(createFileGDB, null); //Create a Raster Dataset CreateRasterDataset createRasterDataset = new CreateRasterDataset(); //Set parameters //Set output location and name createRasterDataset.out_name = dsName; createRasterDataset.out_path = FGDBPath; //Set number of band to 3 createRasterDataset.number_of_bands = 3; //Set pixel type to unsigned 8 bit integer createRasterDataset.pixel_type = "8_BIT_UNSIGNED"; //Build pyramid layers with GDB calculated number of levels createRasterDataset.pyramids = "PYRAMIDS -1 BILINEAR"; //Set GDB dataset properties //Set JPEG compression of quality 50 createRasterDataset.compression = "JPEG 50"; //Set pyramid origin point so it takes advantage of partial pyramid building when mosaicking //Need to make sure that any raster that will be mosaicked is to the southeast of this point //If the rasters are in GCS, the following origin point is good. //createRasterDataset.pyramid_origin = "-180 90"; //Execute the tool to create a raster dataset geoProcessor.Execute(createRasterDataset, null); ReturnMessages(geoProcessor); } catch (Exception exc) { Console.WriteLine(exc.Message); } }
private IGeoProcessorResult UnionOverlay(Geoprocessor gp) { IGpValueTableObject vtobject = new GpValueTableObject() as IGpValueTableObject; vtobject.SetColumns(1); object row = ""; row = GetFeatureLayer(strInputLayer); vtobject.AddRow(ref row); row = GetFeatureLayer(strOverLayer); vtobject.AddRow(ref row); IVariantArray pVarArray = new VarArrayClass(); pVarArray.Add(vtobject); string outputFullPath = System.IO.Path.Combine (strOutputPath, strInputLayer + "_" + strOverLayer + "_" + "Union.shp"); pVarArray.Add(outputFullPath); pVarArray.Add(strJoinAttributeType); pVarArray.Add(tolerance); IGeoProcessorResult results = gp.Execute ("Union_analysis", pVarArray, null) as IGeoProcessorResult; System.Runtime.InteropServices.Marshal.ReleaseComObject(pVarArray); System.Runtime.InteropServices.Marshal.ReleaseComObject(vtobject); return(results); }
/// <summary> /// 两图层进行裁剪运算 /// </summary> /// <param name="inputLayer">被裁剪图层</param> /// <param name="clipLayer">裁剪图层</param> /// <param name="outputFullPath">输出图层完整路径</param> public void ClipByLayer(ILayer inputLayer, ILayer clipLayer, string outputFullPath) { string inputPath = GetLayerPath(inputLayer); string clipPath = GetLayerPath(clipLayer); Clip clipTool = new Clip(); clipTool.in_features = inputPath; clipTool.clip_features = clipPath; clipTool.out_feature_class = outputFullPath; Geoprocessor processor = new Geoprocessor(); IGPProcess process = null; processor.OverwriteOutput = true; process = clipTool; processor.Validate(process, true); processor.Execute(process, null); FileInfo fi = new FileInfo(outputFullPath); string pathDir = fi.Directory.FullName; string name = fi.Name; IWorkspaceFactory wsf = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace fws = wsf.OpenFromFile(pathDir, 0) as IFeatureWorkspace; IFeatureClass featCls = fws.OpenFeatureClass(name); IFeatureLayer layer = new FeatureLayerClass(); layer.FeatureClass = featCls; layer.Name = featCls.AliasName; m_mapControl.Map.AddLayer(layer as ILayer); }
public static void ExtractValuesToPoints(object points, object raster, object outpoints) { var geoprocessor = new Geoprocessor() { OverwriteOutput = true, AddOutputsToMap = false }; try { ExtractValuesToPoints extract = new ExtractValuesToPoints(points, raster, outpoints); geoprocessor.Execute(extract, null); } catch (Exception) { if (geoprocessor.MessageCount > 0) { string excMessage = null; for (int Count = 0; Count <= geoprocessor.MessageCount - 1; Count++) { excMessage += geoprocessor.GetMessage(Count) + Environment.NewLine; } throw new Exception(excMessage); } } }
public static void AlterField(object inFeatureClass, object field, string newName, string newAlias = null) { var geoprocessor = new Geoprocessor() { OverwriteOutput = true, AddOutputsToMap = false }; try { AlterField alter = new AlterField(inFeatureClass, field) { new_field_name = newName, new_field_alias = newAlias ?? newName }; geoprocessor.Execute(alter, null); } catch (Exception) { if (geoprocessor.MessageCount > 0) { string excMessage = null; for (int Count = 0; Count <= geoprocessor.MessageCount - 1; Count++) { excMessage += geoprocessor.GetMessage(Count) + Environment.NewLine; } throw new Exception(excMessage); } } }
public static void Append(object inputs, object target) { var geoprocessor = new Geoprocessor() { OverwriteOutput = true, AddOutputsToMap = false }; try { Append append = new Append(inputs, target); geoprocessor.Execute(append, null); } catch (Exception) { if (geoprocessor.MessageCount > 0) { string excMessage = null; for (int Count = 0; Count <= geoprocessor.MessageCount - 1; Count++) { excMessage += geoprocessor.GetMessage(Count) + Environment.NewLine; } throw new Exception(excMessage); } } }
public static void DeleteFeatures(object infeatures) { var geoprocessor = new Geoprocessor() { OverwriteOutput = true, AddOutputsToMap = false }; try { DeleteFeatures del = new DeleteFeatures(infeatures); geoprocessor.Execute(del, null); } catch (Exception) { if (geoprocessor.MessageCount > 0) { string excMessage = null; for (int Count = 0; Count <= geoprocessor.MessageCount - 1; Count++) { excMessage += geoprocessor.GetMessage(Count) + Environment.NewLine; } throw new Exception(excMessage); } } }
public static void CalculateField(object table, string fldName, object expression) { var geoprocessor = new Geoprocessor() { OverwriteOutput = true, AddOutputsToMap = false }; try { CalculateField fieldCalc = new CalculateField(table, fldName, expression) { expression_type = "PYTHON_9.3" }; geoprocessor.Execute(fieldCalc, null); } catch (Exception) { if (geoprocessor.MessageCount > 0) { string excMessage = null; for (int Count = 0; Count <= geoprocessor.MessageCount - 1; Count++) { excMessage += geoprocessor.GetMessage(Count) + Environment.NewLine; } throw new Exception(excMessage); } } }
private void btnCalculate_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; //计算默认索引 try { ESRI.ArcGIS.DataManagementTools.CalculateDefaultGridIndex vCalculateDefault = new ESRI.ArcGIS.DataManagementTools.CalculateDefaultGridIndex(); vCalculateDefault.in_features = m_pFeaCls; Geoprocessor gp = new Geoprocessor(); gp.OverwriteOutput = true; gp.Execute(vCalculateDefault, null); this.txtGridSize1.Text = vCalculateDefault.grid_index1.ToString(); this.txtGridSize2.Text = vCalculateDefault.grid_index2.ToString(); this.txtGridSize3.Text = vCalculateDefault.grid_index3.ToString(); } catch { } this.Cursor = Cursors.Default; }
//执行计算,输出计算结果信息字符串 private string FieldCal(IFeatureLayer pFtLayer, string strExpression) { txtMessage.Text = "正在计算请稍后……\r\n"; try { Geoprocessor Gp = new Geoprocessor(); Gp.OverwriteOutput = true; CalculateField calField = new CalculateField(); calField.expression = strExpression; Gp.Execute(calField, null); for (int i = 0; i < Gp.MessageCount; i++) { txtMessage.Text += Gp.GetMessage(i).ToString() + "\r\n"; } return "计算成功"; } catch (Exception e) { txtMessage.Text += e.Message; return "计算失败" + e.Message; } }
public static void AddField(object table, string fieldName, string fieldtype) { var geoprocessor = new Geoprocessor() { OverwriteOutput = true, AddOutputsToMap = false }; try { AddField addField = new AddField(table, fieldName, fieldtype); geoprocessor.Execute(addField, null); } catch (Exception) { if (geoprocessor.MessageCount > 0) { string excMessage = null; for (int Count = 0; Count <= geoprocessor.MessageCount - 1; Count++) { excMessage += geoprocessor.GetMessage(Count) + Environment.NewLine; } throw new Exception(excMessage); } } }
/// <summary> /// Copies the feature class. /// </summary> /// <param name="inputPaths">The input paths.</param> /// <param name="outPutPath">The out put path.</param> /// <param name="outputHasMValues"></param> /// <param name="outputHasZValues"></param> /// <returns></returns> public IGeoProcessorResult CopyFeatureClass(string inputPaths, string outPutPath, bool outputHasZValues, bool outputHasMValues) { try { CopyFeatures pCopyFeature = new CopyFeatures(inputPaths, outPutPath); Geoprocessor GP = new Geoprocessor(); GP.OverwriteOutput = true; GP.TemporaryMapLayers = false; if (outputHasZValues) { object obj = GP.GetEnvironmentValue("OutputZFlag"); //设置Output has Z Values GP.SetEnvironmentValue("OutputZFlag", "DEFAULT"); } if (outputHasMValues) { object obj = GP.GetEnvironmentValue("OutputMFlag"); //设置Output has M Values GP.SetEnvironmentValue("OutputMFlag", "DEFAULT"); } IGeoProcessorResult result = GP.Execute(pCopyFeature, null) as IGeoProcessorResult; //GT_CONST.LogAPI.CheckLog.AppendErrLogs(result.Status.ToString()); //GT_CONST.LogAPI.CheckLog.AppendErrLogs(result.GetMessages(0)); return(result); } catch (Exception exp) { Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString()); return(null); } }
public void createVoronoiDiagram(string layername) { try { Geoprocessor gp = new Geoprocessor(); gp.OverwriteOutput = false; IFeatureClass pInputFeatureClass = ChkMarkPoint.getFeatureLayer(layername).FeatureClass; MessageBox.Show("Choose the Save File of Voronoi Diagram"); AutoChooseFile acf = new AutoChooseFile(); string saveFilePath = acf.saveFullPathName(); //CreateThiessenPolygons pCTP = new CreateThiessenPolygons(pInputFeatureClass, @"F:\Voronoi Land Cover\LC Voronoi.shp"); CreateThiessenPolygons pCTP = new CreateThiessenPolygons(pInputFeatureClass, @saveFilePath); pCTP.fields_to_copy = "ALL"; IGeoProcessorResult pGPR = gp.Execute(pCTP, null) as IGeoProcessorResult; for (int i = 0; i < gp.MessageCount; i++) { ChkMarkPoint.changeText(gp.GetMessage(i)); } //IFeatureClass pOutFeatureClass = gp.Open(pGPR.ReturnValue) as IFeatureClass; //IFeatureLayer pFeatureLayer = new FeatureLayerClass(); //pFeatureLayer.Name = "Voronoi"; //pFeatureLayer.FeatureClass = pOutFeatureClass; //ChkMarkPoint.Mapcontr.Map.AddLayer(pFeatureLayer as ILayer); //ChkMarkPoint.Mapcontr.Refresh(); } catch (System.Exception e) { ChkMarkPoint.changeText(e.Message); } }
/// <summary> /// 空间擦除 /// </summary> /// <param name="featureClassPath"></param> /// <param name="layerId"></param> /// <param name="outFsName"></param> /// <returns></returns> public static IFeatureClass spatialErase(string gdb, IFeatureClass features, int layerId) { IFeatureClass kzxFs = Utils.featureClsArray[layerId]; string layer_name = kzxFs.AliasName; Geoprocessor gp = new Geoprocessor(); Erase erase = new Erase(); erase.in_features = features; erase.erase_features = kzxFs; erase.out_feature_class = gdb + @"\results\" + layer_name + @"EraseResult"; try { gp.AddOutputsToMap = false; gp.OverwriteOutput = true; gp.Execute(erase, null); gp.ResetEnvironments(); IFeatureClass outFs = FeatureOperations.OpenFeatureClass(gdb, "results", layer_name + @"EraseResult"); return(outFs); } catch (System.Exception ex) { string error = ""; for (int i = 0; i < gp.MessageCount; i++) { error += gp.GetMessage(i); } return(null); } }
public static void Near(object in_features, object near_features, object searchRadius = null) { Geoprocessor geoprocessor = new Geoprocessor() { OverwriteOutput = true, AddOutputsToMap = false }; try { Near near = new Near(in_features, near_features) { search_radius = searchRadius }; geoprocessor.Execute(near, null); } catch (Exception) { if (geoprocessor.MessageCount > 0) { string excMessage = null; for (int Count = 0; Count <= geoprocessor.MessageCount - 1; Count++) { excMessage += geoprocessor.GetMessage(Count) + Environment.NewLine; } throw new Exception(excMessage); } } }
private IGeoProcessorResult CreateBuffer(Geoprocessor gp) { txtMessages.Text += "Creating Buffer: " + "\r\n"; txtMessages.Update(); ESRI.ArcGIS.AnalysisTools.Buffer buffer = new ESRI.ArcGIS.AnalysisTools.Buffer(); IFeatureLayer bufferLayer = GetFeatureLayer(strBufferLayer); buffer.in_features = bufferLayer; bufferedFeatureClassName = strBufferLayer + "_" + "Buffer"; string outputFullPath = System.IO.Path.Combine(strOutputPath, bufferedFeatureClassName); buffer.out_feature_class = outputFullPath; buffer.buffer_distance_or_field = bufferDistanceField; buffer.line_side = strSideType; buffer.line_end_type = strEndType; buffer.dissolve_option = strDissolveType; buffer.dissolve_field = strDissolveFields; IGeoProcessorResult results = (IGeoProcessorResult)gp.Execute(buffer, null); buffer = null; txtMessages.Text += ReturnMessages(gp); txtMessages.Text += "Buffer Created! " + "\r\n"; ScrollToBottom(txtMessages); txtMessages.Update(); return(results); }
protected override void PerformTimestep(ICollection <EngineOutputItem> requiredOutputItems) { //--- perform calculation --- //Status = LinkableComponentStatus.Updating; if (_Inpath != null) { ESRI.ArcGIS.SpatialAnalystTools.Fill fill = new ESRI.ArcGIS.SpatialAnalystTools.Fill(); fill.in_surface_raster = _Inpath; _Outpath = _outpath; if (_Outpath == null) { //determine outpath string[] inpath = _Inpath.Split('\\'); int l = inpath[inpath.Length - 1].Length; _Outpath = _Inpath.Remove(_Inpath.Length - l); string name = _OutputItem.ElementSet.Caption; name = name.Replace(" ", ""); if (name.Length >= 9) { name = name.Remove(9); } _Outpath += name + "_fil"; } fill.out_surface_raster = _Outpath; GP.Execute(fill, null); if (GP.MaxSeverity == 2) { object sev = 2; throw new Exception("Unable to perform raster Fill operationESRI ERROR: " + GP.GetMessages(ref sev)); } numProcessed++; _currentTime.AddSeconds(_timeStepLengthInSeconds); this._outputExchangeItems[0].SetSingleTime(this.GetCurrentTime(true)); this._inputExchangeItems[0].SetSingleTime(this.GetCurrentTime(true)); //Status = LinkableComponentStatus.Updated; //clear inputs this._Inpath = null; //if (numProcessed >= requiredOutputItems.Count) //{ // //_currentTime = _simulationEnd; // Status = LinkableComponentStatus.Done; //} } }
//计算字段的函数 private string FieldCal(IFeatureLayer pFtLayer, string strField, string strExpression) { try { Geoprocessor Gp = new Geoprocessor(); Gp.OverwriteOutput = true; ESRI.ArcGIS.DataManagementTools.CalculateField calField = new ESRI.ArcGIS.DataManagementTools.CalculateField(); calField.in_table = pFtLayer as ITable; calField.field = strField; calField.expression = strExpression; calField.expression_type = "PYTHON"; Gp.Execute(calField, null); for (int i = 0; i < Gp.MessageCount; i++) { txtMessage.Text += Gp.GetMessage(i).ToString() + "\r\n"; } return("计算成功"); } catch (Exception e) { txtMessage.Text += e.Message; return("计算失败" + e.Message); } }
private void button1_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show("确定生成消防站有效覆盖区域吗?可能需要花费较长时间,生成时请勿操作计算机!", "提示", MessageBoxButtons.YesNo); if (result != DialogResult.Yes) { return; } this.Cursor = Cursors.WaitCursor; try { double a = double.Parse(textBox1.Text); double b = double.Parse(textBox2.Text); if (a <= 0 || a > 999 || b <= 0 || b > 999) { MessageBox.Show("请填入符合实际情况的数值!"); return; } } catch { MessageBox.Show("请填入符合实际情况的数值!"); return; } //缓冲区分析,GP工具调用 Geoprocessor gp = new Geoprocessor(); gp.OverwriteOutput = true; //新生成的文件可以覆盖旧生成的文件 ESRI.ArcGIS.AnalysisTools.Buffer pBuffer = new ESRI.ArcGIS.AnalysisTools.Buffer(); //设置获取缓冲区分析图层 ILayer pLayer = this.mainMapControl.get_Layer(0); IFeatureLayer featureLayer = (IFeatureLayer)pLayer; pBuffer.in_features = featureLayer; string filePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"太原GIS模型构建(分析版)"; pBuffer.out_feature_class = filePath + "\\" + pLayer.Name + ".shp"; //计算可达距离 double longer = double.Parse(textBox1.Text) * 1000 / 60 * double.Parse(textBox2.Text); int longer2 = (int)longer; //设置缓冲区距离 pBuffer.buffer_distance_or_field = longer2.ToString() + " Meters"; pBuffer.dissolve_option = "ALL"; //执行缓冲区分析 gp.Execute(pBuffer, null); //将生成结果添加到地图中 this.mainMapControl.AddShapeFile(filePath, pLayer.Name + ".shp"); this.mainMapControl.MoveLayerTo(1, 0); this.mainMapControl.MoveLayerTo(1, 7); this.Cursor = Cursors.Default; }
public void ReturnBufferFeatureClass(IFeatureLayer pInputlayer, string pOutputPath, double bufferDistance, string units) { //判断缓冲区距离 if (bufferDistance == 0.0) { MessageBox.Show("缓冲区距离无效!"); //return null; } //get an instance of the geoprocessor Geoprocessor gp = new Geoprocessor(); gp.OverwriteOutput = true; //create a new instance of a buffer tool ESRI.ArcGIS.AnalysisTools.Buffer buffer = new ESRI.ArcGIS.AnalysisTools.Buffer(pInputlayer, pOutputPath, Convert.ToString(bufferDistance) + " " + units); //buffer.dissolve_option = "ALL";//这个要设成ALL,否则相交部分不会融合 buffer.dissolve_option = "NONE";//这个要设成ALL,否则相交部分不会融合 //buffer.line_side = "FULL";//默认是"FULL",最好不要改否则出错 //buffer.line_end_type = "ROUND";//默认是"ROUND",最好不要改否则出错 try { //results = (IGeoProcessorResult)gp.Execute(buffer, null); gp.Execute(buffer, null); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void button2_Click(object sender, EventArgs e) { string text; text = textBox1.Text; Geoprocessor GP = new Geoprocessor(); GP.OverwriteOutput = true; ESRI.ArcGIS.AnalysisTools.Buffer pBuffer = new ESRI.ArcGIS.AnalysisTools.Buffer(); ILayer pLayer = aMap.get_Layer(0); IFeatureLayer featLayer = pLayer as IFeatureLayer; pBuffer.in_features = featLayer; string filepath = @"c:\temp"; pBuffer.out_feature_class = filepath + "\\" + pLayer.Name + ".shp"; pBuffer.buffer_distance_or_field = text; pBuffer.dissolve_option = "ALL"; GP.Execute(pBuffer, null); aMap.AddShapeFile(filepath, pLayer.Name); aMap.MoveLayerTo(1, 0); }
public static void Rename(object item, object newItem) { Geoprocessor geoprocessor = new Geoprocessor() { OverwriteOutput = true, AddOutputsToMap = false }; try { Rename copy = new Rename(item, newItem); geoprocessor.Execute(copy, null); } catch (Exception) { if (geoprocessor.MessageCount > 0) { string excMessage = null; for (int Count = 0; Count <= geoprocessor.MessageCount - 1; Count++) { excMessage += geoprocessor.GetMessage(Count) + Environment.NewLine; } throw new Exception(excMessage); } } }
public static void InterpolateShape(object in_surface, object in_feature_class, object out_feature_class, bool verticesOnly = false) { Geoprocessor geoprocessor = new Geoprocessor() { OverwriteOutput = true, AddOutputsToMap = false }; try { InterpolateShape inter = new InterpolateShape(in_surface, in_feature_class, out_feature_class); if (verticesOnly) { inter.vertices_only = "VERTICES_ONLY"; } geoprocessor.Execute(inter, null); } catch (Exception) { if (geoprocessor.MessageCount > 0) { string excMessage = null; for (int Count = 0; Count <= geoprocessor.MessageCount - 1; Count++) { excMessage += geoprocessor.GetMessage(Count) + Environment.NewLine; } throw new Exception(excMessage); } } }
/// <summary> /// 根据输入的中红外影像获取洪湖矢量边界 /// </summary> /// <param name="inputPath"></param> /// <param name="savePath"></param> public void CalculateBoundary(string inputPath, string savePath) { try { //使用模型来处理 _gp.AddToolbox(@"D:\RasterMaSysTemp\hhData\MyToolbox.tbx"); IVariantArray parametersArray = new VarArrayClass(); parametersArray.Add(inputPath); parametersArray.Add(savePath); _gp.Execute("GetHonghuBoundary", parametersArray, null); } catch (Exception e) { MessageBox.Show("获取边界出现错误:" + e.ToString()); } }
private IGeoProcessorResult IntersectOverlay(Geoprocessor gp) { IGpValueTableObject vtobject = new GpValueTableObject() as IGpValueTableObject; vtobject.SetColumns(1); object row = null; row = GetFeatureLayer(strInputLayer); vtobject.AddRow(ref row); row = GetFeatureLayer(strOverLayer); vtobject.AddRow(ref row); IVariantArray pVarArray = new VarArrayClass(); pVarArray.Add(vtobject); string outputFullPath = System.IO.Path.Combine (strOutputPath, strInputLayer + "_" + strOverLayer + "_" + "Intersect"); pVarArray.Add(outputFullPath); pVarArray.Add(strJoinAttributeType); pVarArray.Add(tolerance); pVarArray.Add(strOutputFeatureType); IGeoProcessorResult results = gp.Execute( "intersect_analysis", pVarArray, null) as IGeoProcessorResult; return(results); }
public static void WriteBuildErrorsToTurnFC(string outputFileGdbPath, string fdsName, string turnFCName, IGPMessages messages, ITrackCancel trackcancel) { messages.AddMessage("Writing build errors to the turn feature class..."); // Create a new field on the turn feature class for the build errors Geoprocessor gp = new Geoprocessor(); gp.AddOutputsToMap = false; AddField addFieldTool = new AddField(); addFieldTool.in_table = outputFileGdbPath + "\\" + fdsName + "\\" + turnFCName; addFieldTool.field_name = "BuildError"; addFieldTool.field_type = "SHORT"; gp.Execute(addFieldTool, trackcancel); // Open the turn feature class in the file geodatabase and find the BuildError field on it Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); var wsf = Activator.CreateInstance(factoryType) as IWorkspaceFactory; var fws = wsf.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace; IFeatureClass turnFC = fws.OpenFeatureClass(turnFCName); int buildErrorField = turnFC.FindField("BuildError"); // Open the BuildErrors.txt file generated from building the network dataset string s, leftTrimmedString, oidString; int leftTrimAmt = 24 + turnFCName.Length; IFeature feat = null; string[] buildErrorsFiles = System.IO.Directory.GetFiles(Environment.GetEnvironmentVariable("TEMP"), "BuildErrors.txt", System.IO.SearchOption.AllDirectories); string buildErrorsFile = buildErrorsFiles[0]; System.IO.StreamReader f = new System.IO.StreamReader(buildErrorsFile); // Loop through the BuildErrors.txt file and write the value 1 for each entry found. while ((s = f.ReadLine()) != null) { // ignore blank lines if (s.Length == 0) continue; // ignore build errors not dealing with the turn source if (s.Remove(leftTrimAmt) != ("SourceName: " + turnFCName + ", ObjectID: ")) continue; leftTrimmedString = s.Substring(leftTrimAmt); oidString = leftTrimmedString.Remove(leftTrimmedString.IndexOf(", ")); feat = turnFC.GetFeature(Convert.ToInt32(oidString, System.Globalization.CultureInfo.InvariantCulture)); feat.set_Value(buildErrorField, 1); feat.Store(); } f.Close(); }
public PolygonsPartitionAggregation(string dataPath,string dataName,string resultPath,string gradeField) { m_GP = new Geoprocessor(); MakeFeatureLayer makefeaturelayer = new MakeFeatureLayer(); makefeaturelayer.in_features = dataPath + dataName + ".shp"; makefeaturelayer.out_layer = "origin_lyr"; m_GP.Execute(makefeaturelayer, null); IFeatureLayer fealyr = m_GP.Open(makefeaturelayer.out_layer) as IFeatureLayer; m_FeaCls = fealyr.FeatureClass; m_PartitionField = gradeField; m_WorkingPath = resultPath; }
/// <summary> /// 运行地理分析工具 /// </summary> /// <param name="gp"></param> /// <param name="process"></param> /// <param name="trackCancel"></param> /// <returns></returns> public static IGeoProcessorResult2 RunGeoProcessor(Geoprocessor gp, IGPProcess process, ITrackCancel trackCancel) { IGeoProcessorResult2 gpResult = null; try { gpResult = gp.Execute(process, trackCancel) as IGeoProcessorResult2; //执行分析 return gpResult; } catch (Exception ex) { #if DEBUG System.Diagnostics.Debug.WriteLine(string.Format("#RunGP:{0};{1}", ex.Message, ex.StackTrace)); #endif return gpResult; } }
protected virtual void runTool(Geoprocessor geoprocessor, string name, IGPProcess process, IVariantArray param, ITrackCancel TC) { // Set the overwrite output option to true geoprocessor.OverwriteOutput = true; // Execute the tool try { geoprocessor.Execute(name, param, TC);//"Clip_analysis" ReturnMessages(geoprocessor); } catch (Exception err) { Console.WriteLine(err.Message); ReturnMessages(geoprocessor); } }
protected virtual 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, TC); ReturnMessages(geoprocessor); } catch (Exception err) { Console.WriteLine(err.Message); ReturnMessages(geoprocessor); } }
/// <summary> /// 添加属性字段 /// </summary> /// <param name="dsTarget"></param> /// <param name="newFields"></param> /// <returns></returns> public static bool AddFields(ITable dsTarget, List<IField> newFields) { if (dsTarget == null || newFields == null || newFields.Count == 0) return false; try { Geoprocessor geoProcessor = new Geoprocessor(); foreach (IField field in newFields) { ESRI.ArcGIS.DataManagementTools.AddField gpAddField = new ESRI.ArcGIS.DataManagementTools.AddField(); gpAddField.in_table = dsTarget; gpAddField.field_name = field.Name; gpAddField.field_type = GetFieldTypeGpString(field.Type); gpAddField.field_alias = field.AliasName; if (field.Domain != null) gpAddField.field_domain = field.Domain.Name; gpAddField.field_is_nullable = field.IsNullable.ToString(); gpAddField.field_is_required = field.Required.ToString(); gpAddField.field_length = field.Length; gpAddField.field_precision = field.Precision; gpAddField.field_scale = field.Scale; IGeoProcessorResult gpResult = geoProcessor.Execute(gpAddField, null) as IGeoProcessorResult; if (gpResult.Status != esriJobStatus.esriJobSucceeded) return false; } //System.Runtime.InteropServices.Marshal.FinalReleaseComObject(geoProcessor); return true; } catch(Exception exp) { ErrorMessage = exp.Message; return false; } }
/// <summary> /// This sample console app demonstrates listening to GP events as they happen /// </summary> /// <param name="args"></param> static void Main(string[] args) { ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); GPMessageEventHandler gpEventHandler = new GPMessageEventHandler(); //get an instance of the geoprocessor Geoprocessor GP = new Geoprocessor(); //register the event helper in order to be able to listen to GP events GP.RegisterGeoProcessorEvents(gpEventHandler); //wire the GP events gpEventHandler.GPMessage += new MessageEventHandler(OnGPMessage); gpEventHandler.GPPreToolExecute += new PreToolExecuteEventHandler(OnGPPreToolExecute); gpEventHandler.GPToolboxChanged += new ToolboxChangedEventHandler(OnGPToolboxChanged); gpEventHandler.GPPostToolExecute += new PostToolExecuteEventHandler(OnGPPostToolExecute); //instruct the geoprocessing engine to overwrite existing datasets GP.OverwriteOutput = true; //create instance of the 'create random points' tool. Write the output to the machine's temp directory CreateFeatureclass createFeatureClass = new CreateFeatureclass(System.IO.Path.GetTempPath(), "RandomPoints.shp"); //execute the tool GP.Execute(createFeatureClass, null); //unwire the GP events gpEventHandler.GPMessage -= new MessageEventHandler(OnGPMessage); gpEventHandler.GPPreToolExecute -= new PreToolExecuteEventHandler(OnGPPreToolExecute); gpEventHandler.GPToolboxChanged -= new ToolboxChangedEventHandler(OnGPToolboxChanged); gpEventHandler.GPPostToolExecute -= new PostToolExecuteEventHandler(OnGPPostToolExecute); //unregister the event helper GP.UnRegisterGeoProcessorEvents(gpEventHandler); System.Diagnostics.Trace.WriteLine("Done"); }
public static string ConvertMXDToMSD(string mxdfile, string convertMXDtoMSDtoolboxPath) { if (!File.Exists(convertMXDtoMSDtoolboxPath)) { MessageBox.Show(string.Format("GP Toolbox {0} to convert mxd to msd is not found", convertMXDtoMSDtoolboxPath), "Convert MXD to MSD", MessageBoxButton.OK, MessageBoxImage.Error); return null; } Geoprocessor gp = new Geoprocessor() { OverwriteOutput = true }; gp.AddToolbox(convertMXDtoMSDtoolboxPath); IVariantArray gpparams = new VarArrayClass(); gpparams.Add(mxdfile); IGeoProcessorResult gpresult = null; try { gpresult = gp.Execute(Properties.Settings.Default.toolname, gpparams, null) as IGeoProcessorResult; } catch (Exception) { object sev = 2; System.Windows.MessageBox.Show(gp.GetMessages(ref sev)); return null; } string msdfile = ((IGPString)gpresult.GetOutput(0)).Value; //MessageBox.Show(msdfile); gp = null; gpresult = null; return msdfile; }
static void LoadDirToRasterDataset(string outRasterDataset, string inputDir) { try { //Initialize GeoProcessor Geoprocessor geoProcessor = new Geoprocessor(); //Mosaic the works WorkspaceToRasterDataset wsToRasDs = new WorkspaceToRasterDataset(); //Set input folder wsToRasDs.in_workspace = inputDir; //Set target GDB raster dataset wsToRasDs.in_raster_dataset = outRasterDataset; //Include rasters in the subdirectories wsToRasDs.include_subdirectories = "INCLUDE_SUBDIRECTORIES"; //Set mosaic mode wsToRasDs.mosaic_type = "LAST"; //Set colormap mode wsToRasDs.colormap = "MATCH"; //Set background value wsToRasDs.background_value = 0; //Execute the tool to load rasters in the directory to raster dataset geoProcessor.Execute(wsToRasDs, null); ReturnMessages(geoProcessor); } catch (Exception exc) { Console.WriteLine(exc.Message); } }
public static void ConverTool(IFeatureClass feature,string fold) { Geoprocessor gp = new Geoprocessor(); gp.OverwriteOutput = true; ESRI.ArcGIS.ConversionTools.FeatureClassToShapefile Conver = new FeatureClassToShapefile(); Conver.Input_Features=feature; Conver.Output_Folder = fold; gp.Execute(Conver, null); }
public static void ExportLayerToUploadableRaster(string outputFilePath, string name, ILayer source) { try { // cast the selected/requested layer into a raster layer ESRI.ArcGIS.Carto.IRasterLayer rasterLayer = (IRasterLayer)source; // create a new raster to raster converter utility ESRI.ArcGIS.DataManagementTools.CopyRaster raster2raster = new ESRI.ArcGIS.DataManagementTools.CopyRaster(); // set the input raster layer raster2raster.in_raster = rasterLayer; // set the output path and Shapefile name /* The name and location of the raster dataset to be created. * .bil—Esri BIL * .bip—Esri BIP * .bmp—BMP * .bsq—Esri BSQ * .dat—ENVI DAT * .gif—GIF * .img—ERDAS IMAGINE * .jpg—JPEG * .jp2—JPEG 2000 * .png—PNG * .tif—TIFF * no extension for Esri Grid */ raster2raster.out_rasterdataset = outputFilePath + "\\" + name + ".tif"; // create a new GeoProcessor Geoprocessor geoprocessor = new Geoprocessor(); geoprocessor.TemporaryMapLayers = true; // execute the RasterToOtherFormat geoprocessor.Execute(raster2raster, null); } catch (Exception ex) { // an error occured System.Windows.Forms.MessageBox.Show("Error: " + ex.Message); } }
private void button5_Click(object sender, EventArgs e) { ToggleEndlessProgress.Execute(); circularProgress1.IsRunning = true; #region GP工具的使用 //得到参数 IFeatureLayer layer = GetFeatureLayer((string)comboBox3.SelectedItem); string out_feature = textBox2.Text; //实例化GP工具 Geoprocessor gp = new Geoprocessor(); gp.OverwriteOutput = true; //设置矢量投影转换参数 Project pro = new Project(); pro.in_dataset = layer; pro.out_dataset = out_feature; IEnvelope tempfeature = GetFeatureLayer((string)comboBox4.SelectedItem).AreaOfInterest; pro.out_coor_system = tempfeature.SpatialReference; //执行GP工具 IGeoProcessorResult results = (IGeoProcessorResult)gp.Execute(pro, null); #endregion #region 运行完成之后的信息提示窗口 balloonTipFocus.Enabled = true; DevComponents.DotNetBar.Balloon b = new DevComponents.DotNetBar.Balloon(); b.Style = eBallonStyle.Alert; //b.CaptionImage = balloonTipFocus.CaptionImage.Clone() as Image; b.CaptionText = "信息提示"; b.Text = "运行成功!"; b.AlertAnimation = eAlertAnimation.TopToBottom; b.AutoResize(); b.AutoClose = true; b.AutoCloseTimeOut = 4; b.Owner = this; b.Show(button5, false); #endregion }
private static bool 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); return ReturnMessages(geoprocessor); } catch (Exception err) { Debug.WriteLine(err.Message); ReturnMessages(geoprocessor); } return false; }
//线转面:测试不成功 private void feture2line(string CN_code, Geoprocessor gp, string outPath, string path, string name) { IWorkspaceFactory pwokspace = new ShapefileWorkspaceFactoryClass(); IWorkspace workspace = pwokspace.OpenFromFile(path, 0); IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)workspace; IFeatureClass featureClass = pFeatureWorkspace.OpenFeatureClass(name); //Msg("正在处理···" + CN_code + "···面转线"); ESRI.ArcGIS.DataManagementTools.FeatureToLine fe2li = new FeatureToLine(); fe2li.in_features = featureClass; fe2li.out_feature_class = outPath; gp.OverwriteOutput = true; gp.Execute(fe2li, null); MessageBox.Show(CN_code + "···面转线处理完成!"); }
private void button3_Click(object sender, EventArgs e) { ToggleEndlessProgress.Execute(); circularProgress1.IsRunning = true; #region GP工具的使用 //得到参数 IRasterLayer layer = GetRasterLayer((string)comboBox1.SelectedItem); string out_raster = textBox1.Text; //实例化GP工具 Geoprocessor gp = new Geoprocessor(); gp.OverwriteOutput = true; //设置栅格投影转换参数 ProjectRaster PR = new ProjectRaster(); PR.in_raster = layer; PR.out_raster = out_raster; IEnvelope tempRaster = GetRasterLayer((string)comboBox2.SelectedItem).VisibleExtent; PR.out_coor_system = tempRaster.SpatialReference; //执行GP工具 IGeoProcessorResult results = (IGeoProcessorResult)gp.Execute(PR, null); #endregion #region 运行完成之后的信息提示窗口 balloonTipFocus.Enabled = true; DevComponents.DotNetBar.Balloon b = new DevComponents.DotNetBar.Balloon(); b.Style = eBallonStyle.Alert; //b.CaptionImage = balloonTipFocus.CaptionImage.Clone() as Image; b.CaptionText = "信息提示"; b.Text = "运行成功!"; b.AlertAnimation = eAlertAnimation.TopToBottom; b.AutoResize(); b.AutoClose = true; b.AutoCloseTimeOut = 4; b.Owner = this; b.Show(button3, false); #endregion }
/// <summary> /// 删除IDataset /// </summary> /// <param name="dsTarget"></param> /// <returns></returns> public static bool DeleteDataset(IDataset dsTarget) { if (dsTarget == null) return false; try { ESRI.ArcGIS.DataManagementTools.Delete gpDetele = new ESRI.ArcGIS.DataManagementTools.Delete(dsTarget); Geoprocessor geoProcessor = new Geoprocessor(); IGeoProcessorResult gpResult = geoProcessor.Execute(gpDetele, null) as IGeoProcessorResult; //System.Runtime.InteropServices.Marshal.FinalReleaseComObject(geoProcessor); return gpResult.Status == esriJobStatus.esriJobSucceeded; } catch(Exception exp) { ErrorMessage = exp.Message; return false; } }
public void btnCreate_auto_Click(object sender, EventArgs e) { // Initialize the geoprocessor. Geoprocessor GP = new Geoprocessor(); try { sbLabel.Text = "Creating Map Package... "; uw.Show(); uw.lblUploadWait.Text = "Creating Map Package..."; if (workingDir == string.Empty) { workingDir = createGDXTempFolder(); } // Project Directory //string projDir = System.IO.Directory.GetCurrentDirectory(); //MessageBox.Show("ProjDir: " + projDir); // The active document is always the last template ITemplates templates = ArcMap.Application.Templates; string mxdPath = templates.get_Item(templates.Count - 1); ESRI.ArcGIS.DataManagementTools.PackageMap createPM = new ESRI.ArcGIS.DataManagementTools.PackageMap(); createPM.in_map = mxdPath; createPM.output_file = workingDir + "\\" + Path.GetFileNameWithoutExtension(mxdPath) + ".mpk"; GP.Execute(createPM, null); PMPath = workingDir + "\\" + Path.GetFileNameWithoutExtension(mxdPath) + ".mpk"; txbFilename.Text = Path.GetFileNameWithoutExtension(mxdPath) + ".mpk"; fpath_file = PMPath; uw.lblUploadWait.Visible = false; uw.lblUploadRes.Text = "Map Package successfully created."; uw.lblUploadRes.Visible = true; uw.prbUpload.Style = ProgressBarStyle.Continuous; uw.prbUpload.Value = 100; uw.btnCancel.Visible = false; uw.btnOk.Visible = true; sbLabel.Text = "Map Package successfully created. "; } catch { //MessageBox.Show("Python-Error (" + GP.GetReturnCode(0) + "), try to create the map package manually (option menu)");uw.Close(); uw.Close(); MessageBox.Show("Please enter a description for the document. (File -> Map Document Properties -> Description)"); return; } }
/// <summary> /// 要素类复制 /// </summary> /// <param name="strInput"></param> /// <param name="outPath"></param> /// <param name="outName"></param> /// <returns></returns> public static bool CopyFeatureClass(string strInput, string outPath,string outName) { try { FeatureClassToFeatureClass gpCopyFeatureClass = new FeatureClassToFeatureClass(); gpCopyFeatureClass.in_features = strInput; gpCopyFeatureClass.out_path = outPath; gpCopyFeatureClass.out_name = outName; Geoprocessor geoProcessor = new Geoprocessor(); geoProcessor.OverwriteOutput = true; IGeoProcessorResult gpResult = geoProcessor.Execute(gpCopyFeatureClass, null) as IGeoProcessorResult; //System.Runtime.InteropServices.Marshal.FinalReleaseComObject(geoProcessor); return gpResult.Status == esriJobStatus.esriJobSucceeded; } catch(Exception exp) { ErrorMessage = exp.Message; return false; } }
/// <summary> /// /// </summary> /// <param name="strInput"></param> /// <param name="outPut"></param> /// <param name="isToFile"></param> /// <param name="strFormat">当isToFile为Ture时,可设置此值,默认值为TIFF,可选值:BMP、JPEG、PNG、GIF、TIFF、IMAGINE、GRID</param> /// <returns></returns> public static bool CopyRaster(string strInput, string outPut,bool isToFile,string strFormat) { try{ IGPProcess gpTool = null; if (isToFile) { RasterToOtherFormat gpToOther = new RasterToOtherFormat(); gpToOther.Input_Rasters = strInput; gpToOther.Output_Workspace = outPut; gpToOther.Raster_Format = strFormat; gpTool = gpToOther; } else { RasterToGeodatabase gpToGDB = new RasterToGeodatabase(); gpToGDB.Input_Rasters = strInput; gpToGDB.Output_Geodatabase = outPut; gpTool = gpToGDB; } Geoprocessor geoProcessor = new Geoprocessor(); geoProcessor.OverwriteOutput = true; IGeoProcessorResult gpResult = geoProcessor.Execute(gpTool, null) as IGeoProcessorResult; //System.Runtime.InteropServices.Marshal.FinalReleaseComObject(geoProcessor); return gpResult.Status == esriJobStatus.esriJobSucceeded; } catch(Exception exp) { ErrorMessage = exp.Message; return false; } }
public void Execute(IArray paramvalues, ITrackCancel trackcancel, IGPEnvironmentManager envMgr, IGPMessages messages) { // Remember the original GP environment settings and temporarily override these settings var gpSettings = envMgr as IGeoProcessorSettings; bool origAddOutputsToMapSetting = gpSettings.AddOutputsToMap; bool origLogHistorySetting = gpSettings.LogHistory; gpSettings.AddOutputsToMap = false; gpSettings.LogHistory = false; // Create the Geoprocessor Geoprocessor gp = new Geoprocessor(); try { // Validate our values IGPMessages validateMessages = ((IGPFunction2)this).Validate(paramvalues, false, envMgr); if ((validateMessages as IGPMessage).IsError()) { messages.AddError(1, "Validate failed"); return; } // Unpack values IGPParameter gpParam = paramvalues.get_Element(InputMtdDSTTable) as IGPParameter; IGPValue inputMtdDSTTableValue = m_gpUtils.UnpackGPValue(gpParam); gpParam = paramvalues.get_Element(InputMtdCntryRefTable) as IGPParameter; IGPValue inputMtdCntryRefTableValue = m_gpUtils.UnpackGPValue(gpParam); gpParam = paramvalues.get_Element(InputMtdAreaTable) as IGPParameter; IGPValue inputMtdAreaTableValue = m_gpUtils.UnpackGPValue(gpParam); gpParam = paramvalues.get_Element(InputAdminBndyFeatureClasses) as IGPParameter; var inputAdminBndyFeatureClassesMultiValue = m_gpUtils.UnpackGPValue(gpParam) as IGPMultiValue; gpParam = paramvalues.get_Element(OutputFileGDB) as IGPParameter; IGPValue outputFileGDBValue = m_gpUtils.UnpackGPValue(gpParam); gpParam = paramvalues.get_Element(InputStreetsFeatureClass) as IGPParameter; IGPValue inputStreetsFeatureClassValue = m_gpUtils.UnpackGPValue(gpParam); gpParam = paramvalues.get_Element(InputTimeZoneIDBaseFieldName) as IGPParameter; IGPValue inputTimeZoneIDBaseFieldNameValue = m_gpUtils.UnpackGPValue(gpParam); bool processStreetsFC = (!(inputStreetsFeatureClassValue.IsEmpty())); string timeZoneIDBaseFieldName = ""; if (!(inputTimeZoneIDBaseFieldNameValue.IsEmpty())) timeZoneIDBaseFieldName = inputTimeZoneIDBaseFieldNameValue.GetAsText(); // Get the path to the output file GDB string outputFileGdbPath = outputFileGDBValue.GetAsText(); // Create the new file geodatabase AddMessage("Creating the file geodatabase...", messages, trackcancel); int lastBackslash = outputFileGdbPath.LastIndexOf("\\"); CreateFileGDB createFGDBTool = new CreateFileGDB(); createFGDBTool.out_folder_path = outputFileGdbPath.Remove(lastBackslash); createFGDBTool.out_name = outputFileGdbPath.Substring(lastBackslash + 1); gp.Execute(createFGDBTool, trackcancel); // Copy the MtdDST table to the file geodatabase and add the ADMIN_LVL and AREACODE fields to it AddMessage("Copying the MtdDST table to the file geodatabase...", messages, trackcancel); TableToTable importTableTool = new TableToTable(); string inputMtdDSTTablePath = inputMtdDSTTableValue.GetAsText(); importTableTool.in_rows = inputMtdDSTTablePath; importTableTool.out_path = outputFileGdbPath; importTableTool.out_name = "MtdDST"; importTableTool.field_mapping = "AREA_ID \"AREA_ID\" true true false 4 Long 0 0 ,First,#," + inputMtdDSTTablePath + ",AREA_ID,-1,-1;" + "TIME_ZONE \"TIME_ZONE\" true true false 4 Text 0 0 ,First,#," + inputMtdDSTTablePath + ",TIME_ZONE,-1,-1;" + "DST_EXIST \"DST_EXIST\" true true false 1 Text 0 0 ,First,#," + inputMtdDSTTablePath + ",DST_EXIST,-1,-1"; gp.Execute(importTableTool, trackcancel); string mtdDSTTablePath = outputFileGdbPath + "\\MtdDST"; AddField addFieldTool = new AddField(); addFieldTool.in_table = mtdDSTTablePath; addFieldTool.field_name = "ADMIN_LVL"; addFieldTool.field_type = "SHORT"; gp.Execute(addFieldTool, trackcancel); addFieldTool = new AddField(); addFieldTool.in_table = mtdDSTTablePath; addFieldTool.field_name = "AREACODE"; addFieldTool.field_type = "TEXT"; addFieldTool.field_length = 76; gp.Execute(addFieldTool, trackcancel); // Copy the MtdArea table to the file geodatabase and index the AREA_ID field AddMessage("Copying the MtdArea table to the file geodatabase...", messages, trackcancel); importTableTool = new TableToTable(); importTableTool.in_rows = inputMtdAreaTableValue.GetAsText(); importTableTool.out_path = outputFileGdbPath; importTableTool.out_name = "MtdArea"; gp.Execute(importTableTool, trackcancel); string mtdAreaTablePath = outputFileGdbPath + "\\MtdArea"; AddIndex addIndexTool = new AddIndex(); addIndexTool.in_table = mtdAreaTablePath; addIndexTool.fields = "AREA_ID"; addIndexTool.index_name = "AREA_ID"; gp.Execute(addIndexTool, trackcancel); // Calculate the ADMIN_LVL and AREACODE fields on the MtdDST table MakeTableView makeTableViewTool = new MakeTableView(); makeTableViewTool.in_table = mtdDSTTablePath; makeTableViewTool.out_view = "MtdDST_Layer"; gp.Execute(makeTableViewTool, trackcancel); AddJoin addJoinTool = new AddJoin(); addJoinTool.in_layer_or_view = "MtdDST_Layer"; addJoinTool.in_field = "AREA_ID"; addJoinTool.join_table = mtdAreaTablePath; addJoinTool.join_field = "AREA_ID"; addJoinTool.join_type = "KEEP_COMMON"; gp.Execute(addJoinTool, trackcancel); AddMessage("Calculating the ADMIN_LVL field...", messages, trackcancel); CalculateField calcFieldTool = new CalculateField(); calcFieldTool.in_table = "MtdDST_Layer"; calcFieldTool.field = "MtdDST.ADMIN_LVL"; calcFieldTool.expression = "[MtdArea.ADMIN_LVL]"; calcFieldTool.expression_type = "VB"; gp.Execute(calcFieldTool, trackcancel); AddMessage("Calculating the AREACODE field...", messages, trackcancel); calcFieldTool = new CalculateField(); calcFieldTool.in_table = "MtdDST_Layer"; calcFieldTool.field = "MtdDST.AREACODE"; calcFieldTool.code_block = "lvl = [MtdArea.ADMIN_LVL]\n" + "s = CStr([MtdArea.AREACODE_1])\n" + "If lvl >= 2 Then s = s & \".\" & CStr([MtdArea.AREACODE_2])\n" + "If lvl >= 3 Then s = s & \".\" & CStr([MtdArea.AREACODE_3])\n" + "If lvl >= 4 Then s = s & \".\" & CStr([MtdArea.AREACODE_4])\n" + "If lvl >= 5 Then s = s & \".\" & CStr([MtdArea.AREACODE_5])\n" + "If lvl >= 6 Then s = s & \".\" & CStr([MtdArea.AREACODE_6])\n" + "If lvl >= 7 Then s = s & \".\" & CStr([MtdArea.AREACODE_7])"; calcFieldTool.expression = "s"; calcFieldTool.expression_type = "VB"; gp.Execute(calcFieldTool, trackcancel); RemoveJoin removeJoinTool = new RemoveJoin(); removeJoinTool.in_layer_or_view = "MtdDST_Layer"; removeJoinTool.join_name = "MtdArea"; gp.Execute(removeJoinTool, trackcancel); Delete deleteTool = new Delete(); deleteTool.in_data = "MtdDST_Layer"; gp.Execute(deleteTool, trackcancel); // Create the MtdDST# tables by admin levels and index the AREACODE field TableSelect tableSelectTool = null; for (int i = 1; i <= 7; i++) { string iAsString = Convert.ToString(i, System.Globalization.CultureInfo.InvariantCulture); AddMessage("Extracting level " + iAsString + " MtdDST rows...", messages, trackcancel); tableSelectTool = new TableSelect(); tableSelectTool.in_table = mtdDSTTablePath; tableSelectTool.out_table = mtdDSTTablePath + iAsString; tableSelectTool.where_clause = "ADMIN_LVL = " + iAsString; gp.Execute(tableSelectTool, trackcancel); addIndexTool = new AddIndex(); addIndexTool.in_table = mtdDSTTablePath + iAsString; addIndexTool.fields = "AREACODE"; addIndexTool.index_name = "AREACODE"; gp.Execute(addIndexTool, trackcancel); } deleteTool = new Delete(); deleteTool.in_data = mtdDSTTablePath; gp.Execute(deleteTool, trackcancel); // Copy the MtdCntryRef table to the file geodatabase (use Statistics tool to remove duplicate rows) AddMessage("Copying the MtdCntryRef table to the file geodatabase...", messages, trackcancel); string inputMtdCntryRefTablePath = inputMtdCntryRefTableValue.GetAsText(); string mtdCntryRefTablePath = outputFileGdbPath + "\\MtdCntryRef"; Statistics statsTool = new Statistics(); statsTool.in_table = inputMtdCntryRefTablePath; statsTool.out_table = mtdCntryRefTablePath; statsTool.statistics_fields = "ISO_CODE COUNT"; statsTool.case_field = "GOVT_CODE;ISO_CODE;DRIVING_SD;ADMINLEVEL"; gp.Execute(statsTool, trackcancel); DeleteField deleteFieldTool = new DeleteField(); deleteFieldTool.in_table = mtdCntryRefTablePath; deleteFieldTool.drop_field = "FREQUENCY;COUNT_ISO_CODE"; gp.Execute(deleteFieldTool, trackcancel); // Index the GOVT_CODE field addIndexTool = new AddIndex(); addIndexTool.in_table = mtdCntryRefTablePath; addIndexTool.fields = "GOVT_CODE"; addIndexTool.index_name = "GOVT_CODE"; gp.Execute(addIndexTool, trackcancel); // Extract the top level (country) records from the MtdArea table and index the AREACODE_1 field AddMessage("Extracting the top-level rows from the MtdArea table...", messages, trackcancel); string mtdTopAreaTablePath = outputFileGdbPath + "\\TopArea"; tableSelectTool = new TableSelect(); tableSelectTool.in_table = mtdAreaTablePath; tableSelectTool.out_table = mtdTopAreaTablePath; tableSelectTool.where_clause = "AREACODE_2 = 0 AND AREA_TYPE = 'B'"; gp.Execute(tableSelectTool, trackcancel); addIndexTool = new AddIndex(); addIndexTool.in_table = mtdTopAreaTablePath; addIndexTool.fields = "AREACODE_1"; addIndexTool.index_name = "AREACODE_1"; gp.Execute(addIndexTool, trackcancel); // Create and calculate the TOP_GOVT_CODE field on the MtdArea table addFieldTool = new AddField(); addFieldTool.in_table = mtdAreaTablePath; addFieldTool.field_name = "TOP_GOVT_CODE"; addFieldTool.field_type = "LONG"; gp.Execute(addFieldTool, trackcancel); makeTableViewTool = new MakeTableView(); makeTableViewTool.in_table = mtdAreaTablePath; makeTableViewTool.out_view = "MtdArea_Layer"; gp.Execute(makeTableViewTool, trackcancel); addJoinTool = new AddJoin(); addJoinTool.in_layer_or_view = "MtdArea_Layer"; addJoinTool.in_field = "AREACODE_1"; addJoinTool.join_table = mtdTopAreaTablePath; addJoinTool.join_field = "AREACODE_1"; addJoinTool.join_type = "KEEP_COMMON"; gp.Execute(addJoinTool, trackcancel); AddMessage("Calculating the TOP_GOVT_CODE field...", messages, trackcancel); calcFieldTool = new CalculateField(); calcFieldTool.in_table = "MtdArea_Layer"; calcFieldTool.field = "MtdArea.TOP_GOVT_CODE"; calcFieldTool.expression = "[TopArea.GOVT_CODE]"; calcFieldTool.expression_type = "VB"; gp.Execute(calcFieldTool, trackcancel); removeJoinTool = new RemoveJoin(); removeJoinTool.in_layer_or_view = "MtdArea_Layer"; removeJoinTool.join_name = "TopArea"; gp.Execute(removeJoinTool, trackcancel); deleteTool = new Delete(); deleteTool.in_data = mtdTopAreaTablePath; gp.Execute(deleteTool, trackcancel); // Create and calculate the ISO_CODE and DRIVING_SD string fields addFieldTool = new AddField(); addFieldTool.in_table = mtdAreaTablePath; addFieldTool.field_name = "ISO_CODE"; addFieldTool.field_type = "TEXT"; addFieldTool.field_length = 3; gp.Execute(addFieldTool, trackcancel); addFieldTool = new AddField(); addFieldTool.in_table = mtdAreaTablePath; addFieldTool.field_name = "DRIVING_SD"; addFieldTool.field_type = "TEXT"; addFieldTool.field_length = 1; gp.Execute(addFieldTool, trackcancel); addJoinTool = new AddJoin(); addJoinTool.in_layer_or_view = "MtdArea_Layer"; addJoinTool.in_field = "TOP_GOVT_CODE"; addJoinTool.join_table = mtdCntryRefTablePath; addJoinTool.join_field = "GOVT_CODE"; addJoinTool.join_type = "KEEP_COMMON"; gp.Execute(addJoinTool, trackcancel); AddMessage("Calculating the ISO_CODE field...", messages, trackcancel); calcFieldTool = new CalculateField(); calcFieldTool.in_table = "MtdArea_Layer"; calcFieldTool.field = "MtdArea.ISO_CODE"; calcFieldTool.expression = "[MtdCntryRef.ISO_CODE]"; calcFieldTool.expression_type = "VB"; gp.Execute(calcFieldTool, trackcancel); AddMessage("Calculating the DRIVING_SD field...", messages, trackcancel); calcFieldTool = new CalculateField(); calcFieldTool.in_table = "MtdArea_Layer"; calcFieldTool.field = "MtdArea.DRIVING_SD"; calcFieldTool.expression = "[MtdCntryRef.DRIVING_SD]"; calcFieldTool.expression_type = "VB"; gp.Execute(calcFieldTool, trackcancel); removeJoinTool = new RemoveJoin(); removeJoinTool.in_layer_or_view = "MtdArea_Layer"; removeJoinTool.join_name = "MtdCntryRef"; gp.Execute(removeJoinTool, trackcancel); // Create and calculate the FullAREACODE# string fields and the UTCOffset and DST fields addFieldTool = new AddField(); addFieldTool.in_table = mtdAreaTablePath; addFieldTool.field_type = "SHORT"; addFieldTool.field_name = "UTCOffset"; gp.Execute(addFieldTool, trackcancel); addFieldTool.field_name = "DST"; gp.Execute(addFieldTool, trackcancel); string codeBlock = "lvl = [ADMIN_LVL]\ns = CStr([AREACODE_1])"; for (int i = 1; i <= 7; i++) { string iAsString = Convert.ToString(i, System.Globalization.CultureInfo.InvariantCulture); string iPlusOne = Convert.ToString(i+1, System.Globalization.CultureInfo.InvariantCulture); string fullAreaCodeFieldName = "FullAREACODE" + iAsString; addFieldTool = new AddField(); addFieldTool.in_table = mtdAreaTablePath; addFieldTool.field_name = fullAreaCodeFieldName; addFieldTool.field_type = "TEXT"; addFieldTool.field_length = 76; gp.Execute(addFieldTool, trackcancel); AddMessage("Calculating the FullAREACODE" + iAsString + " field...", messages, trackcancel); calcFieldTool = new CalculateField(); calcFieldTool.in_table = mtdAreaTablePath; calcFieldTool.field = fullAreaCodeFieldName; calcFieldTool.code_block = codeBlock; calcFieldTool.expression = "s"; calcFieldTool.expression_type = "VB"; gp.Execute(calcFieldTool, trackcancel); codeBlock = codeBlock + "\nIf lvl >= " + iPlusOne + " Then s = s & \".\" & CStr([AREACODE_" + iPlusOne + "])"; string dstJoinTableName = "MtdDST" + iAsString; string dstJoinTablePath = outputFileGdbPath + "\\" + dstJoinTableName; addJoinTool = new AddJoin(); addJoinTool.in_layer_or_view = "MtdArea_Layer"; addJoinTool.in_field = fullAreaCodeFieldName; addJoinTool.join_table = dstJoinTablePath; addJoinTool.join_field = "AREACODE"; addJoinTool.join_type = "KEEP_COMMON"; gp.Execute(addJoinTool, trackcancel); AddMessage("Calculating the UTCOffset field (" + iAsString + " of 7)...", messages, trackcancel); calcFieldTool = new CalculateField(); calcFieldTool.in_table = "MtdArea_Layer"; calcFieldTool.field = "MtdArea.UTCOffset"; calcFieldTool.code_block = "s = [MtdArea.UTCOffset]\n" + "joinValue = [" + dstJoinTableName + ".TIME_ZONE]\n" + "If Not IsNull(joinValue) Then\n" + " If Trim(joinValue) <> \"\" Then s = CInt(joinValue) * 6\n" + "End If"; calcFieldTool.expression = "s"; calcFieldTool.expression_type = "VB"; gp.Execute(calcFieldTool, trackcancel); AddMessage("Calculating the DST field (" + iAsString + " of 7)...", messages, trackcancel); calcFieldTool = new CalculateField(); calcFieldTool.in_table = "MtdArea_Layer"; calcFieldTool.field = "MtdArea.DST"; calcFieldTool.code_block = "s = [MtdArea.DST]\n" + "joinValue = [" + dstJoinTableName + ".DST_EXIST]\n" + "If Not IsNull(joinValue) Then\n" + " Select Case Trim(joinValue)\n" + " Case \"Y\": s = 1\n Case \"N\": s = 0\n" + " End Select\n" + "End If"; calcFieldTool.expression = "s"; calcFieldTool.expression_type = "VB"; gp.Execute(calcFieldTool, trackcancel); removeJoinTool = new RemoveJoin(); removeJoinTool.in_layer_or_view = "MtdArea_Layer"; removeJoinTool.join_name = dstJoinTableName; gp.Execute(removeJoinTool, trackcancel); deleteTool = new Delete(); deleteTool.in_data = dstJoinTablePath; gp.Execute(deleteTool, trackcancel); } deleteTool = new Delete(); deleteTool.in_data = "MtdArea_Layer"; gp.Execute(deleteTool, trackcancel); // Create and calculate the sortable MSTIMEZONE field on the MtdArea table addFieldTool = new AddField(); addFieldTool.in_table = mtdAreaTablePath; addFieldTool.field_name = "SortableMSTIMEZONE"; addFieldTool.field_type = "TEXT"; addFieldTool.field_length = 60; gp.Execute(addFieldTool, trackcancel); AddMessage("Calculating the time zones...", messages, trackcancel); calcFieldTool = new CalculateField(); calcFieldTool.in_table = mtdAreaTablePath; calcFieldTool.field = "SortableMSTIMEZONE"; calcFieldTool.code_block = TimeZoneUtilities.MakeSortableMSTIMEZONECode("ISO_CODE"); calcFieldTool.expression = "z"; calcFieldTool.expression_type = "VB"; gp.Execute(calcFieldTool, trackcancel); // Extract the MtdArea rows to be used for generating the time zone polygons and index the AREA_ID field string mtdAreaForTZPolysTablePath = outputFileGdbPath + "\\MtdAreaForTZPolys"; tableSelectTool = new TableSelect(); tableSelectTool.in_table = mtdAreaTablePath; tableSelectTool.out_table = mtdAreaForTZPolysTablePath; tableSelectTool.where_clause = CreateWhereClauseForAdminLvlByCountry(outputFileGdbPath, "MtdCntryRef"); gp.Execute(tableSelectTool, trackcancel); addIndexTool = new AddIndex(); addIndexTool.in_table = mtdAreaForTZPolysTablePath; addIndexTool.fields = "AREA_ID"; addIndexTool.index_name = "AREA_ID"; gp.Execute(addIndexTool, trackcancel); // We no longer need the MtdCntryRef table anymore deleteTool = new Delete(); deleteTool.in_data = mtdCntryRefTablePath; gp.Execute(deleteTool, trackcancel); // Merge the AdminBndy feature classes together into one feature class int numAdminBndyFCs = inputAdminBndyFeatureClassesMultiValue.Count; string mergeToolInputs = ""; for (int i = 0; i < numAdminBndyFCs; i++) { mergeToolInputs = mergeToolInputs + inputAdminBndyFeatureClassesMultiValue.get_Value(i).GetAsText() + ";"; } mergeToolInputs = mergeToolInputs.Remove(mergeToolInputs.Length - 1); string adminBndyFCPath = outputFileGdbPath + "\\AdminBndy"; AddMessage("Merging the Administrative Boundary feature classes...", messages, trackcancel); Merge mergeTool = new Merge(); mergeTool.inputs = mergeToolInputs; mergeTool.output = adminBndyFCPath; gp.Execute(mergeTool, trackcancel); // Join the AdminBndy polygons to the MtdArea rows to be used for generating the time zone polygons MakeFeatureLayer makeFeatureLayerTool = new MakeFeatureLayer(); makeFeatureLayerTool.in_features = adminBndyFCPath; makeFeatureLayerTool.out_layer = "AdminBndy_Layer"; gp.Execute(makeFeatureLayerTool, trackcancel); addJoinTool = new AddJoin(); addJoinTool.in_layer_or_view = "AdminBndy_Layer"; addJoinTool.in_field = "AREA_ID"; addJoinTool.join_table = mtdAreaForTZPolysTablePath; addJoinTool.join_field = "AREA_ID"; addJoinTool.join_type = "KEEP_COMMON"; gp.Execute(addJoinTool, trackcancel); FeatureClassToFeatureClass importFCTool = new FeatureClassToFeatureClass(); importFCTool.in_features = "AdminBndy_Layer"; importFCTool.out_path = outputFileGdbPath; importFCTool.out_name = "UndissolvedTZPolys"; importFCTool.field_mapping = "SortableMSTIMEZONE \"SortableMSTIMEZONE\" true true false 60 Text 0 0 ,First,#," + mtdAreaForTZPolysTablePath + ",MtdAreaForTZPolys.SortableMSTIMEZONE,-1,-1"; gp.Execute(importFCTool, trackcancel); string undissolvedTZPolysFCPath = outputFileGdbPath + "\\UndissolvedTZPolys"; removeJoinTool = new RemoveJoin(); removeJoinTool.in_layer_or_view = "AdminBndy_Layer"; removeJoinTool.join_name = "MtdAreaForTZPolys"; gp.Execute(removeJoinTool, trackcancel); deleteTool = new Delete(); deleteTool.in_data = "AdminBndy_Layer"; gp.Execute(deleteTool, trackcancel); deleteTool = new Delete(); deleteTool.in_data = adminBndyFCPath; gp.Execute(deleteTool, trackcancel); deleteTool.in_data = mtdAreaForTZPolysTablePath; gp.Execute(deleteTool, trackcancel); // Dissolve the time zone polygons together AddMessage("Dissolving the time zones...", messages, trackcancel); string timeZoneFCPath = outputFileGdbPath + "\\" + TimeZoneFCName; Dissolve dissolveTool = new Dissolve(); dissolveTool.in_features = undissolvedTZPolysFCPath; dissolveTool.out_feature_class = timeZoneFCPath; dissolveTool.dissolve_field = "SortableMSTIMEZONE"; dissolveTool.multi_part = "MULTI_PART"; gp.Execute(dissolveTool, trackcancel); deleteTool = new Delete(); deleteTool.in_data = undissolvedTZPolysFCPath; gp.Execute(deleteTool, trackcancel); // Create and calculate the MSTIMEZONE field addFieldTool = new AddField(); addFieldTool.in_table = timeZoneFCPath; addFieldTool.field_name = "MSTIMEZONE"; addFieldTool.field_type = "TEXT"; addFieldTool.field_length = 50; gp.Execute(addFieldTool, trackcancel); AddMessage("Calculating the time zones...", messages, trackcancel); calcFieldTool = new CalculateField(); calcFieldTool.in_table = timeZoneFCPath; calcFieldTool.field = "MSTIMEZONE"; calcFieldTool.expression = "Mid([SortableMSTIMEZONE], 7)"; calcFieldTool.expression_type = "VB"; gp.Execute(calcFieldTool, trackcancel); // Delete the old sortable MSTIMEZONE field deleteFieldTool = new DeleteField(); deleteFieldTool.in_table = timeZoneFCPath; deleteFieldTool.drop_field = "SortableMSTIMEZONE"; gp.Execute(deleteFieldTool, trackcancel); if (processStreetsFC) { // Create the network dataset time zone table AddMessage("Creating the time zones table...", messages, trackcancel); importTableTool = new TableToTable(); importTableTool.in_rows = timeZoneFCPath; importTableTool.out_path = outputFileGdbPath; importTableTool.out_name = TimeZonesTableName; importTableTool.field_mapping = "MSTIMEZONE \"MSTIMEZONE\" true true false 50 Text 0 0 ,First,#," + timeZoneFCPath + ",MSTIMEZONE,-1,-1"; gp.Execute(importTableTool, trackcancel); // Separate the MtdArea table by driving side and index the AREA_ID field on each AddMessage("Extracting rows for the left-side driving areas...", messages, trackcancel); string drivingLTablePath = mtdAreaTablePath + "DrivingL"; string drivingRTablePath = mtdAreaTablePath + "DrivingR"; tableSelectTool = new TableSelect(); tableSelectTool.in_table = mtdAreaTablePath; tableSelectTool.out_table = drivingLTablePath; tableSelectTool.where_clause = "DRIVING_SD = 'L'"; gp.Execute(tableSelectTool, trackcancel); addIndexTool = new AddIndex(); addIndexTool.in_table = drivingLTablePath; addIndexTool.fields = "AREA_ID"; addIndexTool.index_name = "AREA_ID"; gp.Execute(addIndexTool, trackcancel); AddMessage("Extracting rows for the right-side driving areas...", messages, trackcancel); tableSelectTool = new TableSelect(); tableSelectTool.in_table = mtdAreaTablePath; tableSelectTool.out_table = drivingRTablePath; tableSelectTool.where_clause = "DRIVING_SD = 'R'"; gp.Execute(tableSelectTool, trackcancel); addIndexTool = new AddIndex(); addIndexTool.in_table = drivingRTablePath; addIndexTool.fields = "AREA_ID"; addIndexTool.index_name = "AREA_ID"; gp.Execute(addIndexTool, trackcancel); // Import the Streets feature class to the file geodatabase and // add the FT_TimeZoneID and TF_TimeZoneID fields AddMessage("Copying the Streets feature class to the geodatabase...", messages, trackcancel); importFCTool = new FeatureClassToFeatureClass(); importFCTool.in_features = inputStreetsFeatureClassValue.GetAsText(); importFCTool.out_path = outputFileGdbPath; importFCTool.out_name = StreetsFCName; gp.Execute(importFCTool, trackcancel); string pathToStreetsFC = outputFileGdbPath + "\\" + StreetsFCName; addFieldTool = new AddField(); addFieldTool.in_table = pathToStreetsFC; addFieldTool.field_name = "FT_" + timeZoneIDBaseFieldName; addFieldTool.field_type = "SHORT"; gp.Execute(addFieldTool, trackcancel); addFieldTool.field_name = "TF_" + timeZoneIDBaseFieldName; addFieldTool.field_type = "SHORT"; gp.Execute(addFieldTool, trackcancel); // Calculate the TimeZoneID fields makeFeatureLayerTool = new MakeFeatureLayer(); makeFeatureLayerTool.in_features = pathToStreetsFC; makeFeatureLayerTool.out_layer = "Streets_Layer"; gp.Execute(makeFeatureLayerTool, trackcancel); addJoinTool = new AddJoin(); addJoinTool.in_layer_or_view = "Streets_Layer"; addJoinTool.in_field = "R_AREA_ID"; addJoinTool.join_table = drivingLTablePath; addJoinTool.join_field = "AREA_ID"; addJoinTool.join_type = "KEEP_COMMON"; gp.Execute(addJoinTool, trackcancel); AddMessage("Calculating the FT_" + timeZoneIDBaseFieldName + " field for left driving side roads...", messages, trackcancel); calcFieldTool = new CalculateField(); calcFieldTool.in_table = "Streets_Layer"; calcFieldTool.field = StreetsFCName + ".FT_" + timeZoneIDBaseFieldName; calcFieldTool.code_block = TimeZoneUtilities.MakeTimeZoneIDCode(outputFileGdbPath, TimeZonesTableName, "MtdAreaDrivingL.SortableMSTIMEZONE"); calcFieldTool.expression = "tzID"; calcFieldTool.expression_type = "VB"; gp.Execute(calcFieldTool, trackcancel); removeJoinTool = new RemoveJoin(); removeJoinTool.in_layer_or_view = "Streets_Layer"; removeJoinTool.join_name = "MtdAreaDrivingL"; gp.Execute(removeJoinTool, trackcancel); addJoinTool = new AddJoin(); addJoinTool.in_layer_or_view = "Streets_Layer"; addJoinTool.in_field = "L_AREA_ID"; addJoinTool.join_table = drivingRTablePath; addJoinTool.join_field = "AREA_ID"; addJoinTool.join_type = "KEEP_COMMON"; gp.Execute(addJoinTool, trackcancel); AddMessage("Calculating the FT_" + timeZoneIDBaseFieldName + " field for right driving side roads...", messages, trackcancel); calcFieldTool = new CalculateField(); calcFieldTool.in_table = "Streets_Layer"; calcFieldTool.field = StreetsFCName + ".FT_" + timeZoneIDBaseFieldName; calcFieldTool.code_block = TimeZoneUtilities.MakeTimeZoneIDCode(outputFileGdbPath, TimeZonesTableName, "MtdAreaDrivingR.SortableMSTIMEZONE"); calcFieldTool.expression = "tzID"; calcFieldTool.expression_type = "VB"; gp.Execute(calcFieldTool, trackcancel); removeJoinTool = new RemoveJoin(); removeJoinTool.in_layer_or_view = "Streets_Layer"; removeJoinTool.join_name = "MtdAreaDrivingR"; gp.Execute(removeJoinTool, trackcancel); addJoinTool = new AddJoin(); addJoinTool.in_layer_or_view = "Streets_Layer"; addJoinTool.in_field = "L_AREA_ID"; addJoinTool.join_table = drivingLTablePath; addJoinTool.join_field = "AREA_ID"; addJoinTool.join_type = "KEEP_COMMON"; gp.Execute(addJoinTool, trackcancel); AddMessage("Calculating the TF_" + timeZoneIDBaseFieldName + " field for left driving side roads...", messages, trackcancel); calcFieldTool = new CalculateField(); calcFieldTool.in_table = "Streets_Layer"; calcFieldTool.field = StreetsFCName + ".TF_" + timeZoneIDBaseFieldName; calcFieldTool.code_block = TimeZoneUtilities.MakeTimeZoneIDCode(outputFileGdbPath, TimeZonesTableName, "MtdAreaDrivingL.SortableMSTIMEZONE"); calcFieldTool.expression = "tzID"; calcFieldTool.expression_type = "VB"; gp.Execute(calcFieldTool, trackcancel); removeJoinTool = new RemoveJoin(); removeJoinTool.in_layer_or_view = "Streets_Layer"; removeJoinTool.join_name = "MtdAreaDrivingL"; gp.Execute(removeJoinTool, trackcancel); addJoinTool = new AddJoin(); addJoinTool.in_layer_or_view = "Streets_Layer"; addJoinTool.in_field = "R_AREA_ID"; addJoinTool.join_table = drivingRTablePath; addJoinTool.join_field = "AREA_ID"; addJoinTool.join_type = "KEEP_COMMON"; gp.Execute(addJoinTool, trackcancel); AddMessage("Calculating the TF_" + timeZoneIDBaseFieldName + " field for right driving side roads...", messages, trackcancel); calcFieldTool = new CalculateField(); calcFieldTool.in_table = "Streets_Layer"; calcFieldTool.field = StreetsFCName + ".TF_" + timeZoneIDBaseFieldName; calcFieldTool.code_block = TimeZoneUtilities.MakeTimeZoneIDCode(outputFileGdbPath, TimeZonesTableName, "MtdAreaDrivingR.SortableMSTIMEZONE"); calcFieldTool.expression = "tzID"; calcFieldTool.expression_type = "VB"; gp.Execute(calcFieldTool, trackcancel); removeJoinTool = new RemoveJoin(); removeJoinTool.in_layer_or_view = "Streets_Layer"; removeJoinTool.join_name = "MtdAreaDrivingR"; gp.Execute(removeJoinTool, trackcancel); deleteTool = new Delete(); deleteTool.in_data = "Streets_Layer"; gp.Execute(deleteTool, trackcancel); deleteTool = new Delete(); deleteTool.in_data = drivingLTablePath; gp.Execute(deleteTool, trackcancel); deleteTool.in_data = drivingRTablePath; gp.Execute(deleteTool, trackcancel); } else { // Create a dummy TimeZones table and a dummy Streets feature class CreateTable createTableTool = new CreateTable(); createTableTool.out_path = outputFileGdbPath; createTableTool.out_name = TimeZonesTableName; gp.Execute(createTableTool, trackcancel); CreateFeatureclass createFCTool = new CreateFeatureclass(); createFCTool.out_path = outputFileGdbPath; createFCTool.out_name = StreetsFCName; createFCTool.geometry_type = "POLYLINE"; gp.Execute(createFCTool, trackcancel); } deleteTool = new Delete(); deleteTool.in_data = mtdAreaTablePath; gp.Execute(deleteTool, trackcancel); // Compact the output file geodatabase AddMessage("Compacting the output file geodatabase...", messages, trackcancel); Compact compactTool = new Compact(); compactTool.in_workspace = outputFileGdbPath; gp.Execute(compactTool, trackcancel); } catch (Exception e) { if (gp.MaxSeverity == 2) { object missing = System.Type.Missing; messages.AddError(1, gp.GetMessages(ref missing)); } messages.AddError(1, e.Message); messages.AddError(1, e.StackTrace); } finally { // Restore the original GP environment settings gpSettings.AddOutputsToMap = origAddOutputsToMapSetting; gpSettings.LogHistory = origLogHistorySetting; } GC.Collect(); return; }
/// <summary> /// 批量KML2SHP进行转换 /// </summary> /// <param name="sKMLPath"></param> /// <param name="sSHPPath"></param> public static void DoKML2SHP(string sKMLPath, string sOutPutFolder) { RichTextBox rtb = Application.OpenForms["FrmKML2SHP"].Controls["richTxt_message"] as RichTextBox; rtb.Text = "正在处理中,请稍候……\n"; //frm.richTxt_message.AppendText("开始处理……"); //获取所有KML文件 List<string> list = FileManage.getAllFileNameFromFolder(sKMLPath, ".kml"); //初始化KML转图层类 KMLToLayer pKMLToLayer = new KMLToLayer(); //定义输出文件夹 string sGDBPath=sOutPutFolder+@"\KMLGDB"; pKMLToLayer.output_folder = sGDBPath; //初始化地理处理结果类 IGeoProcessorResult result = new GeoProcessorResultClass(); //初始化地理处理类 Geoprocessor gp = new Geoprocessor(); //设置可覆盖 gp.OverwriteOutput = true; rtb.AppendText("\n建立GDB文件夹并将KML转为GDB文件数据库及图层文件……\n"); try { foreach (var item in list) { pKMLToLayer.in_kml_file = item; // Execute the tool. result = (IGeoProcessorResult)gp.Execute(pKMLToLayer, null); ; rtb.AppendText(Path.GetFileName(item) + "的图层文件建立完毕……\n"); // Wait until the execution completes. while (result.Status == esriJobStatus.esriJobExecuting) Thread.Sleep(1000); // Wait for 1 second. } rtb.AppendText("所有图层文件建立完毕……\n\n开始转SHP文件……\n"); //GDB文件转SHP GDP2SHP(sGDBPath, sOutPutFolder, "Polylines"); // Print geoprocessring messages. //MessageBox.Show("OK!"); } catch (Exception ex) { // Print a generic exception message. MessageBox.Show(ex.StackTrace); } }
/// <summary> /// 运行GP工具箱 /// </summary> /// <param name="geoprocessor"></param> /// <param name="process"></param> /// <param name="TC"></param> private static void RunTool(Geoprocessor geoprocessor, IGPProcess process, ITrackCancel TC) { // Set the overwrite output option to true geoprocessor.OverwriteOutput = true; try { geoprocessor.Execute(process, null); ReturnMessages(geoprocessor); } catch (Exception err) { MessageBox.Show(err.Message); ReturnMessages(geoprocessor); } }
public static bool Import3DFile(string str3DFile, string outPut, string strSpatialRef) { try { ESRI.ArcGIS.Analyst3DTools.Import3DFiles gpImport3DFiles = new ESRI.ArcGIS.Analyst3DTools.Import3DFiles(); gpImport3DFiles.in_files = str3DFile; gpImport3DFiles.out_featureClass = outPut; gpImport3DFiles.spatial_reference = strSpatialRef; Geoprocessor geoProcessor = new Geoprocessor(); geoProcessor.OverwriteOutput = true; IGeoProcessorResult gpResult = geoProcessor.Execute(gpImport3DFiles, null) as IGeoProcessorResult; //System.Runtime.InteropServices.Marshal.FinalReleaseComObject(geoProcessor); return gpResult.Status == esriJobStatus.esriJobSucceeded; } catch (Exception exp) { ErrorMessage = exp.Message; return false; } }
private void ImportRaster() { Geoprocessor gp = new Geoprocessor();//定义处理对象 gp.OverwriteOutput = true;//覆盖输出 RasterToGeodatabase pRasterToGeodatabase = new RasterToGeodatabase(); try { UIWaiting("正在导入" + this.textBox1.Text + "层"); Application.DoEvents(); FileInfo fileInfo = new FileInfo(this.textBox1.Text.ToString()); string fpath = fileInfo.DirectoryName; string fname = fileInfo.Name.Substring(0, fileInfo.Name.IndexOf('.')); pRasterToGeodatabase.Input_Rasters = this.textBox1.Text; pRasterToGeodatabase.Output_Geodatabase = m_FGDB; gp.Execute(pRasterToGeodatabase, null); IRasterWorkspaceEx rasterWS = m_workSpace as IRasterWorkspaceEx; IRasterDataset rasterDS = rasterWS.OpenRasterDataset(fname); IDataset ds = rasterDS as IDataset; ds.Rename(this.m_place+"_"+this.m_satelite+"_"+this.m_time); m_gdata.InsertMataData(this.m_place + "_" + this.m_satelite + "_" + this.m_time, m_satelite, this.m_time, "2",this.m_place); Application.DoEvents(); MessageBox.Show("入库成功!","提示"); frm.Close(); this.Close(); UIWaiting(""); } catch (Exception error) { MessageBox.Show(error.Message); return; } }
/// <summary> /// 创建拓扑 /// </summary> /// <param name="workspaceName">被检查文件的路径名称</param> public void CreateTopology(string workspaceName) { Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IWorkspace workspace = workspaceFactory.OpenFromFile(Application.StartupPath + @"\Convert\GeoDataBase.gdb", 0); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace; IFeatureDataset featureDataset = featureWorkspace.OpenFeatureDataset("ContourData"); ITopologyContainer2 topologyContainer = (ITopologyContainer2)featureDataset; IFeatureClass CurrContour = null; try { CurrContour = featureWorkspace.OpenFeatureClass("CurrContour"); ITopology topology = topologyContainer.get_TopologyByName("eeee"); IDataset fDataset = (IDataset)topology; fDataset.Delete(); } catch (Exception) { // throw; } if (CurrContour != null) { IDataset fDataset = (IDataset)CurrContour; fDataset.Delete(); } Geoprocessor gp = new Geoprocessor(); FeatureClassToFeatureClass pFFeatureClassToFeatureClass = new FeatureClassToFeatureClass(); pFFeatureClassToFeatureClass.in_features = Application.StartupPath + "\\Convert\\ContourResult\\"+workspaceName+"\\Contour.shp"; pFFeatureClassToFeatureClass.out_path = Application.StartupPath + "\\Convert\\GeoDataBase.gdb\\ContourData"; pFFeatureClassToFeatureClass.out_name = "CurrContour"; IGeoProcessorResult geoProcessorResult = (IGeoProcessorResult)gp.Execute(pFFeatureClassToFeatureClass, null); CurrContour = featureWorkspace.OpenFeatureClass("CurrContour"); ISchemaLock schemaLock = (ISchemaLock)featureDataset; try { schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock); // Create the topology. ITopology topology = topologyContainer.CreateTopology("eeee", topologyContainer.DefaultClusterTolerance, - 1, ""); // Add feature classes and rules to the topology. topology.AddClass((IClass)CurrContour, 5, 1, 1, false); AddRuleToTopology(topology, esriTopologyRuleType.esriTRTLineNoIntersection, "must not intersect", CurrContour); int ErrorCount = 0; // Get an envelope with the topology's extents and validate the topology. IGeoDataset geoDataset = (IGeoDataset)topology; ESRI.ArcGIS.Geometry.IEnvelope envelope = geoDataset.Extent; ValidateTopology(topology, envelope); IGeoDataset geoDS = topology as IGeoDataset; IErrorFeatureContainer errorContainer = topology as IErrorFeatureContainer; IEnumTopologyErrorFeature eErrorFeat; eErrorFeat = errorContainer.get_ErrorFeaturesByRuleType(geoDS.SpatialReference, esriTopologyRuleType.esriTRTAreaNoGaps, null, true, false); ITopologyErrorFeature topoError; topoError = eErrorFeat.Next(); while (topoError != null) { ErrorCount++; topoError = eErrorFeat.Next(); } if (ErrorCount==0) { MessageBox.Show("无拓扑错误!","Sunz",MessageBoxButtons.OK,MessageBoxIcon.Information); } else { MessageBox.Show("拓扑错误" + "" + ErrorCount + "" + "个!"); } } catch (COMException comExc) { throw new Exception(String.Format( "Error creating topology: {0} Message: {1}", comExc.ErrorCode, comExc.Message), comExc); } finally { schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock); } }
private void BuildSpatialIndex(IGPValue gpFeatureClass, Geoprocessor.Geoprocessor geoProcessor, IGPUtilities gpUtil, ITrackCancel trackCancel, IGPMessages message) { if ((gpFeatureClass == null) || (geoProcessor == null) || (gpUtil == null)) return; // Check if the feature class supports spatial index grids IFeatureClass fc = gpUtil.OpenDataset(gpFeatureClass) as IFeatureClass; if (fc == null) return; int idxShapeField = fc.FindField(fc.ShapeFieldName); if (idxShapeField >= 0) { IField shapeField = fc.Fields.get_Field(idxShapeField); if (shapeField.GeometryDef.GridCount > 0) { if (shapeField.GeometryDef.get_GridSize(0) == -2.0) return; } } // Create the new spatial index grid bool storedOriginal = geoProcessor.AddOutputsToMap; try { geoProcessor.AddOutputsToMap = false; DataManagementTools.CalculateDefaultGridIndex calculateDefaultGridIndex = new DataManagementTools.CalculateDefaultGridIndex(gpFeatureClass); IGeoProcessorResult2 gpResults2 = geoProcessor.Execute(calculateDefaultGridIndex, trackCancel) as IGeoProcessorResult2; message.AddMessages(gpResults2.GetResultMessages()); if (gpResults2 != null) { DataManagementTools.RemoveSpatialIndex removeSpatialIndex = new DataManagementTools.RemoveSpatialIndex(gpFeatureClass.GetAsText()); removeSpatialIndex.out_feature_class = gpFeatureClass.GetAsText(); gpResults2 = geoProcessor.Execute(removeSpatialIndex, trackCancel) as IGeoProcessorResult2; message.AddMessages(gpResults2.GetResultMessages()); DataManagementTools.AddSpatialIndex addSpatialIndex = new DataManagementTools.AddSpatialIndex(gpFeatureClass.GetAsText()); addSpatialIndex.out_feature_class = gpFeatureClass.GetAsText(); addSpatialIndex.spatial_grid_1 = calculateDefaultGridIndex.grid_index1; addSpatialIndex.spatial_grid_2 = calculateDefaultGridIndex.grid_index2; addSpatialIndex.spatial_grid_3 = calculateDefaultGridIndex.grid_index3; gpResults2 = geoProcessor.Execute(addSpatialIndex, trackCancel) as IGeoProcessorResult2; message.AddMessages(gpResults2.GetResultMessages()); } } catch (Exception ex) { message.AddWarning(ex.Message); } finally { geoProcessor.AddOutputsToMap = storedOriginal; } }
private void button3_Click(object sender, EventArgs e) { ToggleEndlessProgress.Execute(); circularProgress1.IsRunning = true; #region GP工具的使用 //得到参数 IRasterLayer layer = GetRasterLayer((string)comboBox1.SelectedItem); string field = (string)comboBox2.SelectedItem; string out_polygon = textBox1.Text; string simplify; if (radioButton1.Checked) { simplify = radioButton1.Text; } else { simplify = radioButton2.Text; } //实例化GP工具 Geoprocessor gp = new Geoprocessor(); gp.OverwriteOutput = true; //设置矢量转栅格参数 RasterToPolygon rastertopolygon = new RasterToPolygon(); rastertopolygon.in_raster = layer; rastertopolygon.out_polygon_features = out_polygon; rastertopolygon.raster_field = field; rastertopolygon.simplify = simplify; //执行GP工具 IGeoProcessorResult results = (IGeoProcessorResult)gp.Execute(rastertopolygon, null); #endregion circularProgress1.IsRunning = false; #region 运行完成之后的信息提示窗口 balloonTipFocus.Enabled = true; DevComponents.DotNetBar.Balloon b = new DevComponents.DotNetBar.Balloon(); b.Style = eBallonStyle.Alert; //b.CaptionImage = balloonTipFocus.CaptionImage.Clone() as Image; b.CaptionText = "信息提示"; b.Text = "运行成功!"; b.AlertAnimation = eAlertAnimation.TopToBottom; b.AutoResize(); b.AutoClose = true; b.AutoCloseTimeOut = 4; b.Owner = this; b.Show(button4, false); #endregion }