Esempio n. 1
0
        /// <summary>
        /// 创建GDB
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="gdbname"></param>
        /// <returns></returns>
        public static string CreateGDB(string folder, string gdbname)
        {
            if (string.IsNullOrWhiteSpace(folder) || string.IsNullOrWhiteSpace(gdbname))
            {
                throw new Exception("路径不能为空");
            }
            if (System.Text.RegularExpressions.Regex.IsMatch(gdbname, "[/\\, ]"))
            {
                throw new Exception("路径不能含有特殊字符");
            }
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            IWorkspaceFactory2 wsFctry = new FileGDBWorkspaceFactoryClass();

            if (!gdbname.ToLower().EndsWith(".gdb"))
            {
                gdbname += ".gdb";
            }
            IWorkspaceName wsName  = wsFctry.Create(folder, gdbname, null, 0);
            string         gdbPath = wsName == null ? "" : wsName.PathName;

            Marshal.ReleaseComObject(wsName);
            Marshal.ReleaseComObject(wsFctry);
            return(gdbPath);
        }
        // Create the file geodatabase.
        public static void CreateFileGeodatabase()
        {
            string strFgdPath = @"C:\temp\";
            //string strFgdName = @"AddressCrossCheck";
            string strFgdName = fileGeodatabaseName;

            IWorkspaceName workspaceName = null;
            // Instantiate a file geodatabase workspace factory and create a new file geodatabase.
            // The Create method returns a workspace name object.
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();

            Console.WriteLine("Creating File Geodatabase...");

            // check if file geodatabase exists, before creating it
            if (!(workspaceFactory.IsWorkspace(strFgdPath + strFgdName + ".gdb")))
            {
                workspaceName = workspaceFactory.Create(strFgdPath, strFgdName, null, 0);
            }
            else
            {
                IFileNames arcFileNames = new FileNames();
                arcFileNames.Add(strFgdPath + strFgdName + ".gdb");
                workspaceName = workspaceFactory.GetWorkspaceName(strFgdPath, arcFileNames);
            }

            // Cast the workspace name object to the IName interface and open the workspace.
            var name = (IName)workspaceName;

            workspaceFGDB = (IWorkspace)name.Open();

            // Load the data.
            ImportDataToFGDB();
        }
Esempio n. 3
0
        public bool createGDBFile(string gdbfolderpath, string filename)
        {
            // IWorkspace workspace = null;
            IWorkspaceName workspaceName = null;

            // IName name = null;
            try
            {
                IWorkspaceFactory wsf = new FileGDBWorkspaceFactoryClass();
                workspaceName = wsf.Create(gdbfolderpath, filename, null, 0);
                // name = workspaceName as IName;

                if (workspaceName != null)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception eg)
            {
                return(false);
            }
        }
        // create a file geodatabase in user-specified location
        #region "Create FileGeodatabase"
        public static IWorkspace CreateFileGdbWorkspace(string strFgdPath, string strFgdName)
        {
            IWorkspaceName workspaceName = null;
            // Instantiate a file geodatabase workspace factory and create a new file geodatabase.
            // The Create method returns a workspace name object.
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass() as IWorkspaceFactory;

            // check if file geodatabase exists, before creating it
            if (!(workspaceFactory.IsWorkspace(strFgdPath + strFgdName)))
            {
                workspaceName = workspaceFactory.Create(strFgdPath, strFgdName, null, 0);
            }
            else
            {
                IFileNames arcFileNames = new FileNames();
                arcFileNames.Add(strFgdPath + strFgdName);
                workspaceName = workspaceFactory.GetWorkspaceName(strFgdPath, arcFileNames);
            }

            // Cast the workspace name object to the IName interface and open the workspace.
            IName      name      = (IName)workspaceName;
            IWorkspace workspace = (IWorkspace)name.Open();

            return(workspace);
        }
