Ejemplo n.º 1
0
        /// <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);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets the ArcGIS Geoprocessor, configured with the given parameters.
        /// </summary>
        /// <param name="temporaryMapLayers">Whether new map layers are temporary by default.</param>
        /// <param name="addOutputsToMap">Whether resulting output datasets should be added to the application display.</param>
        /// <param name="overwriteOutput">Whether existing output datasets should be overwritten.</param>
        /// <param name="gridReference">A raster to be used as a template for output grids in regard to dimensions (width, height, cell size, and coordinates)</param>
        /// <returns>The ArcGIS Geoprocessor</returns>
        public static Geoprocessor GetGeoprocessor(bool temporaryMapLayers = true, bool addOutputsToMap = false, bool overwriteOutput = true, IRaster gridReference = null)
        {
            Geoprocessor gp = new Geoprocessor();

            if (!userTempLayers.HasValue)
            {
                userTempLayers = gp.TemporaryMapLayers;
            }

            if (!userAddOutputs.HasValue)
            {
                userAddOutputs = gp.AddOutputsToMap;
            }

            if (!userOverwrite.HasValue)
            {
                userOverwrite = gp.OverwriteOutput;
            }

            gp.TemporaryMapLayers = temporaryMapLayers;
            gp.AddOutputsToMap    = addOutputsToMap;
            gp.OverwriteOutput    = overwriteOutput;

            if (gridReference != null)
            {
                IRasterDataset rds  = ((IRasterAnalysisProps)gridReference).RasterDataset;
                IDataset       ds   = (IDataset)rds;
                string         path = System.IO.Path.Combine(ds.Workspace.PathName, ds.Name);
                gp.SetEnvironmentValue("snapRaster", path);

                string extent = string.Format("{0} {1} {2} {3}", ((IGeoDataset2)rds).Extent.XMin, ((IGeoDataset2)rds).Extent.YMin, ((IGeoDataset2)rds).Extent.XMax, ((IGeoDataset2)rds).Extent.YMax);
                gp.SetEnvironmentValue("extent", extent);
            }

            if (workspace == null)
            {
                workspace = gp.GetEnvironmentValue("workspace");
            }

            if (scratchWorkspace == null)
            {
                scratchWorkspace = gp.GetEnvironmentValue("scratchWorkspace");
            }

            if (gp.GetEnvironmentValue("workspace") == null)
            {
                gp.SetEnvironmentValue("workspace", GetDefaultWorkspace());
            }

            if (gp.GetEnvironmentValue("scratchWorkspace") == null)
            {
                gp.SetEnvironmentValue("scratchWorkspace", GetDefaultWorkspace());
            }

            return(gp);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 栅格传输
        /// </summary>
        /// <param name="task"></param>
        public static void CopyRaster(string sourceFileName, string destFileName, RenameMode renameMode)
        {
            RasterReadHelper inputReadHelper            = new RasterReadHelper(sourceFileName);
            RasterReadHelper outputReadHelper           = new RasterReadHelper(destFileName);
            string           outputNameWithoutExtention = string.Empty;

            if (renameMode.Equals(RenameMode.Overwrite))
            {
                outputReadHelper.Delete(outputReadHelper.NameWithoutExtension + outputReadHelper.Extension);
                outputNameWithoutExtention = outputReadHelper.NameWithoutExtension;
            }
            else
            {
                outputNameWithoutExtention = outputReadHelper.AccumulativeName;
            }

            ESRI.ArcGIS.DataManagementTools.CopyRaster CpyRst = new ESRI.ArcGIS.DataManagementTools.CopyRaster(sourceFileName, outputReadHelper.Directory + "\\" + outputNameWithoutExtention);
            Geoprocessor gp = new Geoprocessor();

            gp.SetEnvironmentValue("Compression", inputReadHelper.RstDs.CompressionType);
            gp.OverwriteOutput = true;
            IGeoProcessorResult gpResult = gp.Execute(CpyRst, null) as IGeoProcessorResult;

            if (gpResult == null || gpResult.Status == esriJobStatus.esriJobFailed)
            {
                for (int i = 0; i < gpResult.MessageCount; i++)
                {
                    MessageBox.Show(gpResult.GetMessage(i));
                }
            }
        }
Ejemplo n.º 4
0
        void IClip.ClipByLayerFileInsideSde(object in_feature, string in_layer_file_path, object clip_feature, string clip_layer_file_path, string out_feature)
        {
            using (ComReleaser releaser = new ComReleaser())
            {
                try
                {
                    Geoprocessor gp = new Geoprocessor();
                    IDataManager _dataManager = new DataManager(this._environment);
                    ESRI.ArcGIS.AnalysisTools.Clip clipTool = new ESRI.ArcGIS.AnalysisTools.Clip();

                    //releaser.ManageLifetime(gp);
                    //releaser.ManageLifetime(clipTool);
                    //IVariantArray param = new VarArrayClass();

                    string inlayer = string.Format("{0}.lyr", in_layer_file_path);
                    string cliplayer = string.Format("{0}.lyr", clip_layer_file_path);
                    //MessageBox.Show(string.Format("line 61 GExtractTool in={0}, clip={1}", inlayer, cliplayer));
                    _dataManager.SaveToLayerFile((ILayer)in_feature, inlayer);
                    _dataManager.SaveToLayerFile((ILayer)clip_feature, cliplayer);

                    //MessageBox.Show(((IFeatureLayer)in_feature).FeatureClass.AliasName);
                    gp.SetEnvironmentValue("workspace", this._environment);
                    clipTool.in_features = inlayer;
                    clipTool.clip_features = cliplayer;
                    clipTool.out_feature_class = out_feature;//string.Format("{0}{1}", this._temFullPath, out_feature);//"C:\\tayninh\\temp\\tempmdb.mdb\\" + out_feature;

                    runTool(gp, clipTool, null);
                }
                catch (Exception err) { MessageBox.Show("loi clip: " + err.ToString()); }
            }
        }
        /// <summary>
        /// Initializes a new instance of the RunGPForm class which represents the ArcGIS Engine application.
        /// The constructor is used to perform setup: the ListViewControl is configured, a new Geoprocessor
        /// object is created, the output result directory is specified and event handlers created in order
        /// to listen to geoprocessing events. A helper method called SetupMap is called to create, add and
        /// symbolize the layers used by the application.
        /// </summary>
        public RunGPForm()
        {
            InitializeComponent();

            //Set up ListView control
            listView1.Columns.Add("Event", 200, HorizontalAlignment.Left);
            listView1.Columns.Add("Message", 1000, HorizontalAlignment.Left);
            //The image list component contains the icons used in the ListView control
            listView1.SmallImageList = imageList1;

            //Create a Geoprocessor object and associated event handlers which will be fired during tool execution
            _gp = new Geoprocessor();
            //All results will be written to the users TEMP folder
            string outputDir = System.Environment.GetEnvironmentVariable("TEMP");

            _gp.SetEnvironmentValue("workspace", outputDir);
            _gp.OverwriteOutput  = true;
            _gp.ToolExecuted    += new EventHandler <ToolExecutedEventArgs>(_gp_ToolExecuted);
            _gp.ProgressChanged += new EventHandler <ESRI.ArcGIS.Geoprocessor.ProgressChangedEventArgs>(_gp_ProgressChanged);
            _gp.MessagesCreated += new EventHandler <MessagesCreatedEventArgs>(_gp_MessagesCreated);
            _gp.ToolExecuting   += new EventHandler <ToolExecutingEventArgs>(_gp_ToolExecuting);

            //Add layers to the map, select a city, zoom in on it
            SetupMap();
        }
Ejemplo n.º 6
0
        /// <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);
            }
        }
Ejemplo n.º 7
0
        //-------------------------------------------------------------------------
        internal static bool GenerateProfileData(
            string lineFeatureClass,
            string profileSource,
            string outTable,
            IEnumerable <string> messages,
            string outGraphName = null
            )
        {
            Geoprocessor gp = new Geoprocessor();

            StackProfile stackProfile = new StackProfile();


            stackProfile.in_line_features = lineFeatureClass;
            stackProfile.profile_targets  = profileSource;
            stackProfile.out_table        = outTable;
            if (!string.IsNullOrEmpty(outGraphName))
            {
                stackProfile.out_graph = outGraphName;
            }

            GeoProcessorResult gpResult = new GeoProcessorResult();

            gp.SetEnvironmentValue(environmentName, temporaryWorkspace);
            return(RunTool(gp, stackProfile, null, messages));
        }
 public GpToolsClass()
 {
     //设置环境
     _gp = new Geoprocessor();
     _gp.OverwriteOutput = true;
     _gp.SetEnvironmentValue("Workspace", this._workspace);
 }
Ejemplo n.º 9
0
        /// <summary>
        /// 调用一个模型
        /// </summary>
        public void GPtest2()
        {
            Geoprocessor gp = new Geoprocessor();

            gp.OverwriteOutput = true;
            gp.SetEnvironmentValue("scratchworkspace", @"F:\gpTest1\data");
            gp.AddToolbox(@"F:\gpTest\Toolbox.tbx");
            IVariantArray parameters = new VarArrayClass();

            parameters.Add(@"F:\gpTest\data\test .xlsx");
            parameters.Add("a");
            parameters.Add("b");
            ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference        spatialReference        = spatialReferenceFactory.CreateProjectedCoordinateSystem(2379);

            parameters.Add(spatialReference);
            parameters.Add(@"F:\gpTest\data\project1.shp");
            try
            {
                gp.Execute("excel", parameters, null);
            }
            catch (Exception ex)
            {
                string a = ex.Message;
            }
        }