Esempio n. 5
0
 private void btnImpSymbol_Click(object sender, EventArgs e)
 {
     try
     {
         SaveFileDialog fbd = new SaveFileDialog();
         fbd.Title            = "Save file";
         fbd.InitialDirectory = System.IO.Path.GetDirectoryName(XMLPath);
         if (fbd.ShowDialog() == DialogResult.OK)
         {
             if (System.IO.Directory.Exists(fbd.FileName + ".shp") == true)
             {
                 MessageBox.Show("shp已存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                 return;
             }
             IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
             IWorkspaceName    workspaceName    = workspaceFactory.Create(System.IO.Path.GetDirectoryName(fbd.FileName), System.IO.Path.GetFileName(fbd.FileName), null, 0);
             gdbPath        = fbd.FileName + ".gdb";
             textBoxX2.Text = fbd.FileName + ".gdb";
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
         return;
     }
 }
Esempio n. 6
0
        /// <summary>
        ///     Creates the scratch workspace.
        /// </summary>
        /// <param name="scratchConnectionFile">The scratch connection file.</param>
        /// <param name="fallbackScratchName">Name of the fallback scratch.</param>
        /// <returns>
        ///     Returns a <see cref="IWorkspace" /> representing the temporary workspace that is either local or in-memory.
        /// </returns>
        protected IWorkspace CreateScratchWorkspace(string scratchConnectionFile, string fallbackScratchName)
        {
            if (string.IsNullOrEmpty(scratchConnectionFile))
            {
                IScratchWorkspaceFactory2 factory = new ScratchWorkspaceFactoryClass();
                return(factory.DefaultScratchWorkspace);
            }

            if (!scratchConnectionFile.EndsWith(".gdb", StringComparison.InvariantCultureIgnoreCase))
            {
                scratchConnectionFile = Path.Combine(scratchConnectionFile, fallbackScratchName);
            }

            Log.Info("");
            Log.Info("Connecting to the geodatabase specified by the {0} file.", Path.GetFileName(scratchConnectionFile));

            var fgdb = new FileGDBWorkspaceFactoryClass();

            if (!fgdb.IsWorkspace(scratchConnectionFile) && Directory.Exists(scratchConnectionFile))
            {
                Directory.Delete(scratchConnectionFile, true);
            }

            if (!Directory.Exists(scratchConnectionFile))
            {
                var name = fgdb.Create(Path.GetDirectoryName(scratchConnectionFile), Path.GetFileName(scratchConnectionFile), null, 0);
                return(((IName)name).Open() as IWorkspace);
            }

            var workspace = fgdb.OpenFromFile(scratchConnectionFile, 0);

            return(workspace);
        }
Esempio n. 7
0
        public IWorkspace IWorkspaceFactory_Create_Example_Access(string string_5)
        {
            IWorkspaceFactory factory = new FileGDBWorkspaceFactoryClass();
            IName             name2   = (IName)factory.Create(string_5, "MyNewFileGDB.gdb", null, 0);

            return((IWorkspace)name2.Open());
        }
Esempio n. 8
0
        private void btnOpenXML_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter = "XML文件(*.xml)|*.xml;|All files (*.*)|*.*";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                XMLPath        = dlg.FileName;
                textBoxX1.Text = XMLPath;
                //textBoxX3.Text = System.IO.Path.GetFileNameWithoutExtension(XMLPath);     //文件名
                textBoxX3.Text = "zhengti";
                try
                {
                    IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
                    IWorkspace        pWorkspace       = workspaceFactory.OpenFromFile(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(XMLPath), textBoxX3.Text + ".gdb"), 0);
                    textBoxX2.Text = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(XMLPath), textBoxX3.Text + ".gdb");
                    gdbPath        = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(XMLPath), textBoxX3.Text + ".gdb");
                }
                catch (Exception ex)
                {
                    // MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    if (System.IO.Directory.Exists(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(XMLPath), textBoxX3.Text + ".gdb")) == true)
                    {
                        MessageBox.Show("GDB同名文件夹已存在,请指定GDB", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                    IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
                    IWorkspaceName    workspaceName    = workspaceFactory.Create(System.IO.Path.GetDirectoryName(XMLPath), textBoxX3.Text, null, 0);
                    gdbPath        = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(XMLPath), textBoxX3.Text + ".gdb");
                    textBoxX2.Text = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(XMLPath), textBoxX3.Text + ".gdb");
                    return;
                }
            }
        }
        //
        // CONSTRUCTOR
        //
        public FileGeodatabaseValidator() : base() {
            string tempPath = Path.GetTempPath();
            string name = Guid.NewGuid().ToString("N").ToUpper();

            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
            IWorkspaceName workspaceName = workspaceFactory.Create(tempPath, name, null, 0);
            IWorkspace workspace = (IWorkspace)((IName)workspaceName).Open();
            this.SetWorkspace(workspace);
        }
Esempio n. 10
0
        //
        // CONSTRUCTOR
        //
        public FileGeodatabaseValidator() : base()
        {
            string tempPath = Path.GetTempPath();
            string name     = Guid.NewGuid().ToString("N").ToUpper();

            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
            IWorkspaceName    workspaceName    = workspaceFactory.Create(tempPath, name, null, 0);
            IWorkspace        workspace        = (IWorkspace)((IName)workspaceName).Open();

            this.SetWorkspace(workspace);
        }
        public static IWorkspace CreateFileGdbWorkspace(string strSavePathBackSlash, string strName)
        {
            // Instantiate a file geodatabase workspace factory and create a new file geodatabase.
            // The Create method returns a workspace name object.
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
            IWorkspaceName    workspaceName    = workspaceFactory.Create(strSavePathBackSlash, strName, null, 0);


            // Cast the workspace name object to the IName interface and open the workspace.
            IName      name      = (IName)workspaceName;
            IWorkspace workspace = (IWorkspace)name.Open();

            return(workspace);
        }
Esempio n. 12
0
        /// <summary>
        /// 创建PGDB数据源
        /// </summary>
        private IWorkspace CreateWorkspace()
        {
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
            int            nIndex        = m_strFilePathName.LastIndexOf("\\");
            string         sPath         = m_strFilePathName.Remove(nIndex);
            string         sName         = m_strFilePathName.Substring(nIndex + 1);
            IWorkspaceName workspaceName = workspaceFactory.Create(sPath,
                                                                   sName, null, 0);

            // Cast the workspace name object to the IName interface and open the workspace.
            IName      name      = (IName)workspaceName;
            IWorkspace workspace = (IWorkspace)name.Open();

            return(workspace);
        }
        private void CreateWorkspace()
        {
            if (FeatureWorkspace == null)
            {
                Config config              = Config.Instance;
                string location            = config.CycloramaVectorLayerLocationDefault ? ArcUtils.FileDir : config.CycloramaVectorLayerLocation;
                string defaultRecordingSrs = config.DefaultRecordingSrs;
                int    factoryCode;

                if (!Directory.Exists(location))
                {
                    Directory.CreateDirectory(location);
                }

                if ((string.IsNullOrEmpty(defaultRecordingSrs)) || (!int.TryParse(defaultRecordingSrs, out factoryCode)))
                {
                    ISpatialReference spatialReference = ArcUtils.SpatialReference;
                    factoryCode = spatialReference.FactoryCode;
                }

                IWorkspaceFactory workspaceFactory  = new FileGDBWorkspaceFactoryClass();
                string            name              = Path.Combine(location, string.Concat(Name, factoryCode));
                string            workSpaceFileName = string.Format("{0}.gdb", name);

                if (workspaceFactory.IsWorkspace(workSpaceFileName))
                {
                    IWorkspace workspace = workspaceFactory.OpenFromFile(workSpaceFileName, 0);
                    _featureWorkspace = workspace as IFeatureWorkspace;
                }
                else
                {
                    IWorkspaceName workspaceName = workspaceFactory.Create(string.Empty, name, null, 0);
                    var            nameObject    = workspaceName as IName;

                    if (nameObject != null)
                    {
                        var workspace = nameObject.Open() as IWorkspace;

                        if (workspace != null)
                        {
                            _featureWorkspace = workspace as IFeatureWorkspace;
                        }
                    }
                }
            }
        }
Esempio n. 14
0
        /*
         * A utility class to create a File Geodatabase Workspace
         */
        public static IWorkspace createFileGeodatabaseWorkspace(ref log4net.ILog log, string workspaceDirectory, string workspaceFolderName)
        {
            log.Debug("Starting the process to create a new local File Geodatabase workspace.");

            // Instantiate a file geodatabase workspace factory and create a new file geodatabase.
            // The Create method returns a workspace name object.
            log.Debug("Initializing a new workspace factory to establish the FGB.");
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
            IWorkspaceName    workspaceName    = null;

            // verify the workspace does not already exist
            log.Debug("Determining if the workspace apready exists or not.");
            if (System.IO.Directory.Exists(workspaceDirectory + "\\" + workspaceFolderName))
            {
                // file geodatabase workspace already exist, throw warning
                log.Warn("File Geodatabase workspace already exists.");
                throw new System.Exception(Properties.Resources.fgdb_GeodatabaseUtilities_createFileGeodatabaseWorkspace_exists);
            }
            else
            {
                // workspace doens't exist, good
                log.Debug("File Geodatabase does not exist.");

                // verify the directory exists
                log.Debug("Checking to see if the workspace directory exists or not (parent of the FGD).");
                if (!System.IO.Directory.Exists(workspaceDirectory))
                {
                    // workspace directory doens't exist, create the directory
                    log.Debug("Workspace folder/parent doesn't exist, creating the directory.");
                    System.IO.Directory.CreateDirectory(workspaceDirectory);
                }

                // create the workspace
                log.Debug("Creating the File Geodatabase workspace.");
                workspaceName = workspaceFactory.Create(workspaceDirectory, workspaceFolderName, null, 0);

                // Cast the workspace name object to the IName interface and open the workspace.
                log.Debug("Retreiving the workspace name.");
                IName name = (IName)workspaceName;

                // return the workspace
                log.Debug("Opening the workspace and returning it to the requestor.");
                return((IWorkspace)name.Open());
            }
        }
        /*
         * A utility class to create a File Geodatabase Workspace
         */
        public static IWorkspace createFileGeodatabaseWorkspace(ref log4net.ILog log, string workspaceDirectory, string workspaceFolderName)
        {
            log.Debug("Starting the process to create a new local File Geodatabase workspace.");

            // Instantiate a file geodatabase workspace factory and create a new file geodatabase.
            // The Create method returns a workspace name object.
            log.Debug("Initializing a new workspace factory to establish the FGB.");
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
            IWorkspaceName workspaceName = null;

            // verify the workspace does not already exist
            log.Debug("Determining if the workspace apready exists or not.");
            if (System.IO.Directory.Exists(workspaceDirectory + "\\" + workspaceFolderName))
            {
                // file geodatabase workspace already exist, throw warning
                log.Warn("File Geodatabase workspace already exists.");
                throw new System.Exception(Properties.Resources.fgdb_GeodatabaseUtilities_createFileGeodatabaseWorkspace_exists);
            }
            else
            {
                // workspace doens't exist, good
                log.Debug("File Geodatabase does not exist.");

                // verify the directory exists
                log.Debug("Checking to see if the workspace directory exists or not (parent of the FGD).");
                if (!System.IO.Directory.Exists(workspaceDirectory))
                {
                    // workspace directory doens't exist, create the directory
                    log.Debug("Workspace folder/parent doesn't exist, creating the directory.");
                    System.IO.Directory.CreateDirectory(workspaceDirectory);
                }

                // create the workspace
                log.Debug("Creating the File Geodatabase workspace.");
                workspaceName = workspaceFactory.Create(workspaceDirectory, workspaceFolderName, null, 0);

                // Cast the workspace name object to the IName interface and open the workspace.
                log.Debug("Retreiving the workspace name.");
                IName name = (IName)workspaceName;

                // return the workspace
                log.Debug("Opening the workspace and returning it to the requestor.");
                return (IWorkspace)name.Open();
            }
        }
Esempio n. 16
0
        /// <summary>
        /// 创建GDB
        /// </summary>
        /// <param name="gdbPath">gdb路径</param>
        /// <param name="cover">是否覆盖</param>
        /// <param name="open">是否打开并返回工作空间</param>
        /// <returns></returns>
        public static IWorkspace CreateGDB(string gdbPath, bool cover = false, bool open = true)
        {
            if (Directory.Exists(gdbPath) && cover)
            {
                Directory.Delete(gdbPath, true);
            }
            FileGDBWorkspaceFactoryClass fac = new FileGDBWorkspaceFactoryClass();

            if (!Directory.Exists(gdbPath))
            {
                fac.Create(Path.GetDirectoryName(gdbPath), Path.GetFileName(gdbPath), null, 0);
            }
            if (open)
            {
                return(fac.OpenFromFile(gdbPath, 0));
            }
            else
            {
                return(null);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// 构造函数

        /// </summary>
        /// <param name="MTpath">保存的连接设置</param>
        /// <param name="DBType">目标的类型(PDB、SDE、GDB)</param>
        /// <param name="pDesProperty">目标的连接设置</param>
        public GOFuzingSpatialTables(string MTpath, string DBType, IPropertySet pDesProperty)
        {
            this._DesDBType   = DBType;
            this._PropertySet = pDesProperty;
            IWorkspaceFactory pWorkspaceFactory = null;

            //if (DBType == "PDB")
            //{
            //    //创建PDB工作空间
            //    pWorkspaceFactory = new AccessWorkspaceFactoryClass();
            //}
            //else if (DBType == "GDB")
            //{
            pWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
            //}

            FileInfo finfo        = new FileInfo(MTpath);
            string   outputDBPath = finfo.DirectoryName;
            string   outputDBName = finfo.Name;

            if (Directory.Exists(MTpath))
            {
                SysCommon.Error.frmInformation frmInfo = new SysCommon.Error.frmInformation("是", "否", "存在同名的工作库实例,是否进行替代?");
                if (frmInfo.ShowDialog() == DialogResult.OK)
                {
                    Directory.Delete(MTpath, true);
                }
                else
                {
                    return;
                }
            }

            //outputDBName = outputDBName.Substring(0, outputDBName.Length - 4);
            IWorkspaceName pWorkspaceName = pWorkspaceFactory.Create(outputDBPath, outputDBName, null, 0);

            ESRI.ArcGIS.esriSystem.IName pName = (ESRI.ArcGIS.esriSystem.IName)pWorkspaceName;
            this._Workspace         = (IWorkspace)pName.Open();
            this._TempleteWorkspace = OpenTempleteWorkSpace();
        }
        private string CreateFileGDB()
        {
            string filePath = System.Environment.CurrentDirectory + @"\temp\";
            string fileName = "temp";
            string fullPath = filePath + fileName + ".gdb";

            while (Directory.Exists(fullPath))
            {
                fileName = fileName + "1";
                fullPath = filePath + fileName + ".gdb";
            }
            if (!Directory.Exists(filePath))
            {
                filePath = System.Environment.CurrentDirectory + @"\temp\";
                DirectoryInfo di = new DirectoryInfo(filePath);
                di.Create();
            }
            IWorkspaceFactory2 wsFctry = new FileGDBWorkspaceFactoryClass();

            wsFctry.Create(System.IO.Path.GetDirectoryName(filePath), fileName, null, 0);
            wsFctry = null;
            return(fullPath);
        }
Esempio n. 19
0
        public static IFeatureClass CreateMemoryFeatureClass(List <IField> dicExportData, ISpatialReference spatialReference, esriGeometryType geometryType, out IWorkspace memoryWS, string name = "Temp", bool isCad = false)
        {
            try
            {
                // 创建内存工作空间
                IWorkspaceFactory pWSF    = new FileGDBWorkspaceFactoryClass();
                IWorkspaceName    pWSName = pWSF.Create(@"D:\FTP\TestData\test.gdb", name, null, 0);
                IName             pName   = (IName)pWSName;
                memoryWS = (IWorkspace)pName.Open();

                IField      field      = new FieldClass();
                IFields     fields     = new FieldsClass();
                IFieldsEdit fieldsEdit = fields as IFieldsEdit;
                IFieldEdit  fieldEdit  = field as IFieldEdit;

                fieldEdit.Name_2       = "OBJECTID";
                fieldEdit.Type_2       = esriFieldType.esriFieldTypeOID;
                fieldEdit.IsNullable_2 = false;
                fieldEdit.Required_2   = false;
                fieldsEdit.AddField(field);

                field     = new FieldClass();
                fieldEdit = field as IFieldEdit;
                IGeometryDef     geoDef     = new GeometryDefClass();
                IGeometryDefEdit geoDefEdit = (IGeometryDefEdit)geoDef;
                geoDefEdit.AvgNumPoints_2     = 5;
                geoDefEdit.GeometryType_2     = geometryType;
                geoDefEdit.GridCount_2        = 1;
                geoDefEdit.HasM_2             = false;
                geoDefEdit.HasZ_2             = false;
                geoDefEdit.SpatialReference_2 = spatialReference;


                //Console.WriteLine();
                fieldEdit.Name_2        = "SHAPE";
                fieldEdit.Type_2        = esriFieldType.esriFieldTypeGeometry;
                fieldEdit.GeometryDef_2 = geoDef;
                fieldEdit.IsNullable_2  = true;
                fieldEdit.Required_2    = true;
                fieldsEdit.AddField(field);

                foreach (var item in dicExportData)
                {
                    if (item.Type == esriFieldType.esriFieldTypeOID || item.Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        continue;
                    }
                    fieldsEdit.AddField(item);
                }

                //创建要素类
                IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)memoryWS;
                IFeatureClass     featureClass     = featureWorkspace.CreateFeatureClass(
                    name, fields, null, null, esriFeatureType.esriFTSimple, "SHAPE", "");

                return(featureClass);
            }
            catch (Exception e)
            {
                memoryWS = null;
                return(null);
            }
        }
Esempio n. 20
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();
        }
Esempio n. 21
0
        private IWorkspace GetWksBySetting()
        {
            if (this.cboDataType.Tag == null)
            {
                return(null);
            }
            string strType = this.cboDataType.Tag.ToString();

            IWorkspace pTempWks = null;
            Exception  err      = null;

            errorServer.Clear();
            errorService.Clear();
            errorUser.Clear();
            errorPassWord.Clear();
            errorVersion.Clear();
            errorDataBase.Clear();
            try
            {
                if (strType == "ARCSDE")
                {
                    if (txtServer.Text == "")
                    {
                        errorServer.SetError(btnNew, "必填!");
                    }
                    if (txtService.Text == "")
                    {
                        errorService.SetError(txtService, "必填!");
                    }
                    if (txtUser.Text == "")
                    {
                        errorUser.SetError(txtUser, "必填!");
                    }
                    if (txtPassWord.Text == "")
                    {
                        errorPassWord.SetError(txtPassWord, "必填!");
                    }
                    if (cboVersion.Text == "")
                    {
                        errorVersion.SetError(cboVersion, "必填!");
                    }
                    if (txtDataBase.Text == "")
                    {
                        errorDataBase.SetError(txtDataBase, "必填!");
                        return(pTempWks);
                    }
                    pTempWks = SetWorkspace(this.txtServer.Text, this.txtService.Text, this.txtDataBase.Text, this.txtUser.Text, this.txtPassWord.Text, this.cboVersion.Text, out err);
                }
                else if (strType == "FGDB")
                {
                    if (txtServer.Text == "")
                    {
                        errorServer.SetError(btnNew, "必填!");
                        return(pTempWks);
                    }
                    if (Directory.Exists(this.txtServer.Text))
                    {
                        pTempWks = SetWorkspace(this.txtServer.Text, WksType.FGDB, out err);
                    }
                    else
                    {
                        if (_Addtag == "New")
                        {
                            string                       path = txtServer.Text.Substring(0, txtServer.Text.LastIndexOf("\\") + 1);
                            string                       name = txtServer.Text.Substring(txtServer.Text.LastIndexOf("\\") + 1);
                            IWorkspaceFactory            pworkspacefactory = new FileGDBWorkspaceFactoryClass();
                            IWorkspaceName               workspaceName     = pworkspacefactory.Create(path, name, null, 0);
                            ESRI.ArcGIS.esriSystem.IName pname             = (ESRI.ArcGIS.esriSystem.IName)workspaceName;

                            pTempWks = SetWorkspace(this.txtServer.Text, WksType.FGDB, out err);
                        }
                    }
                }
                else if (strType == "PGDB")
                {
                    if (txtServer.Text == "")
                    {
                        errorServer.SetError(btnNew, "必填!");
                        return(pTempWks);
                    }
                    if (File.Exists(this.txtServer.Text))
                    {
                        pTempWks = SetWorkspace(this.txtServer.Text, WksType.PGDB, out err);
                    }
                    else
                    {
                        if (_Addtag == "New")
                        {
                            string path = txtServer.Text.Substring(0, txtServer.Text.LastIndexOf("\\") + 1);
                            string name = txtServer.Text.Substring(txtServer.Text.LastIndexOf("\\") + 1);
                            if (!Directory.Exists(path))
                            {
                                return(null);
                            }
                            IWorkspaceFactory            pworkspacefactory = new AccessWorkspaceFactoryClass();
                            IWorkspaceName               workspaceName     = pworkspacefactory.Create(path, name, null, 0);
                            ESRI.ArcGIS.esriSystem.IName pname             = (ESRI.ArcGIS.esriSystem.IName)workspaceName;

                            pTempWks = SetWorkspace(this.txtServer.Text, WksType.PGDB, out err);
                        }
                    }
                }

                if (pTempWks == null && err != null)
                {
                    Fan.Common.Error.ErrorHandle.ShowFrmErrorHandle("提示", "无法连接数据库:" + this.txtServer.Text + err.Message);
                    return(null);
                }
            }
            catch (Exception ex)
            {
                Fan.Common.Error.ErrorHandle.ShowFrmErrorHandle("提示", "无法连接数据库:" + this.txtServer.Text + " " + ex.Message);
            }

            return(pTempWks);
        }
Esempio n. 22
0
        //根据XML节点获取连接信息
        public static object GetDBInfoByXMLNode(XmlElement dbElement, string strPath)
        {
            try
            {
                string strType     = dbElement.GetAttribute("类型");
                string strServer   = dbElement.GetAttribute("服务器");
                string strInstance = dbElement.GetAttribute("服务名");
                string strDB       = dbElement.GetAttribute("数据库");
                if (strPath != "")
                {
                    strDB = strPath + strDB;
                }
                string strUser     = dbElement.GetAttribute("用户");
                string strPassword = dbElement.GetAttribute("密码");
                string strVersion  = dbElement.GetAttribute("版本");

                IPropertySet pPropSet = null;
                switch (strType.Trim().ToLower())
                {
                case "pdb":
                    pPropSet = new PropertySetClass();
                    AccessWorkspaceFactory pAccessFact = new AccessWorkspaceFactoryClass();
                    if (!File.Exists(strDB))
                    {
                        FileInfo filePDB = new FileInfo(strDB);
                        pAccessFact.Create(filePDB.DirectoryName, filePDB.Name, null, 0);
                    }
                    pPropSet.SetProperty("DATABASE", strDB);
                    IWorkspace pdbWorkspace = pAccessFact.Open(pPropSet, 0);
                    pAccessFact = null;
                    return(pdbWorkspace);

                case "gdb":
                    pPropSet = new PropertySetClass();
                    FileGDBWorkspaceFactoryClass pFileGDBFact = new FileGDBWorkspaceFactoryClass();
                    if (!Directory.Exists(strDB))
                    {
                        DirectoryInfo dirGDB = new DirectoryInfo(strDB);
                        pFileGDBFact.Create(dirGDB.Parent.FullName, dirGDB.Name, null, 0);
                    }
                    pPropSet.SetProperty("DATABASE", strDB);
                    IWorkspace gdbWorkspace = pFileGDBFact.Open(pPropSet, 0);
                    pFileGDBFact = null;
                    return(gdbWorkspace);

                case "sde":
                    pPropSet = new PropertySetClass();
                    IWorkspaceFactory pSdeFact = new SdeWorkspaceFactoryClass();
                    pPropSet.SetProperty("SERVER", strServer);
                    pPropSet.SetProperty("INSTANCE", strInstance);
                    pPropSet.SetProperty("DATABASE", strDB);
                    pPropSet.SetProperty("USER", strUser);
                    pPropSet.SetProperty("PASSWORD", strPassword);
                    pPropSet.SetProperty("VERSION", strVersion);
                    IWorkspace sdeWorkspace = pSdeFact.Open(pPropSet, 0);
                    pSdeFact = null;
                    return(sdeWorkspace);

                case "access":
                    System.Data.Common.DbConnection dbCon = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strDB);
                    dbCon.Open();
                    return(dbCon);

                case "oracle":
                    string strOracle = "Data Source=" + strDB + ";Persist Security Info=True;User ID=" + strUser + ";Password="******";Unicode=True";
                    System.Data.Common.DbConnection dbConoracle = new OracleConnection(strOracle);
                    dbConoracle.Open();
                    return(dbConoracle);

                case "sql":
                    string strSql = "Data Source=" + strDB + ";Initial Catalog=" + strInstance + ";User ID=" + strUser + ";Password=" + strPassword;
                    System.Data.Common.DbConnection dbConsql = new SqlConnection(strSql);
                    dbConsql.Open();
                    return(dbConsql);

                default:
                    break;
                }

                return(null);
            }
            catch (Exception e)
            {
                //*******************************************************************
                //guozheng added
                if (ModuleData.v_SysLog != null)
                {
                    ModuleData.v_SysLog.Write(e, null, DateTime.Now);
                }
                else
                {
                    ModuleData.v_SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
                    ModuleData.v_SysLog.Write(e, null, DateTime.Now);
                }
                //********************************************************************
                return(null);
            }
        }
Esempio n. 23
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (listViewEx.CheckedItems.Count == 0)
            {
                SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "未选择对象,无法生成历史!");
                return;
            }

            Exception err = null;

            //获取现势库连接信息

            SysCommon.Gis.SysGisDataSet sourceSysGisDataSet = new SysCommon.Gis.SysGisDataSet();
            switch (comBoxType.Text)
            {
            case "SDE":
                sourceSysGisDataSet.SetWorkspace(txtServer.Text, txtInstance.Text, txtDB.Text, txtUser.Text, txtPassword.Text, txtVersion.Text, out err);
                break;

            case "GDB":
                sourceSysGisDataSet.SetWorkspace(txtDB.Text, SysCommon.enumWSType.GDB, out err);
                break;

            case "PDB":
                sourceSysGisDataSet.SetWorkspace(txtDB.Text, SysCommon.enumWSType.PDB, out err);
                break;

            default:
                break;
            }

            if (err != null || sourceSysGisDataSet.WorkSpace == null)
            {
                SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "未设置用户数据库连接或连接失败,请检查!");
                return;
            }

            //获取历史库连接信息

            IPropertySet pPropSet        = new PropertySetClass();
            IWorkspace   pTagetWorkspace = null;

            try
            {
                switch (comboBoxTypeHistory.Text)
                {
                case "PDB":
                    AccessWorkspaceFactory pAccessFact = new AccessWorkspaceFactoryClass();
                    if (!File.Exists(txtDBHistory.Text))
                    {
                        FileInfo filePDB = new FileInfo(txtDBHistory.Text);
                        pAccessFact.Create(filePDB.DirectoryName, filePDB.Name, null, 0);
                    }
                    pPropSet.SetProperty("DATABASE", txtDBHistory.Text);
                    pTagetWorkspace = pAccessFact.Open(pPropSet, 0);

                    break;

                case "GDB":
                    FileGDBWorkspaceFactoryClass pFileGDBFact = new FileGDBWorkspaceFactoryClass();
                    DirectoryInfo dirGDB = new DirectoryInfo(txtDBHistory.Text);
                    pFileGDBFact.Create(dirGDB.Parent.FullName, dirGDB.Name.Substring(0, dirGDB.Name.Length - 4), null, 0);
                    pPropSet.SetProperty("DATABASE", txtDBHistory.Text);
                    pTagetWorkspace = pFileGDBFact.Open(pPropSet, 0);

                    break;

                case "SDE":
                    IWorkspaceFactory pSdeFact = new SdeWorkspaceFactoryClass();
                    pPropSet.SetProperty("SERVER", txtServerHistory.Text);
                    pPropSet.SetProperty("INSTANCE", txtInstanceHistory.Text);
                    pPropSet.SetProperty("DATABASE", txtDBHistory.Text);
                    pPropSet.SetProperty("USER", txtUserHistory.Text);
                    pPropSet.SetProperty("PASSWORD", txtPasswordHistory.Text);
                    pPropSet.SetProperty("VERSION", txtVersionHistory.Text);
                    pTagetWorkspace = pSdeFact.Open(pPropSet, 0);

                    break;

                default:
                    break;
                }
            }
            catch (Exception er)
            {
                //*******************************************************************
                //guozheng added
                if (ModData.SysLog != null)
                {
                    ModData.SysLog.Write(er, null, DateTime.Now);
                }
                else
                {
                    ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
                    ModData.SysLog.Write(er, null, DateTime.Now);
                }
                //********************************************************************
            }

            if (pTagetWorkspace == null)
            {
                SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "未设置历史库连接或连接失败,请检查!");
                return;
            }

            this.Cursor = System.Windows.Forms.Cursors.AppStarting;

            List <string> lstData = new List <string>();

            try
            {
                //根据用户数据库结构创建历史库
                foreach (ListViewItem aItem in listViewEx.CheckedItems)
                {
                    if (aItem.Tag.ToString() == "FD")
                    {
                        IFeatureDataset tagetFeatureDataset = null;
                        IFeatureDataset pFeatureDataset     = sourceSysGisDataSet.GetFeatureDataset(aItem.Text, out err);
                        if (!(pTagetWorkspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTFeatureDataset, aItem.Text + "_GOH"))
                        {
                            tagetFeatureDataset = (pTagetWorkspace as IFeatureWorkspace).CreateFeatureDataset(aItem.Text + "_GOH", (pFeatureDataset as IGeoDataset).SpatialReference);
                        }
                        else
                        {
                            tagetFeatureDataset = (pTagetWorkspace as IFeatureWorkspace).OpenFeatureDataset(aItem.Text + "_GOH");
                        }

                        IEnumDataset pEnumDs = pFeatureDataset.Subsets;
                        pEnumDs.Reset();
                        IDataset pDs = pEnumDs.Next();
                        while (pDs != null)
                        {
                            IFeatureClass pFeatureClass = pDs as IFeatureClass;
                            if (pFeatureClass != null)
                            {
                                if (!(pTagetWorkspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTFeatureClass, pDs.Name + "_GOH"))
                                {
                                    CreateFeatCls(tagetFeatureDataset, pFeatureClass, pDs.Name + "_GOH", out err);
                                }
                                lstData.Add(pDs.Name);
                            }
                            pDs = pEnumDs.Next();
                        }
                    }
                    else if (aItem.Tag.ToString() == "FC")
                    {
                        IFeatureClass pFeatureClass = sourceSysGisDataSet.GetFeatureClass(aItem.Text, out err);
                        if (!(pTagetWorkspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTFeatureClass, aItem.Text + "_GOH"))
                        {
                            CreateFeatCls(pTagetWorkspace as IFeatureWorkspace, pFeatureClass, aItem.Text + "_GOH", out err);
                        }
                        lstData.Add(aItem.Text);
                    }
                }
            }
            catch (Exception er)
            {
                //*******************************************************************
                //guozheng added
                if (ModData.SysLog != null)
                {
                    ModData.SysLog.Write(er, null, DateTime.Now);
                }
                else
                {
                    ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
                    ModData.SysLog.Write(er, null, DateTime.Now);
                }
                //********************************************************************
                this.Cursor = System.Windows.Forms.Cursors.Default;
                SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "创建历史库结构失败!");
                return;
            }

            //遍历现势库数据FC进行数据移植
            Dictionary <string, string> dicFieldsPair = new Dictionary <string, string>();

            dicFieldsPair.Add("OBJECTID", "SourceOID");
            Dictionary <string, object> dicValue = new Dictionary <string, object>();

            dicValue.Add("FromDate", DateTime.Now.ToString("u"));
            dicValue.Add("ToDate", DateTime.MaxValue.ToString("u"));//.ToString("YYYY-MM-DD HH:MI:SS"));
            dicValue.Add("State", 0);
            (pTagetWorkspace as IWorkspaceEdit).StartEditing(false);
            bool res = true;

            progressBarXLay.Maximum = lstData.Count;
            progressBarXLay.Minimum = 0;
            progressBarXLay.Value   = 0;
            foreach (string aFeatClsName in lstData)
            {
                labelXMemo.Text = "正在进行图层" + aFeatClsName + "...";
                Application.DoEvents();
                int            cnt           = 0;
                int            allcnt        = 0;
                IFeatureCursor featureCursor = null;
                IFeatureClass  tagetFeatCls  = null;
                try
                {
                    featureCursor = sourceSysGisDataSet.GetFeatureCursor(aFeatClsName, "", null, "", out err, out cnt, out allcnt);
                    tagetFeatCls  = (pTagetWorkspace as IFeatureWorkspace).OpenFeatureClass(aFeatClsName + "_GOH");
                }
                catch (Exception ex)
                {
                    //*******************************************************************
                    //guozheng added
                    if (ModData.SysLog != null)
                    {
                        ModData.SysLog.Write(ex, null, DateTime.Now);
                    }
                    else
                    {
                        ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
                        ModData.SysLog.Write(ex, null, DateTime.Now);
                    }
                    //********************************************************************
                    SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", ex.Message);
                    return;
                }

                progressBarXFeat.Maximum = cnt;
                progressBarXFeat.Minimum = 0;
                progressBarXFeat.Value   = 0;
                ModDBOperator.NewFeatures(tagetFeatCls, featureCursor, dicFieldsPair, dicValue, true, false, progressBarXFeat, out err);
                Marshal.ReleaseComObject(featureCursor);
                progressBarXLay.Value++;

                labelXMemo.Text = "";
                Application.DoEvents();
                if (err != null)
                {
                    res = false;
                    break;
                }
            }
            (pTagetWorkspace as IWorkspaceEdit).StopEditing(res);

            this.Cursor = System.Windows.Forms.Cursors.Default;
            if (res)
            {
                if (m_DbProjectElement != null)
                {
                    try
                    {
                        XmlElement aElement = m_DbProjectElement.SelectSingleNode(".//内容//历史库//连接信息") as XmlElement;
                        SaveObjDB(aElement, listViewEx.Items[0].Text + "_GOH");
                    }
                    catch (Exception er)
                    {
                        //*******************************************************************
                        //guozheng added
                        if (ModData.SysLog != null)
                        {
                            ModData.SysLog.Write(er, null, DateTime.Now);
                        }
                        else
                        {
                            ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
                            ModData.SysLog.Write(er, null, DateTime.Now);
                        }
                        //********************************************************************
                        return;
                    }
                }
                SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "生成历史库成功!");
                this.Close();
            }
            else
            {
                SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "生成历史库失败!");
            }
        }
Esempio n. 24
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (txtProjectName.Text == "")
            {
                SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("信息提示", "请填写输出文件名称 !");
                return;
            }

            if (!Directory.Exists(txtSavePath.Text.Trim()))
            {
                SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("信息提示", "请选择保存路径 !");
                return;
            }

            if (listViewEx.CheckedItems.Count == 0)
            {
                SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("信息提示", "请选择数据版本信息 !");
                return;
            }

            string WorkSpacePath = txtSavePath.Text.Trim() + "\\" + txtProjectName.Text.Trim();

            IPropertySet pPropSet        = new PropertySetClass();
            IWorkspace   pTagetWorkspace = null;

            try
            {
                switch (comBoxType.Tag.ToString().Trim())
                {
                case "PDB":
                    AccessWorkspaceFactory pAccessFact = new AccessWorkspaceFactoryClass();
                    if (!File.Exists(WorkSpacePath + ".mdb"))
                    {
                        pAccessFact.Create(txtSavePath.Text, txtProjectName.Text, null, 0);
                    }
                    pPropSet.SetProperty("DATABASE", WorkSpacePath + ".mdb");
                    pTagetWorkspace = pAccessFact.Open(pPropSet, 0);
                    pAccessFact     = null;
                    pPropSet        = null;
                    break;

                case "GDB":
                    FileGDBWorkspaceFactoryClass pFileGDBFact = new FileGDBWorkspaceFactoryClass();
                    if (!Directory.Exists(WorkSpacePath + ".gdb"))
                    {
                        pFileGDBFact.Create(txtSavePath.Text, txtProjectName.Text, null, 0);
                    }
                    pPropSet.SetProperty("DATABASE", WorkSpacePath + ".gdb");
                    pTagetWorkspace = pFileGDBFact.Open(pPropSet, 0);
                    pFileGDBFact    = null;
                    pPropSet        = null;
                    break;

                default:
                    break;
                }
            }
            catch (Exception er)
            {
                //*******************************************************************
                //guozheng added
                if (ModData.SysLog != null)
                {
                    ModData.SysLog.Write(er, null, DateTime.Now);
                }
                else
                {
                    ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
                    ModData.SysLog.Write(er, null, DateTime.Now);
                }
                //********************************************************************
            }

            if (pTagetWorkspace == null)
            {
                SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "未设置输出库连接或连接失败,请检查!");
                return;
            }

            this.Cursor = System.Windows.Forms.Cursors.AppStarting;

            Exception            err        = null;
            bool                 res        = true;
            List <IFeatureLayer> lstFeatLay = new List <IFeatureLayer>();

            //根据历史图层创建输出数据图层结构
            for (int i = 0; i < Map.LayerCount; i++)
            {
                //cyf 20110706 add
                ILayer mLayer = Map.get_Layer(i);
                if (mLayer is IGroupLayer)
                {
                    ICompositeLayer pComLayer = mLayer as ICompositeLayer;
                    for (int j = 0; j < pComLayer.Count; j++)
                    {
                        IFeatureLayer featLay = pComLayer.get_Layer(j) as IFeatureLayer;
                        if (featLay == null)
                        {
                            continue;
                        }
                        if (!(featLay.FeatureClass as IDataset).Name.EndsWith("_GOH"))
                        {
                            continue;
                        }
                        lstFeatLay.Add(featLay);
                        if (!(pTagetWorkspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTFeatureClass, featLay.Name))//(featLay.FeatureClass as IDataset).Name
                        {
                            if (!CreateFeatCls(pTagetWorkspace as IFeatureWorkspace, featLay.FeatureClass, featLay.Name, out err))
                            {
                                res       = false;
                                featLay   = null;
                                pComLayer = null;
                                mLayer    = null;
                                break;
                            }
                        }
                    }
                }//end
                else
                {
                    IFeatureLayer featLay = Map.get_Layer(i) as IFeatureLayer;
                    if (featLay == null)
                    {
                        continue;
                    }
                    if (!(featLay.FeatureClass as IDataset).Name.EndsWith("_GOH"))
                    {
                        continue;
                    }
                    lstFeatLay.Add(featLay);
                    if (!(pTagetWorkspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTFeatureClass, featLay.Name))//(featLay.FeatureClass as IDataset).Name
                    {
                        if (!CreateFeatCls(pTagetWorkspace as IFeatureWorkspace, featLay.FeatureClass, featLay.Name, out err))
                        {
                            res     = false;
                            featLay = null;
                            mLayer  = null;
                            break;
                        }
                    }
                }
            }

            if (res == false)
            {
                this.Cursor = System.Windows.Forms.Cursors.Default;
                SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "创建输出库结构失败!");
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pTagetWorkspace);
                pTagetWorkspace = null;
                lstFeatLay.Clear();
                lstFeatLay = null;
                try
                {
                    Directory.Delete(txtSavePath.Text + "\\" + txtProjectName.Text + ".gdb", true);
                }
                catch (Exception err2)
                { }
                return;
            }

            StringBuilder sb = new StringBuilder();

            foreach (ListViewItem aItem in listViewEx.CheckedItems)
            {
                if (sb.Length != 0)
                {
                    sb.Append("or");
                }
                else
                {
                    sb.Append("(");
                }

                sb.Append("(FromDate<='" + aItem.Text + "' and ToDate>'" + aItem.Text + "')");
            }

            sb.Append(")");

            //遍历数据FC进行数据移植
            (pTagetWorkspace as IWorkspaceEdit).StartEditing(false);
            progressBarXLay.Maximum = lstFeatLay.Count;
            progressBarXLay.Minimum = 0;
            progressBarXLay.Value   = 0;
            foreach (IFeatureLayer aFeatLay in lstFeatLay)
            {
                labelXMemo.Text = aFeatLay.FeatureClass.AliasName + "...";
                Application.DoEvents();

                StringBuilder newSB = new StringBuilder();
                newSB.Append(sb.ToString());

                if (m_Sel)
                {
                    int fdIndex = aFeatLay.FeatureClass.Fields.FindField("SourceOID");
                    if (fdIndex == -1)
                    {
                        continue;
                    }
                    IFeatureLayerDefinition featLayDefTemp = aFeatLay as IFeatureLayerDefinition;
                    IEnumIDs      pEnumIDs = featLayDefTemp.DefinitionSelectionSet.IDs;
                    int           ID       = pEnumIDs.Next();
                    StringBuilder sbTemp   = new StringBuilder();
                    while (ID != -1)
                    {
                        IFeature pFeat = aFeatLay.FeatureClass.GetFeature(ID);
                        if (sbTemp.Length != 0)
                        {
                            sbTemp.Append(",");
                        }
                        sbTemp.Append(pFeat.get_Value(fdIndex).ToString());
                        ID = pEnumIDs.Next();
                    }
                    newSB.Append(" and SourceOID in (" + sbTemp.ToString() + ")");
                }

                IQueryFilter queryFilter = new QueryFilterClass();
                queryFilter.WhereClause = newSB.ToString();
                IFeatureCursor featureCursor = aFeatLay.FeatureClass.Search(queryFilter, false);
                progressBarXFeat.Maximum = aFeatLay.FeatureClass.FeatureCount(queryFilter);
                progressBarXFeat.Minimum = 0;
                progressBarXFeat.Value   = 0;
                try
                {
                    //cyf 20110706 modify:去掉用户名
                    string pFeaLayerName = aFeatLay.Name.Trim();
                    if (pFeaLayerName.Contains("."))
                    {
                        pFeaLayerName = pFeaLayerName.Substring(pFeaLayerName.IndexOf('.') + 1);
                    }
                    //end
                    IFeatureClass tagetFeatCls = (pTagetWorkspace as IFeatureWorkspace).OpenFeatureClass(pFeaLayerName);//(aFeatLay.FeatureClass as IDataset).Name
                    ModDBOperator.NewFeatures(tagetFeatCls, featureCursor, null, null, true, false, progressBarXFeat, out err);
                }
                catch (Exception ex)
                {
                    //*******************************************************************
                    //guozheng added
                    if (ModData.SysLog != null)
                    {
                        ModData.SysLog.Write(ex, null, DateTime.Now);
                    }
                    else
                    {
                        ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
                        ModData.SysLog.Write(ex, null, DateTime.Now);
                    }
                    //********************************************************************
                    SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "入库失败!");
                    return;
                }

                Marshal.ReleaseComObject(featureCursor);
                progressBarXLay.Value++;

                labelXMemo.Text = "";
                Application.DoEvents();
                if (err != null)
                {
                    res = false;
                    break;
                }
            }

            (pTagetWorkspace as IWorkspaceEdit).StopEditing(res);

            this.Cursor = System.Windows.Forms.Cursors.Default;
            if (res)
            {
                SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "提取成功!");
                this.Close();
            }
            else
            {
                SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "提取失败!");
            }
        }
Esempio n. 25
0
        /// <summary>
        /// 创建PGDB数据源
        /// </summary>
        private IWorkspace CreateWorkspace()
        {
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
            int nIndex = m_strFilePathName.LastIndexOf("\\");
            string sPath = m_strFilePathName.Remove(nIndex);
            string sName = m_strFilePathName.Substring(nIndex + 1) ;
            IWorkspaceName workspaceName = workspaceFactory.Create(sPath,
                sName, null, 0);

            // Cast the workspace name object to the IName interface and open the workspace.
            IName name = (IName)workspaceName;
            IWorkspace workspace = (IWorkspace)name.Open();
            return workspace;
        }