Ejemplo n.º 10
0
        private static bool RunTool(IGPProcess process, ITrackCancel TC, out IEnumerable <string> messages)
        {
            if (gp == null)
            {
                gp = new Geoprocessor
                {
                    AddOutputsToMap = false
                };

                gp.SetEnvironmentValue(environmentName, temporaryWorkspace);
            }

            gp.OverwriteOutput = true; // Set the overwrite output option to true
            bool result = true;

            try
            {
                IGeoProcessorResult pResult = (IGeoProcessorResult)gp.Execute(process, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                result = false;
            }

            messages = ReturnMessages(gp).ToArray();
            return(result);
        }
Ejemplo n.º 11
0
 void IAppend.Append(IFeatureClass fcSource, IFeatureClass fcTarget)
 {
     Geoprocessor gp = new Geoprocessor();
        ESRI.ArcGIS.DataManagementTools.Append pAppend = new ESRI.ArcGIS.DataManagementTools.Append(fcSource, fcTarget);
        gp.SetEnvironmentValue("workspace",this._environment);
        pAppend.schema_type = "NO_TEST";
        runTool(gp, pAppend, null);
 }
Ejemplo n.º 12
0
 // 空间分析:欧式距离
 private void EuclideanDistance(object in_raster, object out_raster)
 {
     ESRI.ArcGIS.SpatialAnalystTools.EucDistance pTool = new ESRI.ArcGIS.SpatialAnalystTools.EucDistance()
     {
         in_source_data      = in_raster,
         out_distance_raster = out_raster
     };
     GP.SetEnvironmentValue("extent", DATADIR + "Database.gdb\\填挖研究区DEM");
     GP.Execute(pTool, null);
 }
Ejemplo n.º 13
0
        private IRaster _DrainagePointsToSeedGrid(IFeatureClass featureClass, string baseName, string valueField)
        {
            Geoprocessor gp         = new Geoprocessor();
            bool         addOutputs = gp.AddOutputsToMap;

            try
            {
                IRasterDataset demRasterDataset = ((IRasterAnalysisProps)DEM).RasterDataset;
                IDataset       demDataset       = (IDataset)demRasterDataset;
                string         path             = System.IO.Path.Combine(demDataset.Workspace.PathName, demDataset.Name);

                gp.SetEnvironmentValue("snapRaster", path);

                string extent = string.Format("{0} {1} {2} {3}", ((IGeoDataset2)demRasterDataset).Extent.XMin, ((IGeoDataset2)demRasterDataset).Extent.YMin, ((IGeoDataset2)demRasterDataset).Extent.XMax, ((IGeoDataset2)demRasterDataset).Extent.YMax);
                gp.SetEnvironmentValue("extent", extent);

                gp.AddOutputsToMap = false;

                FeatureToRaster featureToRasterTool = new FeatureToRaster();

                featureToRasterTool.cell_size = ((IRasterAnalysisProps)DEM).PixelHeight;
                featureToRasterTool.field     = valueField;

                IDataset dataset          = (IDataset)featureClass;
                string   featureClassPath = System.IO.Path.Combine(dataset.Workspace.PathName, dataset.Name + ".shp");
                featureToRasterTool.in_features = featureClassPath;

                string outputName = SetupOp.CreateTempFileName(this.ScratchDirectory, baseName, null);
                featureToRasterTool.out_raster = outputName;

                string outputShortName = System.IO.Path.GetFileNameWithoutExtension(outputName);

                RunTool(gp, featureToRasterTool, null);

                IRasterWorkspace rws = this.GetTempRasterWorkspace() as IRasterWorkspace;
                return(rws.OpenRasterDataset(outputShortName).CreateDefaultRaster());
            }
            finally
            {
                gp.AddOutputsToMap = addOutputs;
            }
        }
Ejemplo n.º 14
0
 void IBuffer.BufferInsideSde(string in_features, string out_feature, object distance)
 {
     Geoprocessor gp = new Geoprocessor();
     ESRI.ArcGIS.AnalysisTools.Buffer bufferTool = new ESRI.ArcGIS.AnalysisTools.Buffer();
     //_environment = "Database Connections/Connection to HT-LAPTOP.sde";
     //MessageBox.Show("TnBuffer-line:85--environment: " + _environment);
     gp.SetEnvironmentValue("workspace", _environment);
     bufferTool.in_features = in_features;
     bufferTool.out_feature_class = out_feature;
     bufferTool.buffer_distance_or_field = distance;
     runTool(gp, bufferTool, null);
 }
Ejemplo n.º 15
0
        public static bool ExportLayer2Dwg(IList <IFeatureLayer> pInPutLayerList, string outputfile)
        {
            Geoprocessor GP = new Geoprocessor();

            GP.OverwriteOutput = true;//覆盖同名
            GP.SetEnvironmentValue("workspace", @"C:\temp");

            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < pInPutLayerList.Count; i++)
            {
                IFeatureLayer layer = pInPutLayerList[i];

                IDataset dataset = layer.FeatureClass as IDataset;

                string layerfullname = dataset.Workspace.PathName + "\\" + dataset.Name;
                builder.Append(layerfullname + ";");
            }

            string fullfilepath = builder.ToString().Substring(0, builder.Length - 1);

            ExportCAD exportcad = new ExportCAD();

            exportcad.in_features = fullfilepath;
            exportcad.Output_Type = "DWG_R2010";
            exportcad.Output_File = outputfile;

            try
            {
                IGeoProcessorResult results = (IGeoProcessorResult)GP.Execute(exportcad, null);
                string msg = "";
                if (GP.MessageCount > 0)
                {
                    for (int i = 0; i < GP.MessageCount; i++)
                    {
                        msg += GP.GetMessage(i) + "\n";
                    }
                }
                if (msg.Contains("Successed"))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Ejemplo n.º 16
0
        public static void GPListFeatureClasses(Geoprocessor GP)
        {
            // List all feature classes in the workspace starting with d.
            GP.SetEnvironmentValue("workspace", @"C:\Uc2003\Portland_OR.gdb");
            IGpEnumList fcs = GP.ListFeatureClasses("d*", "", "");
            string      fc  = fcs.Next();

            while (fc != "")
            {
                Console.WriteLine(fc);
                fc = fcs.Next();
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 简单调用一个裁剪工具
        /// </summary>
        public void GPtest1()
        {
            Geoprocessor gp = new Geoprocessor();

            //输出文件是否能被覆盖
            gp.OverwriteOutput = true;
            gp.SetEnvironmentValue("scratchworkspace", @"F:\gpTest\data");
            ESRI.ArcGIS.AnalysisTools.Clip clip = new ESRI.ArcGIS.AnalysisTools.Clip();
            clip.in_features       = @"F:\gpTest\data\po1.shp";
            clip.clip_features     = @"F:\gpTest\data\po2.shp";
            clip.cluster_tolerance = "";
            clip.out_feature_class = @"\gpTest\data\result.shp";
            gp.Execute(clip, null);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Resets the ArcGIS Geoprocessor to the user defined environment variables.
        /// </summary>
        public static void ResetGeoprocessor()
        {
            Geoprocessor gp = new Geoprocessor();

            if (userTempLayers.HasValue)
            {
                gp.TemporaryMapLayers = userTempLayers.Value;
            }

            if (userAddOutputs.HasValue)
            {
                gp.AddOutputsToMap = userAddOutputs.Value;
            }

            if (userOverwrite.HasValue)
            {
                gp.OverwriteOutput = userOverwrite.Value;
            }

            if (workspace != null)
            {
                gp.SetEnvironmentValue("workspace", workspace);
            }

            if (scratchWorkspace != null)
            {
                gp.SetEnvironmentValue("scratchWorkspace", scratchWorkspace);
            }

            userTempLayers   = null;
            userAddOutputs   = null;
            userOverwrite    = null;
            workspace        = null;
            scratchWorkspace = null;

            esriUtility.RemoveInternalData();
        }
Ejemplo n.º 19
0
        //-------------------------------------------------------------------------

        public static bool GenerateVisibilityData(
            string rasterSource,
            string observerObjectsFeatureClass,
            VisibilityAnalysisTypesEnum analyzeType,
            string outRasterName,
            IEnumerable <string> messages,
            VisibilityCurvatureCorrectionEnum curvatureCorrection = VisibilityCurvatureCorrectionEnum.FLAT_EARTH,
            string outAglRaster = null,
            int innerRadius     = 0,
            int outerRadius     = 0
            )
        {
            Geoprocessor gp = new Geoprocessor();

            Visibility visibility = new Visibility();

            visibility.analysis_type        = analyzeType.ToString().ToUpper();
            visibility.in_raster            = rasterSource;
            visibility.in_observer_features = observerObjectsFeatureClass;
            visibility.out_raster           = outRasterName;
            if (!string.IsNullOrWhiteSpace(outAglRaster))
            {
                visibility.out_agl_raster = outAglRaster;
            }

            visibility.nonvisible_cell_value = NonvisibleCellValue;

            visibility.horizontal_start_angle = VisibilityFieldsEnum.AzimuthB.ToString();
            visibility.horizontal_end_angle   = VisibilityFieldsEnum.AzimuthE.ToString();
            visibility.vertical_lower_angle   = VisibilityFieldsEnum.AnglMinH.ToString();
            visibility.vertical_upper_angle   = VisibilityFieldsEnum.AnglMaxH.ToString();

            if (innerRadius > 0)
            {
                visibility.inner_radius = innerRadius.ToString();
            }
            if (outerRadius > 0)
            {
                visibility.outer_radius = outerRadius.ToString();
            }

            visibility.curvature_correction = curvatureCorrection.ToString();

            GeoProcessorResult gpResult = new GeoProcessorResult();

            gp.SetEnvironmentValue(environmentName, temporaryWorkspace);;

            return(RunTool(gp, visibility, null, messages));
        }
Ejemplo n.º 20
0
        public DataManipulator()
        {
            myProcessor                    = new Geoprocessor();
            myProcessor.LogHistory         = true;
            myProcessor.TemporaryMapLayers = true;
            myProcessor.SetEnvironmentValue("Extent", "MAXOF");


            tempLayer1    = "\\layer1";
            tempLayer2    = "\\layer2";
            selectLayer   = "\\select_lyr";
            pointLayer    = "\\point_lyr";
            dissolveLayer = "\\dissolve_lyr";
            sb            = new StringBuilder();
        }
Ejemplo n.º 21
0
        public static List <string> ListFeatureClasses(Geoprocessor gp, string ws)
        {
            // List all feature classes in the workspace starting with d.
            gp.SetEnvironmentValue("workspace", ws);
            IGpEnumList   fcs = gp.ListFeatureClasses("*", "", "");
            string        fc  = fcs.Next();
            List <string> li  = new List <string>();

            while (fc != "")
            {
                //Console.WriteLine(fc);
                li.Add(fc);
                fc = fcs.Next();
            }
            return(li);
        }
Ejemplo n.º 22
0
        public void Excute(object inputFeatureClass, object targetFeatureClass)
        {
            try
            {
                Geoprocessor gp = new Geoprocessor();
                ESRI.ArcGIS.DataManagementTools.Append appendTool = new ESRI.ArcGIS.DataManagementTools.Append();
                //IVariantArray param = new VarArrayClass();
                gp.SetEnvironmentValue("workspace", this._environment);
                appendTool.inputs = inputFeatureClass;
                appendTool.target = targetFeatureClass;
                //appendTool.out_feature_class = string.Format("{0}{1}", this._temFullPath, out_feature);//"C:\\tayninh\\temp\\tempmdb.mdb\\" + out_feature;

                runTool(gp, appendTool, null);
            }
            catch (Exception err) { MessageBox.Show("loi append: " + err.ToString()); }
        }
Ejemplo n.º 23
0
        void IClip.Clip(object in_feature, object clip_feature, string out_feature)
        {
            try
            {
                Geoprocessor gp = new Geoprocessor();
                ESRI.ArcGIS.AnalysisTools.Clip clipTool = new ESRI.ArcGIS.AnalysisTools.Clip();
                //IVariantArray param = new VarArrayClass();
                gp.SetEnvironmentValue("workspace", this._environment);
                //MessageBox.Show(((IFeatureLayer)in_feature).FeatureClass.AliasName);
                clipTool.in_features = in_feature;
                clipTool.clip_features = clip_feature;
                clipTool.out_feature_class = string.Format("{0}",out_feature);//"C:\\tayninh\\temp\\tempmdb.mdb\\" + out_feature;

                runTool(gp, clipTool, null);
            }
            catch (Exception err) { MessageBox.Show("loi clip: " + err.ToString()); }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Performs an unsupervised iso Clustering Maximum likelyhood classification
        /// </summary>
        /// <param name="inRasterDset"> input raster dataset (string, IRaster, IRasterDataset, IRasterDescription) used to perform the isoCluster</param>
        /// <param name="outWorkSpace">string identifing the output workspace</param>
        /// <param name="numClasses">int specifing the number of classes</param>
        /// <param name="outRstPath">the full path of the output Raster. If null will use outWorkSpace and name the raster iso</param>
        /// <param name="outSigPath">the full path fo the signature file. If null will use outWorkSpace and name signature file isoSig.gsg</param>
        /// <returns>geoprocessing messages</returns>
        public string isoClusterUnSupervised(object inRasterDset, IWorkspace outWorkSpace, int numClasses, string outRstPath, string outSigPath)
        {
            Forms.RunningProcess.frmRunningProcessDialog frmRd = new Forms.RunningProcess.frmRunningProcessDialog(false);
            frmRd.addMessage("Running Iso Cluster Unsupervised classification");
            frmRd.stepPGBar(10);
            frmRd.Show();
            string outRstStr = null;

            if (outRstPath == null)
            {
                outRstPath = outWorkSpace.PathName + "\\iso";
                outSigPath = System.IO.Path.GetDirectoryName(outWorkSpace.PathName) + "\\isoSig.gsg";
            }
            try
            {
                gp.OverwriteOutput = true;
                gp.SetEnvironmentValue("workspace", outWorkSpace.PathName);
                ESRI.ArcGIS.SpatialAnalystTools.IsoClusterUnsupervisedClassification isoCls = new IsoClusterUnsupervisedClassification();
                isoCls.Input_raster_bands       = inRasterDset;
                isoCls.Minimum_class_size       = numClasses * 10;
                isoCls.Number_of_classes        = numClasses;
                isoCls.Output_classified_raster = outRstPath;
                isoCls.Output_signature_file    = outSigPath;
                isoCls.Sample_interval          = 10;
                IGeoProcessorResult gpRslt = (IGeoProcessorResult)gp.Execute(isoCls, null);
                frmRd.addMessage(getMessages(gpRslt));
                outRstStr = gpRslt.ReturnValue.ToString();
                frmRd.stepPGBar(60);
            }
            catch (Exception e)
            {
                string x = e.ToString();
                Console.WriteLine("New Error: " + x);
                frmRd.addMessage(x);
            }
            finally
            {
                frmRd.addMessage("Finished IsoCluster");
                frmRd.stepPGBar(100);
                frmRd.enableClose();
                frmRd.TopMost = false;
            }

            return(outRstStr);
        }
Ejemplo n.º 25
0
        public static String[] GetFeatures(IWorkspace workspace, ref Geoprocessor gp, String wildCard = "", String featureType = "")
        {
            try
            {
                gp.SetEnvironmentValue("workspace", workspace.PathName);
                wildCard = (string.IsNullOrEmpty(wildCard) ? wildCard : wildCard + "*");
                var features = gp.ListFeatureClasses(wildCard, featureType, "");

                String feature;
                var    featList = new List <String>();
                while ((feature = features.Next()) != string.Empty)
                {
                    featList.Add(Path.Combine(workspace.PathName, feature));
                }

                return(featList.ToArray());
            }
            catch (Exception) { return(GetRootFeatures(workspace)); }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// 执行自定义Model GP
        /// </summary>
        /// <param name="parameters">GP 输入参数</param>
        /// <param name="gpname">GP 名字</param>
        /// <param name="modelPath">工具箱路径</param>
        /// <param name="tempFolder">临时工作区路径</param>
        /// <returns></returns>
        public bool RunModelTool(string modelPath, string tempFolder, IVariantArray parameters, string gpname)
        {
            if (parameters == null)
            {
                return(false);
            }
            Geoprocessor geoprocessor = new Geoprocessor();

            geoprocessor.OverwriteOutput = true;
            geoprocessor.SetEnvironmentValue("scratchworkspace", tempFolder);
            try
            {
                geoprocessor.AddToolbox(modelPath);
                geoprocessor.Execute(gpname, parameters, null);
                Marshal.ReleaseComObject(parameters);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 27
0
        public FormProcessing()
        {
            InitializeComponent();

            //Set up ListView control
            listView1.Columns.Add("Event", 200, HorizontalAlignment.Left);
            listView1.Columns.Add("Message", 1000, HorizontalAlignment.Left);
            listView1.SmallImageList = imageList1;

            // Set up Geoprocessor
            _gp = new Geoprocessor();
            string outputDir = @"e:\data\";
            _gp.SetEnvironmentValue("workspace", outputDir);
            _gp.OverwriteOutput = true;
            // GP Events
            _gp.ToolExecuted += new EventHandler<ToolExecutedEventArgs>(_gp_ToolExecuted);
            _gp.ToolExecuting += new EventHandler<ToolExecutingEventArgs>(_gp_ToolExecuting);
            _gp.ProgressChanged += new EventHandler<ESRI.ArcGIS.Geoprocessor.ProgressChangedEventArgs>(_gp_ProgressChanged);
            _gp.MessagesCreated += new EventHandler<MessagesCreatedEventArgs>(_gp_MessagesCreated);

            // Menu Events
            loadDataToolStripMenuItem.Click += new EventHandler(loadDataToolStripMenuItem_Click);
        }
    /// <summary>
    /// Initializes a new instance of the RunGPForm class which represents the ArcGIS Engine application.
    /// The constructor is used to perform setup: the ListViewControl is configured, a new Geoprocessor
    /// object is created, the output result directory is specified and event handlers created in order
    /// to listen to geoprocessing events. A helper method called SetupMap is called to create, add and
    /// symbolize the layers used by the application.
    /// </summary>
    public RunGPForm()
    {
      InitializeComponent();

      //Set up ListView control
      listView1.Columns.Add("Event", 200, HorizontalAlignment.Left);  
      listView1.Columns.Add("Message", 1000, HorizontalAlignment.Left);
      //The image list component contains the icons used in the ListView control
      listView1.SmallImageList = imageList1;

      //Create a Geoprocessor object and associated event handlers which will be fired during tool execution
      _gp = new Geoprocessor();
      //All results will be written to the users TEMP folder
      string outputDir = System.Environment.GetEnvironmentVariable("TEMP");
      _gp.SetEnvironmentValue("workspace", outputDir);
      _gp.OverwriteOutput = true;
      _gp.ToolExecuted += new EventHandler<ToolExecutedEventArgs>(_gp_ToolExecuted);
      _gp.ProgressChanged += new EventHandler<ESRI.ArcGIS.Geoprocessor.ProgressChangedEventArgs>(_gp_ProgressChanged);
      _gp.MessagesCreated += new EventHandler<MessagesCreatedEventArgs>(_gp_MessagesCreated);
      _gp.ToolExecuting += new EventHandler<ToolExecutingEventArgs>(_gp_ToolExecuting);

      //Add layers to the map, select a city, zoom in on it
      SetupMap();
    }
Ejemplo n.º 29
0
        /// <summary>
        /// Ejecuta el modelo de amenazas de incendios
        /// </summary>
        /// <param name="sTablaPrecipPromedio">Tabla Precipitacion Promedio</param>
        /// <param name="sConsultaTablaPrecipPromedio">SQL para la table precipitacion promedio</param>
        /// <param name="sPrefijo">Prefijo para los nombres de las capas</param>
        /// <param name="sTablaTempPromedio">Nombre de la tabla temporal de promedios</param>
        /// <param name="sConsultaTablaTempPromedio">SQL para la tabla temporal de promedios</param>
        /// <param name="bUsarSatelite">Indica si se han de utilizar las imagenes de satelita</param>
        /// <param name="bMostrarIntermedios">Indica si se mostraran los resultados intermedios en el mapa activo</param>
        private void GenerarModelo(string sTablaPrecipPromedio, string sConsultaTablaPrecipPromedio, string sPrefijo,
                                   string sTablaTempPromedio, string sConsultaTablaTempPromedio, bool bUsarSatelite,
                                   bool bMostrarIntermedios, String[] sRastersPrecipitacion)
        {
            String sPath   = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            String tempDir = "";

            sPath = sPath.Replace("file:\\", "");
            SIGPIParametros parametros = new SIGPIParametros();

            try
            {
                XmlSerializer          serializer = new XmlSerializer(typeof(SIGPIParametros));
                System.IO.StreamReader r          = new System.IO.StreamReader(sPath + "\\parameters\\parametros.xml");
                parametros = (SIGPIParametros)serializer.Deserialize(r);
                r.Close();
                serializer = null;
                r          = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SIGPI 2013");
                return;
            }

            SIGPIProcesamiento procesamiento = new SIGPIProcesamiento(parametros);
            SIGPICls           sigpi         = new SIGPICls();
            SIGPIDao           sigpiDao      = new SIGPIDao();

            sigpiDao.ConnectLocalDB(parametros.RutaBD);
            sigpiDao.UltimaFechaIncorporacion(sigpi);
            sigpi.Parametros = parametros;

            OleDbCommand   command = sigpiDao.LocalDBConnection.CreateCommand();
            OleDbParameter param   = command.CreateParameter();
            OleDbParameter param1  = command.CreateParameter();

            param.ParameterName = "fecProce";
            param.Value         = sigpi.FechaProcesamiento;

            command.CommandText = "UPDATE FECHAS_PROCESO SET FEC_PROCE = @fecProce";
            command.Parameters.Add(param);

            string sSQL = ""; // "UPDATE FECHAS_PROCESO SET FEC_PROCE = #" + sigpi.FechaProcesamiento.ToString("MM/dd/yyyy") + "#";

            try
            {
                sigpiDao.EjecutarSentenciaSinQuery(command);
            }
            catch (Exception ex)
            {
                MessageBox.Show("No se pudo actualizar la fecha de incorporacion.\n" + ex.Message);
            }

            IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass();
            IStepProgressor        pStepPro   = pProDiaFac.Create(null, 0);

            pStepPro.MinRange  = 1;
            pStepPro.MaxRange  = 5;
            pStepPro.StepValue = 1;
            IProgressDialog2 pProDia = (IProgressDialog2)pStepPro;

            pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe;

            pProDia.Title = "Generar Modelo Amenazas";
            pProDia.ShowDialog();
            pStepPro.Step();
            pStepPro.Message = "Generando Grids Meteorologicos...";

            IFeatureClass     pFeatureClass;
            IWorkspaceFactory pShpWorkspaceFactory     = new ShapefileWorkspaceFactoryClass();
            IWorkspaceFactory pFileGDBWorkspaceFactory = new FileGDBWorkspaceFactoryClass();

            string sFormatTmp = "gdb_" + sigpi.FechaProcesamiento.ToString("yyyyMMdd") + "_" +
                                DateTime.Now.ToString("HHmmss");

            tempDir = sigpi.Parametros.TempDir;

            if (tempDir == null || tempDir.Trim().Equals(""))
            {
                tempDir = System.IO.Path.GetTempPath();
            }
            string sRutaFileGDB = System.IO.Path.GetTempPath() + sFormatTmp + ".gdb";

            if (System.IO.Directory.Exists(sRutaFileGDB))
            {
                try
                {
                    System.IO.Directory.Delete(sRutaFileGDB);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("No se pudo borrar la File Geodatabase Temporal: " +
                                    sRutaFileGDB +
                                    " Intente Borrarla Manualmente. " + ex.Message);
                    return;
                }
            }

            Geoprocessor   gp = new Geoprocessor();
            IWorkspaceName pWSName;
            string         sCapaResultado = "Amenaza_" + sigpi.FechaProcesamiento.ToString("yyyy_MM_dd");

            string sRutaGdbResultados = parametros.RutaSIGPI + parametros.Resultado + "\\" +
                                        sigpi.FechaProcesamiento.Year.ToString() + "-" +
                                        sigpi.FechaProcesamiento.ToString("MM") + "-Modelos.gdb";

            if (System.IO.Directory.Exists(sRutaGdbResultados))
            {
                GPUtilitiesClass gpUtilClass = new GPUtilitiesClass();
                try
                {
                    Delete del = new Delete();
                    del.in_data = sRutaGdbResultados + "\\" + sCapaResultado;
                    gp.Execute(del, null);
                }
                catch (Exception)
                {
                }
            }
            else
            {
                try
                {
                    pWSName = pFileGDBWorkspaceFactory.Create(parametros.RutaSIGPI + parametros.Resultado + "\\",
                                                              sigpi.FechaProcesamiento.Year.ToString() + "-" +
                                                              sigpi.FechaProcesamiento.ToString("MM") + "-Modelos.gdb", null, 0);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("No se pudo crear la Geodatabase de resultados: \n" + sRutaGdbResultados);
                    pStepPro.Hide();
                }
            }

            pWSName = pFileGDBWorkspaceFactory.Create(System.IO.Path.GetTempPath(), sFormatTmp, null, 0);
            ESRI.ArcGIS.esriSystem.IName name = (ESRI.ArcGIS.esriSystem.IName)pWSName;

            IFeatureWorkspace pWorkspaceTemp;

            try
            {
                pWorkspaceTemp = (IFeatureWorkspace)name.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            IWorkspaceFactory pWF     = new AccessWorkspaceFactoryClass();
            IFeatureWorkspace pWSMask = (IFeatureWorkspace)pWF.OpenFromFile(parametros.RutaGBD, 0);
            IGeoDataset       pFCMask = (IGeoDataset)pWSMask.OpenFeatureClass(parametros.Mascara);
            ISpatialReference pSpaRef = pFCMask.SpatialReference;
            IEnvelope         pEnv    = pFCMask.Extent;

            string sNombreTabla = "TMPPR_";

            DateTime fechaProcesamiento = sigpi.FechaProcesamiento;

            fechaProcesamiento = fechaProcesamiento.Date;


            for (int i = 0; i < 10; i++)
            {
                try
                {
                    sigpiDao.EjecutarSentenciaSinQuery("DROP TABLE " + sNombreTabla + i.ToString());
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.Message);
                }
                // "IIf([LECTUS_PRECI]![LECTURA]<=2,5,IIf([LECTUS_PRECI]![LECTURA]<=8 And [LECTUS_PRECI]![LECTURA]>2,4,IIf([LECTUS_PRECI]![LECTURA]<=14 And [LECTUS_PRECI]![LECTURA]>8,3,IIf([LECTUS_PRECI]![LECTURA]<=24 And [LECTUS_PRECI]![LECTURA]>14,2,IIf([LECTUS_PRECI]![LECTURA]>24,1,0))))) AS LECTURAS " +
                //sSQL = "SELECT CODIGO, FECHA, X, Y, LECTURA AS RASTERVALU " +
                //              "INTO " + sNombreTabla + i.ToString() + " " +
                //              "FROM LECTUS_PRECI " +
                //              "WHERE (((FECHA)=#" + sigpi.FechaProcesamiento.AddDays(-i).ToString("MM/dd/yyyy") + "#))";
                command             = sigpiDao.LocalDBConnection.CreateCommand();
                command.CommandText = "SELECT CODIGO, FECHA, X, Y, LECTURA AS RASTERVALU " +
                                      "INTO " + sNombreTabla + i.ToString() + " " +
                                      "FROM LECTUS_PRECI " +
                                      "WHERE (((FECHA) >=@fecha) and ((FECHA) <@fecha1))";
                param = command.CreateParameter();
                param.ParameterName = "fecha";
                param.Value         = sigpi.FechaProcesamiento.AddDays(-i);
                command.Parameters.Add(param);
                param1 = command.CreateParameter();
                param1.ParameterName = "fecha1";
                param1.Value         = sigpi.FechaProcesamiento.AddDays(-i + 1);
                command.Parameters.Add(param1);

                try
                {
                    sigpiDao.EjecutarSentenciaSinQuery(command);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error generando las tablas temporales de precipitaciones. Descripcion: \n" + ex.Message);
                    //pProDia.HideDialog();
                    return;
                }
            }

            try
            {
                sigpiDao.EjecutarSentenciaSinQuery("DROP TABLE TEMPERATURA_PROMEDIO");
            }
            catch (Exception ex)
            {
            }

            //"IIf(Avg(LECTUS_TEMPE.LECTURA)<=6,1,IIf(Avg(LECTUS_TEMPE.LECTURA) <=12 And Avg(LECTUS_TEMPE.LECTURA)>6,2," +
            //"IIf(Avg(LECTUS_TEMPE.LECTURA)<=18 And Avg(LECTUS_TEMPE.LECTURA)>12,3,IIf(Avg(LECTUS_TEMPE.LECTURA)<=24 And " +
            //"Avg(LECTUS_TEMPE.LECTURA)>12,4,IIf(Avg(LECTUS_TEMPE.LECTURA)>24,5,0))))) AS LECTURAS, " +

            //sSQL = "SELECT CODIGO, Max(LECTUS_TEMPE.FECHA) AS FECHA, 10 AS Num_Dias, X, Y, AVG(LECTURA) AS RASTERVALU " +
            //        "INTO TEMPERATURA_PROMEDIO " +
            //        "FROM LECTUS_TEMPE " +
            //        "WHERE (((FECHA)>=#" + sigpi.FechaProcesamiento.AddDays(-10).ToString("MM/dd/yyyy") + "# " +
            //        "And (FECHA)<=#" + sigpi.FechaProcesamiento.ToString("MM/dd/yyyy") + "#)) " +
            //        "GROUP BY CODIGO, X, Y";
            command             = sigpiDao.LocalDBConnection.CreateCommand();
            command.CommandText = "SELECT CODIGO, Max(LECTUS_TEMPE.FECHA) AS FECHA, 10 AS Num_Dias, X, Y, AVG(LECTURA) AS RASTERVALU " +
                                  "INTO TEMPERATURA_PROMEDIO " +
                                  "FROM LECTUS_TEMPE " +
                                  "WHERE (((FECHA)>= @fecha1 " +
                                  "And (FECHA)<= @fecha)) " +
                                  "GROUP BY CODIGO, X, Y";
            param = command.CreateParameter();
            param.ParameterName = "fecha";
            param.Value         = sigpi.FechaProcesamiento;
            param1 = command.CreateParameter();
            param1.ParameterName = "fecha1";
            param1.Value         = sigpi.FechaProcesamiento.AddDays(-10);
            command.Parameters.Add(param1);
            command.Parameters.Add(param);

            try
            {
                sigpiDao.EjecutarSentenciaSinQuery(command);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Generando Tabla: TEMPERATURA_PROMEDIO " + ex.Message);
                pProDia.HideDialog();
                return;
            }

            string sExpression = "";
            string sOutGrid;
            double dPeso = 0;
            string sAmenazaXPrecipitacion    = sRutaFileGDB + "\\amenaza_x_precipitacion";
            string sTablaTemperaturaPromedio = "TEMPERATURA_PROMEDIO";
            string sFCTempPromedio           = "TEMP_PROMEDIO";
            string sPrefijoIDW                     = "idw";
            string sAmenazaXTemperatura            = sRutaFileGDB + "\\" + "amenaza_x_temperatura";
            string sAmenazasParciales              = parametros.RutaGBD + "\\" + "amenazas_parciales_2";
            string sAmenazaBruta                   = sRutaFileGDB + "\\amenaza_incendio_bruta";
            string sAmenazaFinal                   = sRutaFileGDB + "\\amenaza_incendio_final";
            string sTablaReclassIncendios          = parametros.TablaReclasificacionIncendios;     //"tbl_reclass_amenaza_incendios";
            string sTablaReclassTemp               = parametros.TablaReclasificacionTemperatura;   //"tbl_reclass_temperatura";
            string sTablaReclassPrecip             = parametros.TablaReclasificacionPrecipitacion; //"tbl_reclass_precipitacion";
            string sAmenazaXTemperaturaCombinada   = sRutaFileGDB + "\\" + "amenaza_x_temperatura_combinada";
            string sEstVirtualesPrecipitacion      = sRutaFileGDB + "\\" + "estaciones_virtuales_precipitacion";
            string sAmenazaXPrecipitacionCombinada = sRutaFileGDB + "\\" + "amenaza_x_precipitacion_combinada";
            string sAmenazaFinalBrutaNVI           = sRutaFileGDB + "\\" + "amenaza_incend_raw_nvi";
            string sNVITempReclass                 = sRutaFileGDB + "\\" + "nvi_reclass_temp";
            string sFromField             = "FROM_";
            string sToField               = "TO_";
            string sOutField              = "OUT";
            string sNoData                = "NODATA";
            string sFieldLecturas         = "RASTERVALU";               //LECTURAS";
            string sTipoEstadistico       = parametros.TipoEstadistico; //"MAXIMUM";
            string sAmenazaXPrecipReclass = sAmenazaXPrecipitacion + "_reclass";
            string sAmenazaXTempReclass   = sAmenazaXTemperatura + "_reclass";
            string nvi = parametros.RutaSIGPI + "NVI" + "\\" + "tmpMosaic.500m_16_days_NDVI_GEO.tif";

            double dPesoPrecipitacion     = parametros.PesoPrecipitacion;     //0.29;
            double dPesoTemperatura       = parametros.PesoTemperatura;       //0.24;
            double dPesoAmenazasParciales = parametros.PesoAmenazasParciales; //0.47;

            IDataset         pDS;
            IDatasetName     pDSName;
            IDatasetName     pDSName2  = new FeatureClassNameClass();
            IExportOperation pExportOp = new ExportOperationClass();

            string sEstacionesVirtuales           = sRutaFileGDB + "\\" + "EstacionesVirtuales.shp";
            ExtractValuesToPoints extractValPoint = new ExtractValuesToPoints();

            extractValPoint.in_point_features  = sEstacionesVirtuales;
            extractValPoint.interpolate_values = "NONE";
            extractValPoint.add_attributes     = "VALUE_ONLY";


            //'0.037037037;
            // 1" = 1/3600
            double dCellSize = parametros.TamanoCelda / (3600 * 30);

            double[] iPesos      = parametros.Pesos; //{ 30, 20, 10, 9, 8, 7, 6, 5, 4, 3 };
            double   iTotalPesos = 0;                //102;

            foreach (double dP in iPesos)
            {
                iTotalPesos += dP;
            }

            gp.AddOutputsToMap = bMostrarIntermedios;
            gp.SetEnvironmentValue("Mask", parametros.RutaGBD + "\\" + parametros.Mascara);
            gp.SetEnvironmentValue("Extent", pEnv.XMin.ToString() + " " + pEnv.YMin.ToString() + " " +
                                   pEnv.XMax.ToString() + " " + pEnv.YMax.ToString());

            ESRI.ArcGIS.SpatialAnalystTools.Idw idw = new Idw();
            idw.z_field   = sFieldLecturas;
            idw.cell_size = dCellSize;

            for (int i = 0; i < 10; i++)
            {
                pFeatureClass          = procesamiento.FCPrecipitacion(sNombreTabla + i.ToString(), pSpaRef);
                pDS                    = (IDataset)pFeatureClass;
                pDSName                = (IDatasetName)pDS.FullName;
                pDSName2.Name          = sNombreTabla + i.ToString();
                pDSName2.WorkspaceName = pWSName;
                try
                {
                    pExportOp.ExportFeatureClass(pDSName, null, null, null, (IFeatureClassName)pDSName2, 0);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    pProDia.HideDialog();
                    return;
                }

                if (bUsarSatelite)
                {
                    //Geoprocessor gp1 = new Geoprocessor();
                    //extractValPoint.in_raster = sRastersPrecipitacion[i];  // txtRutaPrecipitacion.Text;
                    //extractValPoint.out_point_features = sEstVirtualesPrecipitacion + i.ToString();

                    //try
                    //{
                    //  gp1.Execute(extractValPoint, null);
                    //}
                    //catch (Exception ex)
                    //{
                    //  MessageBox.Show(ex.Message);
                    //}

                    //Merge merge = new Merge();
                    //string sInputMerge = sRutaFileGDB + "\\" + sNombreTabla + i.ToString() + ";" + sEstVirtualesPrecipitacion + i.ToString();
                    //merge.inputs = sInputMerge;
                    ////"[" + sRutaFileGDB + "\\" + sNombreTabla + i.ToString() + ";" + sEstVirtualesPrecipitacion + i.ToString() + "]" ;
                    //merge.output = sRutaFileGDB + "\\" + "est_precip_temporal" + i.ToString();
                    //try
                    //{
                    //  gp.Execute(merge, null);
                    //}
                    //catch (Exception ex)
                    //{
                    //  MessageBox.Show(ex.Message);
                    //}

                    //idw.in_point_features = sRutaFileGDB + "\\" + "est_precip_temporal" + i.ToString();

                    idw.in_point_features = sRutaFileGDB + "\\" + sNombreTabla + i.ToString();
                }
                else
                {
                    idw.in_point_features = sRutaFileGDB + "\\" + sNombreTabla + i.ToString();
                }

                sOutGrid       = sRutaFileGDB + "\\" + sPrefijoIDW + "_" + sNombreTabla + i.ToString();
                idw.out_raster = sOutGrid;
                try
                {
                    gp.Execute(idw, null);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

                dPeso        = iPesos[i] / iTotalPesos;
                sExpression += "( Raster(r'" + sOutGrid + "') * " + dPeso.ToString().Replace(",", ".") + ")";
                if (i < 9)
                {
                    sExpression += " + ";
                }
            }


            pStepPro.Step();

            ////for (int i = 0; i < 10; i++)
            ////{
            ////  //pStepPro.Message = "Generando Modelo Precipitacion: " + i.ToString();
            ////  sOutGrid = sRutaFileGDB + "\\" + sPrefijoIDW + "_" + sNombreTabla + i.ToString();
            ////  idw.in_point_features = sRutaFileGDB + "\\" + sNombreTabla + i.ToString();
            ////  idw.out_raster = sOutGrid;
            ////  gp.Execute(idw, null);
            ////  dPeso = iPesos[i] / iTotalPesos;
            ////  sExpression += "(" + sOutGrid + " * " + dPeso.ToString() + ")";
            ////  if (i < 9)
            ////    sExpression += " + ";
            ////}
            //gp.AddMessage("Expresion: " + sExpression);
            //SingleOutputMapAlgebra mapAlgebra = new SingleOutputMapAlgebra();

            ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator mapAlgebra = new RasterCalculator();
            //mapAlgebra.expression_string = sExpression;
            // mapAlgebra.out_raster = sAmenazaXPrecipitacion;

            mapAlgebra.expression = sExpression;

            mapAlgebra.output_raster = sAmenazaXPrecipitacion;
            pStepPro.Message         = "Generando Amenaza Precipitacion...";
            try
            {
                gp.Execute(mapAlgebra, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Generando Amenaza x Precipitacion. " + ex.Message);
                pProDia.HideDialog();
                return;
            }

            //if (bUsarSatelite)  // Para la combinacion de la precipitacion x estaciones y satelite
            //{

            //  //CellStatistics cellStatisticsP = new CellStatistics();
            //  //cellStatisticsP.in_rasters_or_constants = sAmenazaXPrecipitacion + ";" + txtRutaPrecipitacion.Text;
            //  //cellStatisticsP.out_raster = sAmenazaXPrecipitacionCombinada;
            //  //cellStatisticsP.statistics_type = sTipoEstadistico;
            //  try
            //  {
            //    gp.Execute(extractValPoint, null);
            //    //sAmenazaXPrecipitacion = sAmenazaXPrecipitacionCombinada;
            //  }
            //  catch (Exception ex)
            //  {
            //    MessageBox.Show("Error generando estaciones virtuales con precipitacion." + ex.Message);
            //    return;
            //  }

            //  Merge merge = new Merge();
            //  merge.inputs =

            //}

            DateTime date   = sigpi.FechaProcesamiento;
            string   sMonth = date.ToString("MM");

            pStepPro.Step();
            pStepPro.Message = "Generando Amenaza x Temperatura";
            pFeatureClass    = procesamiento.FCPrecipitacion(sTablaTemperaturaPromedio, pSpaRef);
            pDS                    = (IDataset)pFeatureClass;
            pDSName                = (IDatasetName)pDS.FullName;
            pDSName2.Name          = sFCTempPromedio;
            pDSName2.WorkspaceName = pWSName;
            try
            {
                pExportOp.ExportFeatureClass(pDSName, null, null, null, (IFeatureClassName)pDSName2, 0);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            idw.in_point_features = sRutaFileGDB + "\\" + sFCTempPromedio;
            idw.out_raster        = sAmenazaXTemperatura;
            try
            {
                gp.Execute(idw, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }


            //if (bUsarSatelite)
            //{
            //  Geoprocessor gp1 = new Geoprocessor();
            //  Con pContmp = new Con();
            //  pContmp.in_conditional_raster = txtRutaTemperatura.Text;
            //  pContmp.in_true_raster_or_constant = txtRutaTemperatura.Text;
            //  pContmp.in_false_raster_or_constant = -99;
            //  string sRasterTTemp = sAmenazaXTemperaturaCombinada + "_ajs";
            //  pContmp.out_raster = sRasterTTemp;
            //  pContmp.where_clause = "VALUE < 55";

            //  try
            //  {
            //    gp1.Execute(pContmp, null);
            //  }
            //  catch (Exception)
            //  {
            //    sRasterTTemp = txtRutaTemperatura.Text; ;
            //  }
            //  gp1 = null;

            //  CellStatistics cellStatistics = new CellStatistics();
            //  cellStatistics.in_rasters_or_constants = sAmenazaXTemperatura + ";" + sRasterTTemp;
            //  cellStatistics.out_raster = sAmenazaXTemperaturaCombinada;
            //  cellStatistics.statistics_type = sTipoEstadistico;
            //  try
            //  {
            //    gp.Execute(cellStatistics, null);
            //    sAmenazaXTemperatura = sAmenazaXTemperaturaCombinada;
            //  }
            //  catch (Exception)
            //  {
            //  }
            //}

            ReclassByTable rbt = new ReclassByTable();

            rbt.in_raster          = sAmenazaXPrecipitacion;
            rbt.in_remap_table     = sTablaReclassPrecip; // parametros.RutaGBD + "\\" + sTablaReclassPrecip;
            rbt.from_value_field   = sFromField;
            rbt.to_value_field     = sToField;
            rbt.output_value_field = sOutField;
            rbt.missing_values     = sNoData;
            rbt.out_raster         = sAmenazaXPrecipReclass;
            //pStepPro.Message = "Generando Amenaza X Precipitacion Reclasificada";
            try
            {
                gp.Execute(rbt, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                pProDia.HideDialog();
                return;
            }

            rbt.in_raster      = sAmenazaXTemperatura;
            rbt.in_remap_table = sTablaReclassTemp; // parametros.RutaGBD + "\\" + sTablaReclassTemp;
            rbt.out_raster     = sAmenazaXTempReclass;
            //pStepPro.Message = "Generando Amenaza X Temperatura Reclasificada";
            try
            {
                gp.Execute(rbt, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                pProDia.HideDialog();
                return;
            }

            sExpression = "( Raster(r'" + sAmenazaXPrecipReclass + "') * " + dPesoPrecipitacion.ToString().Replace(",", ".") + ") + " +
                          "( Raster(r'" + sAmenazaXTempReclass + "') * " + dPesoTemperatura.ToString().Replace(",", ".") + ") + " +
                          "( Raster(r'" + sAmenazasParciales + "') * " + dPesoAmenazasParciales.ToString().Replace(",", ".") + ")";

            //mapAlgebra.expression_string = sExpression;
            //mapAlgebra.out_raster = sAmenazaBruta;

            sExpression              = sExpression.Replace("\\\\", "/").Replace("\\", "/");
            mapAlgebra.expression    = sExpression;
            mapAlgebra.output_raster = sAmenazaBruta;

            pStepPro.Message = "Generando Amenaza Final Bruta";
            try
            {
                gp.Execute(mapAlgebra, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            //if (txtRutaNVI.Text.Trim() != "")
            //{
            Geoprocessor gp2 = new Geoprocessor();

            mapAlgebra               = new RasterCalculator();
            sExpression              = "Con (Raster(r'" + nvi + "') < 0.75, Raster(r'" + sAmenazaBruta + "'), Raster(r'" + sAmenazaBruta + "') -1)";
            sExpression              = sExpression.Replace("\\\\", "/").Replace("\\", "/");
            mapAlgebra.expression    = sExpression;
            mapAlgebra.output_raster = sAmenazaFinalBrutaNVI;

            try
            {
                gp2.Execute(mapAlgebra, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            //}


            rbt.in_raster          = sAmenazaFinalBrutaNVI;  // sAmenazaBruta;
            rbt.in_remap_table     = sTablaReclassIncendios; // parametros.RutaGBD + "\\" + sTablaReclassIncendios;
            rbt.from_value_field   = sFromField;
            rbt.to_value_field     = sToField;
            rbt.output_value_field = sOutField;
            rbt.missing_values     = sNoData;
            rbt.out_raster         = sAmenazaFinal;
            pStepPro.Message       = "Generando Amenaza Final Reclasificada";
            gp.AddOutputsToMap     = true;
            try
            {
                gp.Execute(rbt, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            Copy copy = new Copy();

            copy.in_data = sAmenazaFinal;

            copy.out_data = sRutaGdbResultados + "\\" + sCapaResultado;
            try
            {
                gp.Execute(copy, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Copiando el resultado. \n " + ex.Message);
            }



            MessageBox.Show("Algoritmo completo ejecutado: " + sRutaGdbResultados + "\\" + sCapaResultado);

            if (m_pApp != null)
            {
                IRasterLayer pRLayer = new RasterLayerClass();
                try
                {
                    IWorkspaceFactory  pWF2      = new FileGDBWorkspaceFactoryClass();
                    IRasterWorkspaceEx pRW       = (IRasterWorkspaceEx)pWF2.OpenFromFile(sRutaGdbResultados, 0);
                    IRasterDataset     pRDataset = pRW.OpenRasterDataset(sCapaResultado);
                    pRLayer.CreateFromDataset(pRDataset);
                    pRLayer.Name = sCapaResultado;
                    IMxDocument pMxDoc = m_pApp.Document as IMxDocument;
                    IMap        pMap   = pMxDoc.FocusMap;
                    AsignarSimbologiaProbabilidad(pRLayer);
                    pMap.AddLayer(pRLayer);
                    if (pMap.LayerCount > 0)
                    {
                        pMap.MoveLayer(pRLayer, pMap.LayerCount - 1);
                    }

                    pMxDoc.UpdateContents();
                    pMxDoc.ActiveView.Refresh();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error cargando Capa!!!");
                }
            }

            pProDia.HideDialog();
        }
Ejemplo n.º 30
0
        public void listRasters(Geoprocessor GP)
        {
            // List all TIFF files in the workspace and build pyramids.
            GP.SetEnvironmentValue("workspace", @"C:\Corey\Ccm\results");
            IGpEnumList rasters = GP.ListRasters("*", "TIFF");
            string raster = rasters.Next();

            // Intialize the BuildPyramids tool.
            BuildPyramids pyramids = new BuildPyramids();

            while (raster != "")
            {

                // Set input raster dataset.
                pyramids.in_raster_dataset = raster;
                GP.Execute(pyramids, null);
                raster = rasters.Next();
            }
        }
Ejemplo n.º 31
0
        private void button1_Click(object sender, EventArgs e)
        {
            string myListBoxContent;
            double myCellSize;

            myCellSize = System.Convert.ToDouble(textBox4.Text);
            //try
            {
                myListBoxContent = "正在转换所选ShpFile到栅格数据...";
                textBox3.Text   += myListBoxContent;
                ILayer        selectedLayer        = mainForm.axMapControl1.get_Layer(comboBox1.SelectedIndex);
                IFeatureLayer selectedFeatureLayer = selectedLayer as IFeatureLayer;
                IFeatureClass selectedFeatureClass = selectedFeatureLayer.FeatureClass;
                Geoprocessor  pGeoprocessor        = new Geoprocessor();
                pGeoprocessor.OverwriteOutput = true;

                if (selectedFeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
                {
                    ESRI.ArcGIS.ConversionTools.PointToRaster pPointToRaster =
                        new ESRI.ArcGIS.ConversionTools.PointToRaster();
                    pGeoprocessor.SetEnvironmentValue("workspace", myFilePath);
                    pPointToRaster.cellsize          = myCellSize;
                    pPointToRaster.in_features       = selectedFeatureLayer;
                    pPointToRaster.value_field       = selectedFeatureClass.Fields.get_Field(comboBox2.SelectedIndex);
                    pPointToRaster.out_rasterdataset = textBox2.Text + ".tif";
                    pGeoprocessor.Execute(pPointToRaster, null);
                    myListBoxContent = "转换成功!";
                    textBox3.Text   += Environment.NewLine + Environment.NewLine + myListBoxContent;
                }
                else if (selectedFeatureClass.ShapeType == esriGeometryType.esriGeometryPolyline)
                {
                    ESRI.ArcGIS.ConversionTools.PolylineToRaster pPolylineToRaster =
                        new ESRI.ArcGIS.ConversionTools.PolylineToRaster();
                    pGeoprocessor.SetEnvironmentValue("workspace", myFilePath);
                    pPolylineToRaster.cellsize          = myCellSize;
                    pPolylineToRaster.in_features       = selectedFeatureLayer;
                    pPolylineToRaster.value_field       = selectedFeatureClass.Fields.get_Field(comboBox2.SelectedIndex);
                    pPolylineToRaster.out_rasterdataset = textBox2.Text + ".tif";
                    pGeoprocessor.Execute(pPolylineToRaster, null);
                    myListBoxContent = "转换成功!";
                    textBox3.Text   += Environment.NewLine + Environment.NewLine + myListBoxContent;
                }
                else if (selectedFeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                {
                    ESRI.ArcGIS.ConversionTools.PolygonToRaster pPolygonToRaster =
                        new ESRI.ArcGIS.ConversionTools.PolygonToRaster();
                    pGeoprocessor.SetEnvironmentValue("workspace", myFilePath);
                    pPolygonToRaster.cellsize          = myCellSize;
                    pPolygonToRaster.in_features       = selectedFeatureLayer;
                    pPolygonToRaster.value_field       = selectedFeatureClass.Fields.get_Field(comboBox2.SelectedIndex);
                    pPolygonToRaster.out_rasterdataset = textBox2.Text + ".tif";
                    pGeoprocessor.Execute(pPolygonToRaster, null);
                    myListBoxContent = "转换成功!";
                    textBox3.Text   += Environment.NewLine + Environment.NewLine + myListBoxContent;
                }
                else
                {
                    MessageBox.Show("请选择正确的ShapeFile文件");
                }

                if (MessageBox.Show("是否将生成的新Raster文件添加到图层", "Confirm Message",
                                    MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    IRasterLayer myRasterLayer = new RasterLayerClass();
                    try
                    {
                        myRasterLayer.CreateFromFilePath(myFilePath + "\\" + textBox2.Text + ".tif");
                        mainForm.axMapControl1.AddLayer(myRasterLayer, 0);
                    }
                    catch
                    {
                        MessageBox.Show("打开文件错误!");
                    }
                }
            }
        }
Ejemplo n.º 32
0
        private static void ConvertPersonalGeodatabaseToFileGeodatabase()
        {
            // Initialize the Geoprocessor
            Geoprocessor geoprocessor = new Geoprocessor();

            // Allow for the overwriting of file geodatabases, if they previously exist.
            geoprocessor.OverwriteOutput = true;

            // Set the workspace to a folder containing personal geodatabases.
            geoprocessor.SetEnvironmentValue("workspace", @"C:\data");

            // Identify personal geodatabases.
            IGpEnumList workspaces = geoprocessor.ListWorkspaces("*", "Access");
            string      workspace  = workspaces.Next();

            while (workspace != "")
            {
                // Set workspace to current personal geodatabase
                geoprocessor.SetEnvironmentValue("workspace", workspace);

                // Create a file geodatabase with the same name as the personal geodatabase
                string gdbname = System.IO.Path.GetFileName(workspace).Replace(".mdb", "");
                string dirname = System.IO.Path.GetDirectoryName(workspace);

                // Execute CreateFileGDB tool
                CreateFileGDB createFileGDBTool = new CreateFileGDB(dirname, gdbname + ".gdb");
                geoprocessor.Execute(createFileGDBTool, null);

                // Initialize the Copy Tool
                Copy copyTool = new Copy();

                // Identify feature classes and copy to file geodatabase
                IGpEnumList fcs = geoprocessor.ListFeatureClasses("", "", "");
                string      fc  = fcs.Next();
                while (fc != "")
                {
                    Console.WriteLine("Copying " + fc + " to " + gdbname + ".gdb");
                    copyTool.in_data  = fc;
                    copyTool.out_data = dirname + "\\" + gdbname + ".gdb" + "\\" + fc;
                    geoprocessor.Execute(copyTool, null);
                    fc = fcs.Next();
                }

                // Identify feature datasets and copy to file geodatabase
                IGpEnumList fds = geoprocessor.ListDatasets("", "");
                string      fd  = fds.Next();
                while (fd != "")
                {
                    Console.WriteLine("Copying " + fd + " to " + gdbname + ".gdb");
                    copyTool.in_data   = fd;
                    copyTool.data_type = "FeatureDataset";
                    copyTool.out_data  = dirname + "\\" + gdbname + ".gdb" + "\\" + fd;
                    try
                    {
                        geoprocessor.Execute(copyTool, null);
                    }
                    catch (Exception ex)
                    {
                        object sev = null;
                        System.Windows.Forms.MessageBox.Show(ex.Message);
                    }
                    fd = fds.Next();
                }

                // Identify tables and copy to file geodatabase
                IGpEnumList tbls = geoprocessor.ListTables("", "");
                string      tbl  = tbls.Next();
                while (tbl != "")
                {
                    Console.WriteLine("Copying " + tbl + " to " + gdbname + ".gdb");
                    copyTool.in_data  = tbl;
                    copyTool.out_data = dirname + "\\" + gdbname + ".gdb" + "\\" + tbl;
                    geoprocessor.Execute(copyTool, null);
                    tbl = tbls.Next();
                }

                workspace = workspaces.Next();
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// 生成等值线
        /// </summary>
        /// <params name="targetworkspace"></params>
        /// <params name="nameOftargetFeatureClass"></params>
        /// <params name="sLayerAliasName"></params>
        private bool CreateContours(IWorkspace targetworkspace, string nameOftargetFeatureClass,
                                    string sLayerAliasName, string extent, ref string failInfo)
        {
            double douElevation;

            //设置一个最小值
            progressBarControl1.Properties.Minimum = 0;
            //设置一个最大值
            progressBarControl1.Properties.Maximum = 6;
            //设置步长,即每次增加的数
            progressBarControl1.Properties.Step = 1;
            //设置进度条的样式
            progressBarControl1.Properties.ProgressViewStyle = ProgressViewStyle.Solid;
            progressBarControl1.Position = 0;

            try
            {
                Geoprocessor GP = new Geoprocessor();

                if (withIn(m_strDataFilePath) == false)
                {
                    return(false);
                }
                if (TB_Interval.Text == "")
                {
                    MessageBox.Show("请输入正确的等高距!", "提示!");
                    return(false);
                }
                if (double.TryParse(TB_Interval.Text.Trim(), out douElevation))
                {
                }
                else
                {
                    TB_Interval.Text = null;
                    MessageBox.Show("请输入正确的等高距!", "提示!");
                    return(false);
                }

                string featurOut = m_MakeContoursFolder + "\\Cont.shp";
                int    k         = 0;
                while (File.Exists(featurOut))
                {
                    k++;
                    featurOut = m_MakeContoursFolder + "\\Cont" + k.ToString() + ".shp";
                }
                int countCont = Directory.GetFiles(m_MakeContoursFolder, "Cont*").Length;
                if (countCont > 0)
                {
                    featurOut = m_MakeContoursFolder + "\\Cont" + countCont.ToString() + ".shp";
                }
                if (DrawContours.ConvertASCIIDescretePoint2FeatureClass(GP, m_strDataFilePath, featurOut) == false)
                {
                    return(false);
                }
                //执行步长
                this.progressBarControl1.PerformStep();

                string ContourRaster = m_MakeContoursFolder + "\\Spline";
                //string ContourRaster = m_MakeContoursFolder + "\\" + nameOftargetFeatureClass + "_Render";
                if (extent != "")//右上左下  xmax  ymax  xmin  ymin
                {
                    GP.SetEnvironmentValue("Extent", extent);
                }
                bool   suc = false;
                string sRasterLayerAliasName = sLayerAliasName + "渲染图";
                ILayer rsLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, sRasterLayerAliasName);
                if (rsLayer != null)
                {
                    DataEditCommon.g_pMap.DeleteLayer(rsLayer);
                }
                if (Directory.Exists(ContourRaster))
                {
                    try
                    {
                        Directory.Delete(ContourRaster, true);
                    }
                    catch
                    {
                        k = 1;
                        while (Directory.Exists(ContourRaster))
                        {
                            ContourRaster = m_MakeContoursFolder + "\\Spline" + k.ToString();
                            k++;
                        }
                    }
                }
                switch (CB_InterpolationMethod.Text)
                {
                case "样条函数插值法":
                    suc = DrawContours.Interpolate2RasterSpline(GP, featurOut, ContourRaster, CB_SplineType.Text);
                    break;

                case "自然邻域插值法":
                    suc = DrawContours.Interpolate2RasterNN(GP, featurOut, ContourRaster);
                    break;

                case "克里格插值法":
                    suc = DrawContours.Interpolate2RasterKriging(GP, featurOut, ContourRaster,
                                                                 CB_semiVariogramProp.Text, CB_searchRadiusProp.Text);
                    break;

                case "反距离权重插值法":
                    suc = DrawContours.Interpolate2RasterIDW(GP, featurOut, ContourRaster);
                    break;

                case "趋势面插值法":
                    suc = DrawContours.TrendToRaster(GP, featurOut, ContourRaster);
                    break;
                }
                if (suc == false)
                {
                    return(false);
                }
                this.progressBarControl1.PerformStep();
                GP = new Geoprocessor();
                string R2Contour = m_MakeContoursFolder + "\\Contour.shp";
                k = 1;
                while (File.Exists(R2Contour))
                {
                    R2Contour = m_MakeContoursFolder + "\\Contour" + k.ToString() + ".shp";
                    k++;
                }
                int countContour = Directory.GetFiles(m_MakeContoursFolder, "Contour*").Length;
                if (countContour > 0)
                {
                    R2Contour = m_MakeContoursFolder + "\\Contour" + countContour.ToString() + ".shp";
                }

                if (DrawContours.SplineRasterToContour(GP, ContourRaster, R2Contour, douElevation) == false)
                {
                    return(false);
                }
                this.progressBarControl1.PerformStep();

                string EvEContour = m_MakeContoursFolder + "\\EvEContour.shp";
                k = 1;
                while (File.Exists(EvEContour))
                {
                    EvEContour = m_MakeContoursFolder + "\\EvEContour" + k.ToString() + ".shp";
                    k++;
                }
                int countEvEContour = Directory.GetFiles(m_MakeContoursFolder, "EvEContour*").Length;
                if (countEvEContour > 0)
                {
                    EvEContour = m_MakeContoursFolder + "\\EvEContour" + countEvEContour.ToString() + ".shp";
                }
                if (DrawContours.FeaturesTo3D(GP, R2Contour, EvEContour) == false)
                {
                    return(false);
                }
                this.progressBarControl1.PerformStep();

                //获得等值线Shp文件所在的工作空间
                IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
                IWorkspace        sourceworkspace  = workspaceFactory.OpenFromFile(m_MakeContoursFolder, 0);
                //裁切
                IPolygon bianjie = GetPolygon();

                //导入等值线Shp文件到数据库中
                DrawSpecialCommon drawspecial = new DrawSpecialCommon();
                string            nameOfsourceFeatureClass = EvEContour.Substring(EvEContour.LastIndexOf("\\") + 1);
                nameOfsourceFeatureClass = nameOfsourceFeatureClass.Substring(0, nameOfsourceFeatureClass.LastIndexOf("."));
                bool          Import = false;
                List <ziduan> list   = new List <ziduan>
                {
                    new ziduan("BID", ""),
                    new ziduan("mingcheng", sLayerAliasName),
                    new ziduan("mcid", "0"),
                    new ziduan("date", DateTime.Now.ToString()),
                    new ziduan("type", CB_InterpolationMethod.Text)
                };
                list.Add(new ziduan("BID", ""));
                list.Add(new ziduan("mingcheng", sLayerAliasName));
                list.Add(new ziduan("mcid", "0"));
                list.Add(new ziduan("date", DateTime.Now.ToString()));
                list.Add(new ziduan("type", CB_InterpolationMethod.Text));
                IFeatureLayer pFeatureLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, EditLayerName) as IFeatureLayer;
                string        WhereClause   = "mcid='" + "0" + "'";

                DataEditCommon.DeleteFeatureByWhereClause(pFeatureLayer, WhereClause);
                if (radioBtnKJ.Checked && bianjie != null)
                {
                    Import = IntersectAll(DataEditCommon.GetFeatureClassByName(sourceworkspace, nameOfsourceFeatureClass), bianjie, list);
                }
                else
                {
                    Import = drawspecial.ShapeImportGDB(sourceworkspace, targetworkspace, nameOfsourceFeatureClass, nameOftargetFeatureClass, list);
                }
                this.progressBarControl1.PerformStep();

                if (Import == false)
                {
                    MessageBox.Show(sLayerAliasName + "导入数据库失败!");
                    DataEditCommon.g_axTocControl.Update();
                    DataEditCommon.g_pAxMapControl.Refresh();
                    failInfo = sLayerAliasName;
                    return(false);
                }

                //添加相应的渲染图
                IRasterLayer newRasterLayer = new RasterLayerClass();
                newRasterLayer.CreateFromFilePath(ContourRaster);
                newRasterLayer = IntersectRaster(newRasterLayer, bianjie);
                //newRasterLayer.CreateFromDataset(newRasterDs);
                newRasterLayer.Name = sRasterLayerAliasName;
                UsingRasterStretchColorRampRender(newRasterLayer);
                //groupLayer.Add(newRasterLayer as ILayer);
                int indexPosition = DataEditCommon.g_pAxMapControl.LayerCount;//GroupLayer序号

                //判断MapControl中是否存在该图层
                ILayer mLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, sRasterLayerAliasName);
                if (mLayer != null)
                {
                    DataEditCommon.g_pMyMapCtrl.Map.DeleteLayer(mLayer);
                    indexPosition--;
                }
                DataEditCommon.g_pAxMapControl.AddLayer(newRasterLayer as ILayer, indexPosition);//添加到最下面
                DataEditCommon.g_pAxMapControl.ActiveView.Extent = newRasterLayer.AreaOfInterest;
                DataEditCommon.g_axTocControl.Update();
                DataEditCommon.g_pAxMapControl.Refresh();
                this.progressBarControl1.PerformStep();

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(false);
            }
        }
Ejemplo n.º 34
0
        private void button6_Click(object sender, EventArgs e)
        {
            Geoprocessor gp = new Geoprocessor();

            gp.AddOutputsToMap = true;
            gp.OverwriteOutput = true;
            CreateThiessenPolygons ct = new CreateThiessenPolygons();
            ILayer        points      = GetLayerByName(map, "public_library_shp");
            IFeatureClass fc          = (points as IFeatureLayer2).FeatureClass;

            ct.in_features       = fc;
            ct.out_feature_class = output;
            ILayer    bounds      = GetLayerByName(map, "cty00_shp");
            IEnvelope envelope    = bounds.AreaOfInterest.Envelope;
            string    envelopestr = string.Format("{0} {1} {2} {3}",
                                                  envelope.XMin, envelope.YMax, envelope.XMax, envelope.YMin);

            gp.SetEnvironmentValue("Extent", envelopestr);
            gp.Execute(ct, null);

            AddJoin joined = new AddJoin();

            joined.join_table        = population;
            joined.in_layer_or_view  = "trt00_shp";
            joined.in_field          = "STFID2";
            joined.join_field        = "GEO_ID";
            joined.out_layer_or_view = output + @"\joinedoutput";
            gp.Execute(joined, null);

            Intersect intersect = new Intersect();

            intersect.in_features       = "marketshare" + ";" + tracts;
            intersect.join_attributes   = "ALL";
            intersect.out_feature_class = output + @"\intersect";
            gp.Execute(intersect, null);

            AddField addedfield = new AddField();

            addedfield.in_table   = "intersect";
            addedfield.field_name = "field";
            addedfield.field_type = "FLOAT";
            gp.Execute(addedfield, null);

            AddJoin joined2 = new AddJoin();

            joined2.join_table        = population;
            joined2.in_layer_or_view  = "intersect";
            joined2.in_field          = "STFID2";
            joined2.join_field        = "GEO_ID";
            joined2.out_layer_or_view = output + @"\joinedoutput";
            gp.Execute(joined2, null);

            CalculateField calc = new CalculateField();

            calc.in_table   = "intersect";
            calc.field      = "field";
            calc.expression = "!population.P001001!*!intersect.Shape_Area!/!intersect_Area!";
            gp.Execute(calc, null);

            Dissolve dissolved = new Dissolve();

            dissolved.in_features       = intersect;
            dissolved.statistics_fields = "field";
            dissolved.out_feature_class = output + @"\dissolve";
            gp.Execute(dissolved, null);
        }
        private static void ConvertPersonalGeodatabaseToFileGeodatabase()
        {
            // Initialize the Geoprocessor
            Geoprocessor geoprocessor = new Geoprocessor();

            // Allow for the overwriting of file geodatabases, if they previously exist.
            geoprocessor.OverwriteOutput = true;

            // Set the workspace to a folder containing personal geodatabases.
            geoprocessor.SetEnvironmentValue("workspace", @"C:\data");

            // Identify personal geodatabases.
            IGpEnumList workspaces = geoprocessor.ListWorkspaces("*", "Access");
            string workspace = workspaces.Next();
            while (workspace != "")
            {
                // Set workspace to current personal geodatabase
                geoprocessor.SetEnvironmentValue("workspace", workspace);

                // Create a file geodatabase with the same name as the personal geodatabase
                string gdbname = System.IO.Path.GetFileName(workspace).Replace(".mdb", "");
                string dirname = System.IO.Path.GetDirectoryName(workspace);

                // Execute CreateFileGDB tool
                CreateFileGDB createFileGDBTool = new CreateFileGDB(dirname, gdbname + ".gdb");
                geoprocessor.Execute(createFileGDBTool, null);

                // Initialize the Copy Tool
                Copy copyTool = new Copy();

                // Identify feature classes and copy to file geodatabase
                IGpEnumList fcs = geoprocessor.ListFeatureClasses("", "", "");
                string fc = fcs.Next();
                while (fc != "")
                {
                    Console.WriteLine("Copying " + fc + " to " + gdbname + ".gdb");
                    copyTool.in_data = fc;
                    copyTool.out_data = dirname + "\\" + gdbname + ".gdb" + "\\" + fc;
                    geoprocessor.Execute(copyTool, null);
                    fc = fcs.Next();
                }

                // Identify feature datasets and copy to file geodatabase
                IGpEnumList fds = geoprocessor.ListDatasets("", "");
                string fd = fds.Next();
                while (fd != "")
                {
                    Console.WriteLine("Copying " + fd + " to " + gdbname + ".gdb");
                    copyTool.in_data = fd;
                    copyTool.data_type = "FeatureDataset";
                    copyTool.out_data = dirname + "\\" + gdbname + ".gdb" + "\\" + fd;
                    try
                    {
                        geoprocessor.Execute(copyTool, null);
                    }
                    catch (Exception ex)
                    {
                        object sev = null;
                        System.Windows.Forms.MessageBox.Show(ex.Message);
                    }
                    fd = fds.Next();
                }

                // Identify tables and copy to file geodatabase
                IGpEnumList tbls = geoprocessor.ListTables("", "");
                string tbl = tbls.Next();
                while (tbl != "")
                {
                    Console.WriteLine("Copying " + tbl + " to " + gdbname + ".gdb");
                    copyTool.in_data = tbl;
                    copyTool.out_data = dirname + "\\" + gdbname + ".gdb" + "\\" + tbl;
                    geoprocessor.Execute(copyTool, null);
                    tbl = tbls.Next();
                }

                workspace = workspaces.Next();
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// 生成等值线
        /// </summary>
        /// <params name="targetworkspace"></params>
        /// <params name="nameOftargetFeatureClass"></params>
        /// <params name="sLayerAliasName"></params>
        private bool CreateContours(IWorkspace targetworkspace, string nameOftargetFeatureClass,
            string sLayerAliasName, string extent, ref string failInfo)
        {
            double douElevation;

            //设置一个最小值
            progressBarControl1.Properties.Minimum = 0;
            //设置一个最大值
            progressBarControl1.Properties.Maximum = 6;
            //设置步长,即每次增加的数
            progressBarControl1.Properties.Step = 1;
            //设置进度条的样式
            progressBarControl1.Properties.ProgressViewStyle = ProgressViewStyle.Solid;
            progressBarControl1.Position = 0;

            try
            {
                Geoprocessor GP = new Geoprocessor();

                if (withIn(m_strDataFilePath) == false)
                    return false;
                if (TB_Interval.Text == "")
                {
                    MessageBox.Show("请输入正确的等高距!", "提示!");
                    return false;
                }
                if (double.TryParse(TB_Interval.Text.Trim(), out douElevation))
                { }
                else
                {
                    TB_Interval.Text = null;
                    MessageBox.Show("请输入正确的等高距!", "提示!");
                    return false;
                }

                string featurOut = m_MakeContoursFolder + "\\Cont.shp";
                int k = 0;
                while (File.Exists(featurOut))
                {
                    k++;
                    featurOut = m_MakeContoursFolder + "\\Cont" + k.ToString() + ".shp";

                }
                int countCont = Directory.GetFiles(m_MakeContoursFolder, "Cont*").Length;
                if (countCont > 0)
                {
                    featurOut = m_MakeContoursFolder + "\\Cont" + countCont.ToString() + ".shp";
                }
                if (DrawContours.ConvertASCIIDescretePoint2FeatureClass(GP, m_strDataFilePath, featurOut) == false)
                    return false;
                //执行步长
                this.progressBarControl1.PerformStep();

                string ContourRaster = m_MakeContoursFolder + "\\Spline";
                //string ContourRaster = m_MakeContoursFolder + "\\" + nameOftargetFeatureClass + "_Render";
                if (extent != "")//右上左下  xmax  ymax  xmin  ymin
                    GP.SetEnvironmentValue("Extent", extent);
                bool suc = false;
                string sRasterLayerAliasName = sLayerAliasName + "渲染图";
                ILayer rsLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, sRasterLayerAliasName);
                if (rsLayer != null)
                {
                    DataEditCommon.g_pMap.DeleteLayer(rsLayer);
                }
                if (Directory.Exists(ContourRaster))
                {
                    try
                    {
                        Directory.Delete(ContourRaster, true);
                    }
                    catch
                    {
                        k = 1;
                        while (Directory.Exists(ContourRaster))
                        {
                            ContourRaster = m_MakeContoursFolder + "\\Spline" + k.ToString();
                            k++;
                        }
                    }
                }
                switch (CB_InterpolationMethod.Text)
                {
                    case "样条函数插值法":
                        suc = DrawContours.Interpolate2RasterSpline(GP, featurOut, ContourRaster, CB_SplineType.Text);
                        break;
                    case "自然邻域插值法":
                        suc = DrawContours.Interpolate2RasterNN(GP, featurOut, ContourRaster);
                        break;
                    case "克里格插值法":
                        suc = DrawContours.Interpolate2RasterKriging(GP, featurOut, ContourRaster,
                            CB_semiVariogramProp.Text, CB_searchRadiusProp.Text);
                        break;
                    case "反距离权重插值法":
                        suc = DrawContours.Interpolate2RasterIDW(GP, featurOut, ContourRaster);
                        break;
                    case "趋势面插值法":
                        suc = DrawContours.TrendToRaster(GP, featurOut, ContourRaster);
                        break;
                }
                if (suc == false)
                    return false;
                this.progressBarControl1.PerformStep();
                GP = new Geoprocessor();
                string R2Contour = m_MakeContoursFolder + "\\Contour.shp";
                k = 1;
                while (File.Exists(R2Contour))
                {
                    R2Contour = m_MakeContoursFolder + "\\Contour" + k.ToString() + ".shp";
                    k++;
                }
                int countContour = Directory.GetFiles(m_MakeContoursFolder, "Contour*").Length;
                if (countContour > 0)
                {
                    R2Contour = m_MakeContoursFolder + "\\Contour" + countContour.ToString() + ".shp";
                }

                if (DrawContours.SplineRasterToContour(GP, ContourRaster, R2Contour, douElevation) == false)
                    return false;
                this.progressBarControl1.PerformStep();

                string EvEContour = m_MakeContoursFolder + "\\EvEContour.shp";
                k = 1;
                while (File.Exists(EvEContour))
                {
                    EvEContour = m_MakeContoursFolder + "\\EvEContour" + k.ToString() + ".shp";
                    k++;
                }
                int countEvEContour = Directory.GetFiles(m_MakeContoursFolder, "EvEContour*").Length;
                if (countEvEContour > 0)
                {
                    EvEContour = m_MakeContoursFolder + "\\EvEContour" + countEvEContour.ToString() + ".shp";
                }
                if (DrawContours.FeaturesTo3D(GP, R2Contour, EvEContour) == false)
                    return false;
                this.progressBarControl1.PerformStep();

                //获得等值线Shp文件所在的工作空间
                IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
                IWorkspace sourceworkspace = workspaceFactory.OpenFromFile(m_MakeContoursFolder, 0);
                //裁切
                IPolygon bianjie = GetPolygon();

                //导入等值线Shp文件到数据库中
                DrawSpecialCommon drawspecial = new DrawSpecialCommon();
                string nameOfsourceFeatureClass = EvEContour.Substring(EvEContour.LastIndexOf("\\") + 1);
                nameOfsourceFeatureClass = nameOfsourceFeatureClass.Substring(0, nameOfsourceFeatureClass.LastIndexOf("."));
                bool Import = false;
                List<ziduan> list = new List<ziduan>
                {
                    new ziduan("BID", ""),
                    new ziduan("mingcheng", sLayerAliasName),
                    new ziduan("mcid", "0"),
                    new ziduan("date", DateTime.Now.ToString()),
                    new ziduan("type", CB_InterpolationMethod.Text)
                };
                list.Add(new ziduan("BID", ""));
                list.Add(new ziduan("mingcheng", sLayerAliasName));
                list.Add(new ziduan("mcid", "0"));
                list.Add(new ziduan("date", DateTime.Now.ToString()));
                list.Add(new ziduan("type", CB_InterpolationMethod.Text));
                IFeatureLayer pFeatureLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, EditLayerName) as IFeatureLayer;
                string WhereClause = "mcid='" + "0" + "'";

                DataEditCommon.DeleteFeatureByWhereClause(pFeatureLayer, WhereClause);
                if (radioBtnKJ.Checked && bianjie != null)
                    Import = IntersectAll(DataEditCommon.GetFeatureClassByName(sourceworkspace, nameOfsourceFeatureClass), bianjie, list);
                else
                    Import = drawspecial.ShapeImportGDB(sourceworkspace, targetworkspace, nameOfsourceFeatureClass, nameOftargetFeatureClass, list);
                this.progressBarControl1.PerformStep();

                if (Import == false)
                {
                    MessageBox.Show(sLayerAliasName + "导入数据库失败!");
                    DataEditCommon.g_axTocControl.Update();
                    DataEditCommon.g_pAxMapControl.Refresh();
                    failInfo = sLayerAliasName;
                    return false;
                }

                //添加相应的渲染图
                IRasterLayer newRasterLayer = new RasterLayerClass();
                newRasterLayer.CreateFromFilePath(ContourRaster);
                newRasterLayer = IntersectRaster(newRasterLayer, bianjie);
                //newRasterLayer.CreateFromDataset(newRasterDs);
                newRasterLayer.Name = sRasterLayerAliasName;
                UsingRasterStretchColorRampRender(newRasterLayer);
                //groupLayer.Add(newRasterLayer as ILayer);
                int indexPosition = DataEditCommon.g_pAxMapControl.LayerCount;//GroupLayer序号

                //判断MapControl中是否存在该图层
                ILayer mLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, sRasterLayerAliasName);
                if (mLayer != null)
                {
                    DataEditCommon.g_pMyMapCtrl.Map.DeleteLayer(mLayer);
                    indexPosition--;
                }
                DataEditCommon.g_pAxMapControl.AddLayer(newRasterLayer as ILayer, indexPosition);//添加到最下面
                DataEditCommon.g_pAxMapControl.ActiveView.Extent = newRasterLayer.AreaOfInterest;
                DataEditCommon.g_axTocControl.Update();
                DataEditCommon.g_pAxMapControl.Refresh();
                this.progressBarControl1.PerformStep();

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }
Ejemplo n.º 37
0
        void IDataManager.CreateLyrFile(object inFeature, string outPath, string environment)
        {
            Geoprocessor GP = new Geoprocessor();
               //MessageBox.Show(dieukien);
               // Intialize the MakeFeatureLayer tool
               GP.SetEnvironmentValue("workspace", environment);
               MakeFeatureLayer makefeaturelayer = new MakeFeatureLayer();

               makefeaturelayer.in_features = inFeature;//this.Mem4DataManager.TempFullPath + inFeature;
               makefeaturelayer.out_layer = "layer1";//outPath;
               runTool(GP, makefeaturelayer, null);

               SaveToLayerFile saveLayer = new SaveToLayerFile();
               saveLayer.in_layer = inFeature;
               saveLayer.out_layer = @"C:\tn\temp\layer3.lyr";

               runTool(GP, saveLayer, null);
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Batches the copy feature class.
        /// </summary>
        /// <param name="workspacePath">The workspace path.</param>
        /// <param name="sourceDatasetName">Name of the source dataset.</param>
        /// <param name="Layerfilter">The layerfilter.</param>
        /// <param name="targetPath">The target path.</param>
        /// <param name="targetDatasetName">Name of the target dataset.</param>
        /// <returns></returns>
        public bool BatchCopyFeatureClass(string workspacePath, string sourceDatasetName,List<string> Layerfilter, string targetPath
                           ,string targetDatasetName)
        {
            try
            {
                Geoprocessor pGP = new Geoprocessor();
                List<string> featclsList = new List<string>();
                pGP.OverwriteOutput = true;
                pGP.SetEnvironmentValue("workspace", (object)workspacePath);

                IGpEnumList pFeatDatasetList = pGP.ListDatasets("", "");

                IGpEnumList pFeatClsList = null;

                string strDatasetName = pFeatDatasetList.Next();

                if (strDatasetName != "")
                {
                    while (strDatasetName !="")
                    {
                        pFeatClsList = pGP.ListFeatureClasses("", "", strDatasetName);

                        string strName = pFeatClsList.Next();
                        while (strName != "")
                        {
                            if (Layerfilter.Contains(strName.ToUpper()) && !featclsList.Contains(strName))
                            {
                                featclsList.Add(strName.ToUpper());
                            }
                            strName = pFeatClsList.Next();
                        }
                        strDatasetName = pFeatDatasetList.Next();
                    }
                }
                else
                {
                    pFeatClsList = pGP.ListFeatureClasses("", "", "");
                    string strName = pFeatClsList.Next();
                    while (strName != "")
                    {
                        if (Layerfilter.Contains(strName.ToUpper()) && !featclsList.Contains(strName))
                        {
                            featclsList.Add(strName.ToUpper());
                        }
                        strName = pFeatClsList.Next();
                    }
                }

                if (featclsList.Count == 0) return false;

                CopyFeatures pCopyFeature = new CopyFeatures();

                foreach (string str in featclsList)
                {
                    if (string.IsNullOrEmpty(strDatasetName))
                    {
                        pCopyFeature.in_features = string.Format("{0}\\{1}", workspacePath, str);
                    }
                    else
                    {
                        pCopyFeature.in_features = string.Format("{0}\\{1}\\{2}", workspacePath, strDatasetName, str);
                    }
                    pCopyFeature.out_feature_class = string.Format("{0}\\{1}\\{2}_Standard", targetPath, targetDatasetName, str);
                    pGP.Execute(pCopyFeature, null);
                    object obj = null;
                    //GT_CONST.LogAPI.CheckLog.AppendErrLogs(pGP.GetMessages(ref obj));
                }
            }
            catch (Exception exp)
            {
                Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString());

                return false;
            }
            return true;
        }
Ejemplo n.º 39
0
        /// <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;
            }
        }
Ejemplo n.º 40
0
        void IErase.EraseByLayerFileInsideSde(object in_feature, string in_layer_file_path, object erase_feature, string erase_layer_file_path, string out_feature)
        {
            //using (ComReleaser releaser = new ComReleaser())
            //{
                try
                {
                    Geoprocessor gp = new Geoprocessor();
                    IDataManager _dataManager = new DataManager(this._environment);
                    ESRI.ArcGIS.AnalysisTools.Erase clipTool = new ESRI.ArcGIS.AnalysisTools.Erase();
                    //releaser.ManageLifetime(gp);
                    //releaser.ManageLifetime(clipTool);
                    //IVariantArray param = new VarArrayClass();

                    string inlayer = string.Format("{0}.lyr", in_layer_file_path);
                    string cliplayer = string.Format("{0}.lyr", erase_layer_file_path);
                    //MessageBox.Show(string.Format("line 105 GExtractTool in={0}, erase={1}", inlayer, cliplayer));
                    _dataManager.SaveToLayerFile((ILayer)in_feature, inlayer);
                    _dataManager.SaveToLayerFile((ILayer)erase_feature, cliplayer);

                    //MessageBox.Show("line 112 GExtractTool, "+((IFeatureLayer)in_feature).FeatureClass.AliasName+", "+this._environment,this._workspace.PathName);
                    gp.SetEnvironmentValue("workspace", this._environment);
                    clipTool.in_features = inlayer;
                    clipTool.erase_features = cliplayer; //@"D:\duong.shp";// cliplayer;
                    clipTool.out_feature_class = out_feature;// string.Format("{0}{1}", "C:\\tn\\temp\\tempmdb.mdb\\", out_feature);//"C:\\tayninh\\temp\\tempmdb.mdb\\" + out_feature;

                    runTool(gp, clipTool, null);
                }
                catch (Exception err) { MessageBox.Show("loi erase: " + err.ToString()); }
            //}
        }
Ejemplo n.º 41
0
        void ICopyFeatures.CopyUseGeoprocessing(object copiedFeature, object toFeatureClass,string env)
        {
            Geoprocessor gp = new Geoprocessor();
               ESRI.ArcGIS.DataManagementTools.MakeFeatureLayer makeFeatureLayer = new MakeFeatureLayer();
              // makeFeatureLayer.in_features = @"C:\tn\temp\tempmdb.mdb\thua_sau50m_clip";
              // makeFeatureLayer.out_layer = "making_layer";
              // runTool(gp, makeFeatureLayer, null);

              // ESRI.ArcGIS.DataManagementTools.SelectLayerByAttribute select = new SelectLayerByAttribute();

              // select.in_layer_or_view = "making_layer";
              //select.selection_type = "NEW_SELECTION";
              //select.where_clause = "OBJECTID>0";
              //runTool(gp, select, null);

               gp.SetEnvironmentValue("workspace", env);
               ESRI.ArcGIS.DataManagementTools.CopyFeatures tool = new CopyFeatures();
               tool.in_features = @"C:\tn\temp\tempmdb.mdb\thua_sau50m_clip";
               string o=string.Format("{0}/{1}",env,"sde.SDE.thua_giadat_2012");
               MessageBox.Show(string.Format("line 483 DataManager {0}", o));
               tool.out_feature_class = o;
               //tool.config_keyword = "WKB_GEOMETRY";
               runTool(gp, tool, null);
        }
Ejemplo n.º 42
0
        string IDataManager.TnCreateFeatureLayer(string inFeature, string outLayer, string environment, string dieukien)
        {
            Geoprocessor GP = new Geoprocessor();
              //MessageBox.Show(dieukien);
              // Intialize the MakeFeatureLayer tool
              GP.SetEnvironmentValue("workspace", environment);
              MakeFeatureLayer makefeaturelayer = new MakeFeatureLayer();

              makefeaturelayer.in_features = inFeature;
              makefeaturelayer.out_layer = outLayer;
              runTool(GP, makefeaturelayer, null);

              SelectLayerByAttribute SelectByAttribute = new SelectLayerByAttribute();
              GP.ResetEnvironments();

              SelectByAttribute.in_layer_or_view = outLayer;
              SelectByAttribute.selection_type = "NEW_SELECTION";
              SelectByAttribute.where_clause = dieukien;
              runTool(GP, SelectByAttribute, null);

              CopyFeatures copyFeatures = new CopyFeatures();

              copyFeatures.in_features = outLayer;

              copyFeatures.out_feature_class = string.Format("{0}", outLayer);//_tempPath.TempFullPath,outLayer);//copiedFeature

              // Set the output Coordinate System environment
              //GP.SetEnvironmentValue("outputCoordinateSystem",
              //@"C:\Program Files\ArcGIS\Coordinate Systems\Projected Coordinate Systems\UTM\Nad 1983\NAD 1983 UTM Zone 21N.prj");

              runTool(GP, copyFeatures, null);
              return string.Format("{0}{1}",_tempPath.TempFullPath,outLayer);
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Batches the copy feature class.
        /// </summary>
        /// <param name="workspacePath">The workspace path.</param>
        /// <param name="sourceDatasetName">Name of the source dataset.</param>
        /// <param name="Layerfilter">The layerfilter.</param>
        /// <param name="targetPath">The target path.</param>
        /// <param name="targetDatasetName">Name of the target dataset.</param>
        /// <returns></returns>
        public bool BatchCopyFeatureClass(string workspacePath, string sourceDatasetName, List <string> Layerfilter, string targetPath
                                          , string targetDatasetName)
        {
            try
            {
                Geoprocessor  pGP         = new Geoprocessor();
                List <string> featclsList = new List <string>();
                pGP.OverwriteOutput = true;
                pGP.SetEnvironmentValue("workspace", (object)workspacePath);

                IGpEnumList pFeatDatasetList = pGP.ListDatasets("", "");

                IGpEnumList pFeatClsList = null;

                string strDatasetName = pFeatDatasetList.Next();

                if (strDatasetName != "")
                {
                    while (strDatasetName != "")
                    {
                        pFeatClsList = pGP.ListFeatureClasses("", "", strDatasetName);

                        string strName = pFeatClsList.Next();
                        while (strName != "")
                        {
                            if (Layerfilter.Contains(strName.ToUpper()) && !featclsList.Contains(strName))
                            {
                                featclsList.Add(strName.ToUpper());
                            }
                            strName = pFeatClsList.Next();
                        }
                        strDatasetName = pFeatDatasetList.Next();
                    }
                }
                else
                {
                    pFeatClsList = pGP.ListFeatureClasses("", "", "");
                    string strName = pFeatClsList.Next();
                    while (strName != "")
                    {
                        if (Layerfilter.Contains(strName.ToUpper()) && !featclsList.Contains(strName))
                        {
                            featclsList.Add(strName.ToUpper());
                        }
                        strName = pFeatClsList.Next();
                    }
                }

                if (featclsList.Count == 0)
                {
                    return(false);
                }

                CopyFeatures pCopyFeature = new CopyFeatures();

                foreach (string str in featclsList)
                {
                    if (string.IsNullOrEmpty(strDatasetName))
                    {
                        pCopyFeature.in_features = string.Format("{0}\\{1}", workspacePath, str);
                    }
                    else
                    {
                        pCopyFeature.in_features = string.Format("{0}\\{1}\\{2}", workspacePath, strDatasetName, str);
                    }
                    pCopyFeature.out_feature_class = string.Format("{0}\\{1}\\{2}_Standard", targetPath, targetDatasetName, str);
                    pGP.Execute(pCopyFeature, null);
                    object obj = null;
                    //GT_CONST.LogAPI.CheckLog.AppendErrLogs(pGP.GetMessages(ref obj));
                }
            }
            catch (Exception exp)
            {
                Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString());

                return(false);
            }
            return(true);
        }
Ejemplo n.º 44
0
        //实现了从sde中导出数据到dwg
        public static void ExportLayertoDwg(IList <IFeatureLayer> pInPutLayerList, string outputfile, ref List <IFeatureLayer> successedList, ref List <IFeatureLayer> failedList)
        {
            try
            {
                //string connectionfile = ConfigurationManager.AppSettings["ConnectionSDE"];//读取配置文件中sde的位置,如Connection to sde.sde
                string connectionfile   = "";
                string _RemoteLinkDBStr = System.Windows.Forms.Application.StartupPath + "\\" + connectionfile;
                string workPath         = string.Empty; //数据库连接路经
                string layerfullname    = string.Empty; //数据源
                for (int i = 0; i < pInPutLayerList.Count; i++)
                {
                    IFeatureLayer layer   = pInPutLayerList[i];
                    IDataset      dataset = layer.FeatureClass as IDataset;
                    if (dataset.Workspace.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace)
                    {
                        if (i == 0)
                        {
                            workPath      = _RemoteLinkDBStr;
                            layerfullname = System.IO.Path.Combine(_RemoteLinkDBStr, dataset.Name);
                        }
                        else
                        {
                            layerfullname += string.Format(";" + dataset.Name);
                        }
                    }
                    else
                    {
                        if (workPath == string.Empty)
                        {
                            workPath = dataset.Workspace.PathName;//未设置本地...
                        }
                    }
                }
                Geoprocessor GP = new Geoprocessor();
                GP.OverwriteOutput = true;//覆盖同名
                GP.SetEnvironmentValue("workspace", workPath);
                //获取数据源全路径
                ExportCAD exportcad = new ExportCAD();
                exportcad.in_features = layerfullname;
                exportcad.Output_Type = "DWG_R2010";
                exportcad.Output_File = outputfile;

                IGeoProcessorResult results = (IGeoProcessorResult)GP.Execute(exportcad, null);

                string msg = "";
                if (GP.MessageCount > 0)
                {
                    for (int j = 0; j < GP.MessageCount; j++)
                    {
                        msg += GP.GetMessage(j) + "\n";
                    }
                }
                if (msg.Contains("Successed") || msg.Contains("成功"))
                {
                    string message = msg;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }