Exemplo n.º 1
0
        private IFeatureClass getShapeFile(string inDir, string infile)
        {
            System.IO.DirectoryInfo directoryInfo_check = new System.IO.DirectoryInfo(inDir);
            if (directoryInfo_check.Exists)
            {
                //We have a valid directory, proceed

                System.IO.FileInfo fileInfo_check = new System.IO.FileInfo(inDir + "\\" + infile + ".shp");
                if (fileInfo_check.Exists)
                {
                    //We have a valid shapefile, proceed

                    ESRI.ArcGIS.Geodatabase.IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass();
                    ESRI.ArcGIS.Geodatabase.IWorkspace        workspace        = workspaceFactory.OpenFromFile(inDir, 0);
                    ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspace; // Explict Cast
                    ESRI.ArcGIS.Geodatabase.IFeatureClass     featureClass     = featureWorkspace.OpenFeatureClass(infile);

                    return(featureClass);
                }
                else
                {
                    //Not valid shapefile
                    return(null);
                }
            }
            else
            {
                // Not valid directory
                return(null);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// 打开文件地理数据库
        /// </summary>
        /// <param name="?"></param>
        /// <returns></returns>
        public static ESRI.ArcGIS.Geodatabase.IWorkspace GetFGDBWorkspace(String _pGDBName)
        {
            IWorkspaceFactory pWsFac = new FileGDBWorkspaceFactoryClass();

            ESRI.ArcGIS.Geodatabase.IWorkspace pWs = pWsFac.OpenFromFile(_pGDBName, 0);
            return(pWs);
        }
Exemplo n.º 3
0
        public ESRI.ArcGIS.Geodatabase.IFeatureClass GetFeatureClassFromShapefileOnDisk(System.String string_ShapefileDirectory, System.String string_ShapefileName)
        {
            System.IO.DirectoryInfo directoryInfo_check = new System.IO.DirectoryInfo(string_ShapefileDirectory);
            if (directoryInfo_check.Exists)
            {
                //We have a valid directory, proceed

                System.IO.FileInfo fileInfo_check = new System.IO.FileInfo(string_ShapefileDirectory + "\\" + string_ShapefileName + ".shp");
                if (fileInfo_check.Exists)
                {
                    //We have a valid shapefile, proceed

                    ESRI.ArcGIS.Geodatabase.IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass();
                    ESRI.ArcGIS.Geodatabase.IWorkspace        workspace        = workspaceFactory.OpenFromFile(string_ShapefileDirectory, 0);
                    ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspace; // Explict Cast
                    ESRI.ArcGIS.Geodatabase.IFeatureClass     featureClass     = featureWorkspace.OpenFeatureClass(string_ShapefileName);

                    return(featureClass);
                }
                else
                {
                    //Not valid shapefile
                    return(null);
                }
            }
            else
            {
                // Not valid directory
                return(null);
            }
        }
        private Boolean CreateDataset(NameEvents templateInfo)
        {
            try
            {
                IGxDatabase pDatabase = (IGxDatabase)m_SelectedObject;

                m_pWS = pDatabase.Workspace;

                ESRI.ArcGIS.Schematic.ISchematicWorkspaceFactory pSWF = new SchematicWorkspaceFactory();
                ESRI.ArcGIS.Schematic.ISchematicWorkspace        pSW  = pSWF.Open(m_pWS);
                //check to see if this dataset name is already used
                m_pSDS = pSW.get_SchematicDatasetByName(templateInfo.DatasetName.ToString());
                if (m_pSDS != null)
                {
                    return(false);
                }

                m_pSDS = pSW.CreateSchematicDataset(templateInfo.DatasetName, "");
                return(true);
            }
            catch
            {
                //nothing
                return(false);
            }
        }
Exemplo n.º 5
0
        public BaseModel(ESRI.ArcGIS.Geodatabase.IWorkspace Workspace) : this()
        {
            _createEntityPersistence.Add(Type.FeatureClass, () => { return(new FeatureClassDAO(Workspace)); });
            _createEntityPersistence.Add(Type.GISTable, () => { return(new GISTableDAO(Workspace)); });
            _createEntityPersistence.Add(Type.Table, () => { return(new TableDAO(Workspace)); });

            _persistence = _createEntityPersistence[_FeatureClassConfig.TypeEntity]();
        }
Exemplo n.º 6
0
 public void Load(ESRI.ArcGIS.Geodatabase.IWorkspace Workspace, ESRI.ArcGIS.Geodatabase.IRow Row, BaseModel AEOModel, ModelProperty Property)
 {
     if (!String.IsNullOrEmpty(Row.get_Value(Row.Fields.FindField(Property.Attribute.FieldName)).ToString()))
     {
         Property.Property.SetValue(AEOModel,
                                    Convert.ChangeType(Row.get_Value(Row.Fields.FindField(Property.Attribute.FieldName)),
                                                       Property.Attribute.FieldType), null);
     }
 }
Exemplo n.º 7
0
 /// <summary>
 /// 把DataTable转为ITable ,tempPath 不含文件名的w文件夹路径
 /// </summary>
 /// <param name="mTable"></param>
 /// <returns></returns>
 private ITable DataTableToITable(DataTable mTable, string xFieldName, string yFieldName, string tempPath)
 {
     try
     {
         #region 新建表字段
         IField      pField     = null;
         IFields     fields     = new FieldsClass();
         IFieldsEdit fieldsEdit = (IFieldsEdit)fields;
         fieldsEdit.FieldCount_2 = 2;
         //添加X字段
         pField = new FieldClass();
         IFieldEdit fieldEdit = (IFieldEdit)pField;
         fieldEdit.Name_2      = "X";
         fieldEdit.AliasName_2 = "X";
         //设置字段类型
         fieldEdit.Type_2     = esriFieldType.esriFieldTypeDouble;
         fieldEdit.Editable_2 = true;
         fieldsEdit.set_Field(0, pField);
         //添加Y字段
         IField     pField1    = new FieldClass();
         IFieldEdit fieldEdit1 = (IFieldEdit)pField1;
         fieldEdit1.Name_2      = "Y";
         fieldEdit1.AliasName_2 = "Y";
         fieldEdit1.Type_2      = esriFieldType.esriFieldTypeDouble;
         fieldEdit1.Editable_2  = true;
         fieldsEdit.set_Field(1, pField1);
         #endregion
         ShapefileWorkspaceFactoryClass     class2     = new ShapefileWorkspaceFactoryClass();
         ESRI.ArcGIS.Geodatabase.IWorkspace pWorkspace = class2.OpenFromFile(tempPath, 0);
         IFeatureWorkspace pFWS = pWorkspace as IFeatureWorkspace;
         //删除已有的
         if (System.IO.File.Exists(tempPath + "点数据.dbf"))
         {
             System.IO.File.Delete(tempPath + "点数据.dbf");
         }
         //创建空表
         ITable pTable = pFWS.CreateTable("点数据", fieldsEdit, null, null, "");
         //遍历DataTable中数据,然后转换为ITable中的数据
         int xRowIndex = pTable.Fields.FindField("X");
         int yRowIndex = pTable.Fields.FindField("Y");
         for (int k = 0; k < mTable.Rows.Count; k++)
         {
             //ITable 的记录
             IRow    row   = pTable.CreateRow();
             DataRow pRrow = mTable.Rows[k];
             row.set_Value(xRowIndex, pRrow[xFieldName]);
             row.set_Value(yRowIndex, pRrow[yFieldName]);
             row.Store();
         }
         return(pTable);
     }
     catch
     {
         return(null);
     }
 }
        //开始编辑
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                if (pCurrentLyr == null)
                {
                    MessageBox.Show("请选择编辑图层!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                setEditToolEnable(true);
                //如果编辑已经开始,则直接退出
                if (pEngineEditor.EditState != esriEngineEditState.esriEngineStateNotEditing)
                {
                    return;
                }
                if (pCurrentLyr == null)
                {
                    return;
                }
                //获取当前编辑图层工作空间
                pDataSet                  = pCurrentLyr.FeatureClass as IDataset;
                pWs                       = pDataSet.Workspace;
                pEngineEditTask           = pEngineEditor.GetTaskByUniqueName("ControlToolsEditing_CreateNewFeatureTask");
                pEngineEditor.CurrentTask = pEngineEditTask; // 设置编辑任务
                pEngineEditor.EnableUndoRedo(true);          //是否可以进行撤销、恢复操作
                //设置编辑模式,如果是ArcSDE采用版本模式
                if (pWs.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace)
                {
                    IVersionedObject3 versionedObject = pDataSet as IVersionedObject3;
                    //注册版本
                    if (versionedObject != null && !versionedObject.IsRegisteredAsVersioned)
                    {
                        versionedObject.RegisterAsVersioned(true);
                    }
                    pEngineEditor.EditSessionMode = esriEngineEditSessionMode.esriEngineEditSessionModeVersioned;
                }
                //else
                //{
                //    pEngineEditor.EditSessionMode = esriEngineEditSessionMode.esriEngineEditSessionModeNonVersioned;
                //}
                //设置编辑任务
                pEngineEditor.StartEditing(pWs, pMap);
                isEditing = true;
                //SysLogHelper.WriteOperationLog("数据编辑", "开始编辑", "数据管理");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                PS.Plot.Common.LogHelper.WriteLog(typeof(Form_Editor), ex, "开始编辑");
            }
        }
Exemplo n.º 9
0
        private static ESRI.ArcGIS.Geodatabase.IFeatureWorkspace getWorkspace(string fPath)
        {
            fPath = fPath.Trim();

            string workspacePath = System.IO.Path.GetDirectoryName(fPath);
            string featureClass  = System.IO.Path.GetFileName(fPath);

            if ((new Regex(@"\.shp$")).IsMatch(fPath))
            {
                try
                {
                    return(shapeWsf.OpenFromFile(workspacePath, 0) as IFeatureWorkspace);
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                    throw new System.IO.FileNotFoundException("Shapefile workspace not found: " + workspacePath);
                }
            }
            else if ((new Regex(@"\\[^\\]*\.(gdb|GDB)\\[^\\]*$")).IsMatch(fPath))
            {
                try
                {
                    return(gdbWsf.OpenFromFile(workspacePath, 0) as IFeatureWorkspace);
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                    throw new System.IO.FileNotFoundException("Geodatabase workspace not found: " + workspacePath);
                }
            }
            else if ((new Regex(@"\\[^\\]*\.(gdb|GDB)\\[^\\]*\\[^\\]*$")).IsMatch(fPath))
            {
                string datasetName = System.IO.Path.GetFileName(workspacePath);
                workspacePath = System.IO.Path.GetDirectoryName(workspacePath);
                ESRI.ArcGIS.Geodatabase.IWorkspace ws = gdbWsf.OpenFromFile(workspacePath, 0);

                ESRI.ArcGIS.Geodatabase.IEnumDataset dss = ws.get_Datasets(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTFeatureDataset);
                ESRI.ArcGIS.Geodatabase.IDataset     ds;

                while ((ds = dss.Next()) != null)
                {
                    if (ds.Name == datasetName)
                    {
                        return(ds.Workspace as IFeatureWorkspace);
                    }
                }
                throw new System.IO.FileNotFoundException("feature dataset not found: " + System.IO.Path.Combine(workspacePath, datasetName));
            }
            else
            {
                throw new System.IO.FileNotFoundException("Invalid feature class path: " + fPath);
            }
        }
 void cleanUp()
 {
     //m_pWSF = null;
     m_pWS            = null;
     m_pSDT           = null;
     m_pSDS           = null;
     m_pSB            = null;
     m_pB             = null;
     m_SelectedObject = null;
     templateInfo     = null;
     m_pSDI           = null;
     formNames        = null;
     formReduce       = null;
     m_sfn            = "";
     blnCancel        = false;
     strLayers        = "";
     strNodeLayers    = "";
 }
        private Boolean CreateTemplate(NameEvents templateInfo)
        {
            //need to get everything first
            IGxDatabase pDatabase = null;
            ISchematicDiagramClassContainer pDiagramClassContainer = null;

            if (m_SelectedObject.Category == "Schematic Dataset")
            {
                pDatabase = (IGxDatabase)m_SelectedObject.Parent;
            }
            else              //on the database already
            {
                pDatabase = (IGxDatabase)m_SelectedObject;
            }
            m_pWS = pDatabase.Workspace;

            ESRI.ArcGIS.Schematic.ISchematicWorkspaceFactory pSWF = new SchematicWorkspaceFactory();
            ESRI.ArcGIS.Schematic.ISchematicWorkspace        pSW  = pSWF.Open(m_pWS);

            m_pSDS = pSW.get_SchematicDatasetByName(templateInfo.DatasetName);

            //check to see if the template name already exists
            pDiagramClassContainer = (ISchematicDiagramClassContainer)m_pSDS;
            m_pSDT = pDiagramClassContainer.GetSchematicDiagramClass(templateInfo.TemplateName.ToString());
            if (m_pSDT != null)
            {
                return(false);
            }

            //create the schematic template
            m_pSDT = m_pSDS.CreateSchematicDiagramClass(templateInfo.TemplateName);

            if ((templateInfo.AutoCreate == true) || (templateInfo.UseVertices == true))
            {
                m_pB  = (ESRI.ArcGIS.Schematic.ISchematicBuilder)m_pSDT;
                m_pSB = (ESRI.ArcGIS.Schematic.ISchematicStandardBuilder)m_pSDT.SchematicBuilder;
                m_pSB.InitializeLinksVertices  = templateInfo.UseVertices;
                m_pSB.AutoCreateElementClasses = templateInfo.AutoCreate;
            }
            m_pSDS.Save(ESRI.ArcGIS.esriSystem.esriArcGISVersion.esriArcGISVersion10, false);
            return(true);
        }
Exemplo n.º 12
0
        public IRasterDataset CreateRasterSurf(string sDir, string sName, string sFormat, IPoint pOrigin, int nCol, int nRow, double cellsizeX, double cellsizeY, rstPixelType ePixelType, ISpatialReference2 pSR, bool bPerm)
        {
            //IWorkspaceFactory rWksFac = new RasterWorkspaceFactory();

            //IWorkspace wks = rWksFac.OpenFromFile(sDir, 0);

            //IRasterWorkspace2 rWks = wks as IRasterWorkspace2;

            //int numbands = 1;

            //IRasterDataset pRDS;// = new RasterDatasetClass();
            //pRDS = rWks.CreateRasterDataset(sName, sFormat, pOrigin, nCol, nRow, cellsizeX, cellsizeY, numbands, ePixelType, pSR, bPerm);
            //return pRDS;

            IWorkspaceFactory pworkspaceFactory = new RasterWorkspaceFactory();

            ESRI.ArcGIS.Geodatabase.IWorkspaceName pworkspaceName = pworkspaceFactory.Create(null, "MyWorkspace", null, 0);
            ESRI.ArcGIS.esriSystem.IName           pname          = (IName)pworkspaceName;
            ESRI.ArcGIS.Geodatabase.IWorkspace     inmemWor       = (IWorkspace)pname.Open();
            IPoint            originpoint = pOrigin;
            IRasterWorkspace2 rasterws    = (IRasterWorkspace2)inmemWor;

            //用于计算的 float型的栅格数据
            IRasterDataset demdataset = rasterws.CreateRasterDataset("Dataset", "MEM", originpoint, nCol, nRow,
                                                                     (double)cellsizeX, (double)cellsizeY, 1, rstPixelType.PT_DOUBLE, null, true);

            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pname);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pworkspaceFactory);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pworkspaceName);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(inmemWor);
            }
            catch { }
            GC.Collect();
            return(demdataset);
        }
Exemplo n.º 13
0
        /// <summary>
        /// uninitialize the nps global instance
        /// </summary>
        public void UnInit()
        {
            m_IsInitialized = false;

            Util.SaveConfigSettings();
            UnwireEditEvents(m_Editor);

            m_DLLPath = null;
            m_Map = null;
            m_XMLConfig = null;
            m_XMLConfigFilePath = null;
            m_Workspace = null;
            m_DatabasePath = null;
            m_DLLPath = null;
            m_Editor = null;
            m_ProgramaticFeatureEdit = false;
            m_InitErrorMessage = null;

            m_LYR_HORIZON = m_LYR_ANIMALS = m_LYR_TRACKLOG
                = m_LYR_GPSPOINTLOG = m_LYR_RANDOMPOINTS
                = m_LYR_GENERATED_TRANSECTS = m_LYR_FLAT_AREAS
                = m_LYR_EXCLUDED_AREAS = m_LYR_SURVEY_BOUNDARY = null;
        }
Exemplo n.º 14
0
        /// <summary>
        /// 创建人员图层
        /// </summary>
        /// <param name="DataSetName"></param>
        /// <param name="AliaseName"></param>
        /// <param name="SpatialRef"></param>
        /// <param name="GeometryType"></param>
        /// <param name="PropertyFields"></param>
        /// <returns></returns>
        private void CreateDrawnLayer()
        {
            try
            {
                if (axMapControl1.LayerCount >= 2)
                {
                    axMapControl1.DeleteLayer(0);
                }
            }
            catch
            { }

            IWorkspaceFactory workspaceFactory = new InMemoryWorkspaceFactoryClass();

            ESRI.ArcGIS.Geodatabase.IWorkspaceName workspaceName = workspaceFactory.Create("", "MyWorkspace", null, 0);
            ESRI.ArcGIS.esriSystem.IName           name          = (IName)workspaceName;
            ESRI.ArcGIS.Geodatabase.IWorkspace     inmemWor      = (IWorkspace)name.Open();
            IField        oField        = new FieldClass();
            IFields       oFields       = new FieldsClass();
            IFieldsEdit   oFieldsEdit   = null;
            IFieldEdit    oFieldEdit    = null;
            IFeatureClass oFeatureClass = null;
            IFeatureLayer oFeatureLayer = null;

            try
            {
                oFieldsEdit = oFields as IFieldsEdit;
                oFieldEdit  = oField as IFieldEdit;

                //创建图元属性
                FieldClass feadName = new FieldClass();
                IFieldEdit edit     = feadName;
                edit.Name_2 = "Name";
                edit.Type_2 = esriFieldType.esriFieldTypeString;
                oFieldsEdit.AddField(feadName);

                FieldClass feadID = new FieldClass();
                IFieldEdit editID = feadID;
                editID.Name_2 = "ID";
                editID.Type_2 = esriFieldType.esriFieldTypeString;
                oFieldsEdit.AddField(editID);


                IGeometryDef     geometryDef     = new GeometryDefClass();
                IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
                //geometryDefEdit.AvgNumPoints_2 = 5;
                geometryDefEdit.GeometryType_2     = esriGeometryType.esriGeometryPolyline;
                geometryDefEdit.GridCount_2        = 1;
                geometryDefEdit.HasM_2             = false;
                geometryDefEdit.HasZ_2             = false;
                geometryDefEdit.SpatialReference_2 = axMapControl1.SpatialReference;
                oFieldEdit.Name_2        = "SHAPE";
                oFieldEdit.Type_2        = esriFieldType.esriFieldTypeGeometry;
                oFieldEdit.GeometryDef_2 = geometryDef;
                oFieldEdit.IsNullable_2  = true;
                oFieldEdit.Required_2    = true;
                oFieldsEdit.AddField(oField);
                oFeatureClass = (inmemWor as IFeatureWorkspace).CreateFeatureClass("DrawnDS", oFields, null, null, esriFeatureType.esriFTSimple, "SHAPE", "");
                (oFeatureClass as IDataset).BrowseName = "DrawnDS";
                oFeatureLayer              = new FeatureLayerClass();
                oFeatureLayer.Name         = "Drawn";
                oFeatureLayer.FeatureClass = oFeatureClass;
            }
            catch
            {
            }
            finally
            {
                try
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oField);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oFields);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oFieldsEdit);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oFieldEdit);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(name);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workspaceFactory);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workspaceName);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(inmemWor);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oFeatureClass);
                }
                catch { }

                GC.Collect();
            }

            DrawnLayer = oFeatureLayer;
            axMapControl1.Map.AddLayer(oFeatureLayer);
            UniqueValueRenderFlyr(oFeatureLayer);
            axMapControl1.Refresh();
        }
Exemplo n.º 15
0
        public IRaster TINToDEM(ITin pTin)
        {
            IPoint pOrigin = pTin.Extent.LowerLeft;


            IWorkspaceFactory pworkspaceFactory = new RasterWorkspaceFactory();

            ESRI.ArcGIS.Geodatabase.IWorkspaceName pworkspaceName = pworkspaceFactory.Create(null, "MyWorkspace", null, 0);
            ESRI.ArcGIS.esriSystem.IName           pname          = (IName)pworkspaceName;
            ESRI.ArcGIS.Geodatabase.IWorkspace     inmemWor       = (IWorkspace)pname.Open();
            IPoint            originpoint = pOrigin;
            IRasterWorkspace2 rasterws    = (IRasterWorkspace2)inmemWor;

            int nCol, nRow;

            nCol = 500;
            nRow = 500;
            double cellsizeX, cellsizeY;

            cellsizeX = pTin.Extent.Width / nCol;
            cellsizeY = pTin.Extent.Height / nRow;

            //用于计算的 float型的栅格数据
            IRasterDataset demdataset = rasterws.CreateRasterDataset("Dataset", "MEM", originpoint, nCol, nRow,
                                                                     (double)cellsizeX, (double)cellsizeY, 1, rstPixelType.PT_DOUBLE, null, true);

            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pname);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pworkspaceFactory);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pworkspaceName);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(inmemWor);
            }
            catch { }

            //IRawPixels pRawPixels = GetRawPixels(pRDS, 0);
            IRaster pRaster    = demdataset.CreateDefaultRaster();
            IPnt    pBlockSize = new DblPnt();

            //nCol = 50;
            //nRow = 50;
            pBlockSize.X = nCol;
            pBlockSize.Y = nRow;
            IPixelBlock pPixelBlock = pRaster.CreatePixelBlock(pBlockSize);
            //IPixelBlock pPixelBlock = pRawPixels.CreatePixelBlock(pBlockSize);
            IPixelBlock3 pPixelBlock3 = pPixelBlock as IPixelBlock3;

            //object val = pPixelBlock.get_SafeArray(0);
            ITinSurface pTinSurf = pTin as ITinSurface;
            // IRasterProps pRasterProps = pRawPixels as IRasterProps;
            IRasterProps pRasterProps = pRaster as IRasterProps;
            object       nodata;

            //pOrigin.X = pOrigin.X + (cellsize * 0.5);
            //pOrigin.Y = pOrigin.Y + (cellsize * nRow) - (cellsize * 0.5);
            pOrigin.X = pOrigin.X;
            pOrigin.Y = pOrigin.Y + (cellsizeY * nRow);
            nodata    = pRasterProps.NoDataValue;
            IGeoDatabaseBridge2 pbridge2 = (IGeoDatabaseBridge2) new GeoDatabaseHelperClass();

            //这个pOrigin为栅格左上角
            //pbridge2.QueryPixelBlock(pTinSurf, pOrigin.X, pOrigin.Y, cellsize, cellsize, esriRasterizationType.esriElevationAsRaster, nodata, ref val);
            //if (pTin.ProcessCancelled)
            //    return null;
            //val.GetType();
            CalPixelArray(pTinSurf, pOrigin.X, pOrigin.Y, cellsizeX, cellsizeY, ref pPixelBlock3);
            IPnt pOffset = new DblPnt();

            pOffset.X = 0;
            pOffset.Y = 0;
            //pPixelBlock3.set_PixelData(0, val);
            //pRawPixels.Write(pOffset, (IPixelBlock)pPixelBlock3);//写入硬盘
            IRasterEdit prasteredit = pRaster as IRasterEdit;

            prasteredit.Write(pOffset, (IPixelBlock)pPixelBlock3);
            //pRDS = OpenOutputRasterDataset(sDir, sName);

            //IPixelBlock pb = pRaster.CreatePixelBlock(pBlockSize);
            //pRaster.Read(pOffset,pb);
            return(pRaster);
        }
Exemplo n.º 16
0
        /// <summary>
        /// 在内存中创建图层
        /// </summary>
        /// <param name="DataSetName">数据集名称</param>
        /// <param name="AliaseName">别名</param>
        /// <param name="SpatialRef">空间参考</param>
        /// <param name="GeometryType">几何类型</param>
        /// <param name="PropertyFields">属性字段集合</param>
        /// <returns>IfeatureLayer</returns>
        public static IFeatureLayer CreateFeatureLayerInmemeory(string DataSetName, string AliaseName, ISpatialReference SpatialRef, esriGeometryType GeometryType, IFields PropertyFields)
        {
            IWorkspaceFactory workspaceFactory = new InMemoryWorkspaceFactoryClass();

            ESRI.ArcGIS.Geodatabase.IWorkspaceName workspaceName = workspaceFactory.Create("", "MyWorkspace", null, 0);
            ESRI.ArcGIS.esriSystem.IName           name          = (IName)workspaceName;
            ESRI.ArcGIS.Geodatabase.IWorkspace     inmemWor      = (IWorkspace)name.Open();
            IField        oField        = new FieldClass();
            IFields       oFields       = new FieldsClass();
            IFieldsEdit   oFieldsEdit   = null;
            IFieldEdit    oFieldEdit    = null;
            IFeatureClass oFeatureClass = null;
            IFeatureLayer oFeatureLayer = null;

            try
            {
                oFieldsEdit = oFields as IFieldsEdit;
                oFieldEdit  = oField as IFieldEdit;
                for (int i = 0; i < PropertyFields.FieldCount; i++)
                {
                    oFieldsEdit.AddField(PropertyFields.get_Field(i));
                }
                IGeometryDef     geometryDef     = new GeometryDefClass();
                IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
                geometryDefEdit.AvgNumPoints_2     = 5;
                geometryDefEdit.GeometryType_2     = GeometryType;
                geometryDefEdit.GridCount_2        = 1;
                geometryDefEdit.HasM_2             = false;
                geometryDefEdit.HasZ_2             = false;
                geometryDefEdit.SpatialReference_2 = SpatialRef;
                oFieldEdit.Name_2        = "SHAPE";
                oFieldEdit.Type_2        = esriFieldType.esriFieldTypeGeometry;
                oFieldEdit.GeometryDef_2 = geometryDef;
                oFieldEdit.IsNullable_2  = true;
                oFieldEdit.Required_2    = true;
                oFieldsEdit.AddField(oField);
                oFeatureClass = (inmemWor as IFeatureWorkspace).CreateFeatureClass(DataSetName, oFields, null, null, esriFeatureType.esriFTSimple, "SHAPE", "");
                (oFeatureClass as IDataset).BrowseName = DataSetName;
                oFeatureLayer              = new FeatureLayerClass();
                oFeatureLayer.Name         = AliaseName;
                oFeatureLayer.FeatureClass = oFeatureClass;
            }
            catch
            {
            }
            finally
            {
                try
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oField);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oFields);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oFieldsEdit);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oFieldEdit);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(name);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workspaceFactory);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workspaceName);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(inmemWor);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oFeatureClass);
                }
                catch { }

                GC.Collect();
            }
            return(oFeatureLayer);
        }
Exemplo n.º 17
0
        /// <summary>
        /// obtain the database workspace and path dynamically from the layers in the map
        /// </summary>
        private void InitDatabase(ESRI.ArcGIS.Carto.IMap ThisMap, ref string ErrorMessage)
        {
            ESRI.ArcGIS.Carto.ILayer ThisLayer;
            ESRI.ArcGIS.Geodatabase.IDataset ThisDataset;
            int LayerCount;

            LayerCount = ThisMap.LayerCount;

            for (int LayerIndex = 0; LayerIndex < LayerCount; LayerIndex++)
            {
                ThisLayer = ThisMap.get_Layer(LayerIndex);

                if (!(ThisLayer is ESRI.ArcGIS.Carto.IFeatureLayer))
                    continue;

                if (((ESRI.ArcGIS.Carto.IFeatureLayer)ThisLayer).FeatureClass == null)
                    continue;

                ThisDataset = (ESRI.ArcGIS.Geodatabase.IDataset)
                    ((ESRI.ArcGIS.Carto.IFeatureLayer)ThisLayer).FeatureClass;

                if (ThisDataset.Name != m_LYR_GENERATED_TRANSECTS)
                    continue;

                m_Workspace = ThisDataset.Workspace;
                m_DatabasePath = ThisDataset.Workspace.PathName;
                break;

            }

            if (string.IsNullOrEmpty(m_DatabasePath))
                ErrorMessage = "Could not find the transect layer used to detect the database.";
        }
Exemplo n.º 18
0
        private void AddTable(ESRI.ArcGIS.Geodatabase.IWorkspace pWks, string strTableName)
        {
            SysCommon.Gis.SysGisTable pGisTable = new SysCommon.Gis.SysGisTable(pWks);

            Exception eError = null;

            IFields     pFields     = new FieldsClass();
            IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;
            IField      pField      = new FieldClass();
            IFieldEdit  pEdit       = pField as IFieldEdit;

            pEdit.Name_2      = "ID";
            pEdit.AliasName_2 = "ID";
            pEdit.Type_2      = esriFieldType.esriFieldTypeOID;
            //pEdit.Length_2 = 50;
            pFieldsEdit.AddField(pField);

            pField            = new FieldClass();
            pEdit             = pField as IFieldEdit;
            pEdit.Name_2      = "Code";
            pEdit.AliasName_2 = "±àÂë";
            pEdit.Type_2      = esriFieldType.esriFieldTypeString;
            pEdit.Length_2    = 50;
            pFieldsEdit.AddField(pField);

            pField            = new FieldClass();
            pEdit             = pField as IFieldEdit;
            pEdit.Name_2      = "Name";
            pEdit.AliasName_2 = "Ãû³Æ";
            pEdit.Type_2      = esriFieldType.esriFieldTypeString;
            pEdit.Length_2    = 255;
            pFieldsEdit.AddField(pField);
            try
            {
                pGisTable.CreateTable(strTableName, pFields, out eError);
            }
            catch
            { }
            pGisTable = null;

            string      strInitXmlPath = Application.StartupPath + "\\..\\Res\\Xml\\DataTreeInitIndex.xml";
            XmlDocument xmldoc         = new XmlDocument();

            if (File.Exists(strInitXmlPath))
            {
                xmldoc.Load(strInitXmlPath);
                string  strSearch = "//Main/Childset/Itemset[@ItemName=" + "'Êý¾Ý×Öµä'" + "]";
                XmlNode xmlNode   = xmldoc.SelectSingleNode(strSearch);
                if (xmlNode != null)
                {
                    XmlElement childele = xmldoc.CreateElement("Layer");

                    childele.SetAttribute("tblName", strTableName);
                    childele.SetAttribute("ItemName", strTableName);
                    childele.SetAttribute("Caption", "");
                    xmlNode.AppendChild(childele as XmlNode);
                    xmldoc.Save(strInitXmlPath);
                }
            }
            xmldoc = null;
        }
Exemplo n.º 19
0
 public void Load(ESRI.ArcGIS.Geodatabase.IWorkspace _workspace, ESRI.ArcGIS.Geodatabase.IRow _row, BaseModel BaseModel, ModelProperty _property, BaseModel.LoadMethod ChooseLoadMethod)
 {
     this.Load(_workspace, _row, BaseModel, _property);
 }
		void cleanUp()
		{
			//m_pWSF = null;
			m_pWS = null;
			m_pSDT = null;
			m_pSDS = null;
			m_pSB = null;
			m_pB = null;
			m_SelectedObject = null;
			templateInfo = null;
			m_pSDI = null;
			formNames = null;
			formReduce = null;
			m_sfn = "";
			blnCancel = false;
			strLayers = "";
			strNodeLayers = "";
		}
Exemplo n.º 21
0
        //获取数据集
        public bool GetAllDataSets(string strServer, string strServerName, string strDataBase, string strUser, string strPassWord, string strVersion, string strDataType, out List <string> listDatasets)
        {
            //cyf 20110609 测试数据库连接 包括SDE、PDB、gdb
            SysCommon.Gis.SysGisDataSet pSysDt = new SysCommon.Gis.SysGisDataSet();
            Exception pError = null;

            listDatasets = null;
            pSysDt.SetWorkspace(strServer, strServerName, strDataBase, strUser, strPassWord, strVersion, out pError);


            ESRI.ArcGIS.Geodatabase.IWorkspace pWs = pSysDt.WorkSpace;
            if (pWs == null)
            {
                return(false);
            }
            //连接成功后,将数据集加载到下拉列表框中
            if (strDataType.Equals("DLG"))
            {
                //框架要素库中数据集名称
                List <string> LstDtName = pSysDt.GetAllFeatureDatasetNames();
                if (LstDtName.Count == 0)
                {
                    //pError = new Exception("该数据库下不存在数据集,请检查!");
                    return(false);
                }
                //遍历数据集名称,将数据集加载在下拉列表框中
                if (listDatasets == null)
                {
                    listDatasets = new List <string>();
                }
                foreach (string item in LstDtName)
                {
                    //历史数据集,不添加
                    if (item.ToLower().EndsWith("_GOH"))
                    {
                        continue;
                    }
                    string GetDataSetName = item;//数据集名称
                    //添加
                    listDatasets.Add(GetDataSetName);
                }
            }
            //  else if (strDataBase.Equals("DOM") || strDataBase.Equals("DEM"))
            else if (strDataType.Equals("DOM") || strDataType.Equals("DEM"))

            {
                IEnumDataset pEnumDataset = null;

                pEnumDataset = pWs.get_Datasets(esriDatasetType.esriDTRasterDataset);
                if (pEnumDataset == null)
                {
                    pError = new Exception("获取栅格数据名称出错!");
                    return(false);
                }
                pEnumDataset.Reset();
                IDataset pDt = pEnumDataset.Next();
                if (listDatasets == null)
                {
                    listDatasets = new List <string>();
                }
                //遍历栅格数据集
                while (pDt != null)
                {
                    string rasteName = ""; //栅格数据名称
                    rasteName = pDt.Name;
                    //添加
                    listDatasets.Add(rasteName);
                    pDt = pEnumDataset.Next();
                }


                pEnumDataset = pWs.get_Datasets(esriDatasetType.esriDTRasterCatalog);
                if (pEnumDataset == null)
                {
                    pError = new Exception("获取栅格数据名称出错!");
                    return(false);
                }
                pEnumDataset.Reset();
                pDt = pEnumDataset.Next();
                if (pDt == null)
                {
                    pError = new Exception("获取栅格数据名称出错!");
                    return(false);
                }

                //遍历栅格编目
                while (pDt != null)
                {
                    string rasteName = ""; //栅格数据名称
                    rasteName = pDt.Name;

                    //added by chulili 20110715过滤掉原本存在的历史库
                    if (!rasteName.ToLower().EndsWith("_GOH"))
                    {
                        //将栅格数据名称添加到数组中
                        listDatasets.Add(rasteName);
                    }
                    pDt = pEnumDataset.Next();
                }
            }
            return(true);
        }
Exemplo n.º 22
0
        private IRaster CreateRaster(Point2D ptLeftTop, double[] dbResolution, int[] nSize)
        {
            try
            {
                IWorkspaceFactory pworkspaceFactory = new RasterWorkspaceFactory();
                ESRI.ArcGIS.Geodatabase.IWorkspaceName pworkspaceName = pworkspaceFactory.Create(null, "MyWorkspace", null, 0);
                ESRI.ArcGIS.esriSystem.IName           pname          = (IName)pworkspaceName;
                ESRI.ArcGIS.Geodatabase.IWorkspace     inmemWor       = (IWorkspace)pname.Open();
                IRasterWorkspace2 rasterWs = (IRasterWorkspace2)inmemWor;

                //Define the spatial reference of the raster dataset.
                ISpatialReference sr = new UnknownCoordinateSystemClass();
                //Define the origin for the raster dataset, which is the lower left corner of the raster.
                IPoint origin = new PointClass();
                origin.PutCoords(ptLeftTop.X, ptLeftTop.Y);
                //Define the dimensions of the raster dataset.
                int    width   = nSize[0];        //This is the width of the raster dataset.
                int    height  = nSize[1];        //This is the height of the raster dataset.
                double xCell   = dbResolution[0]; //This is the cell size in x direction.
                double yCell   = dbResolution[1]; //This is the cell size in y direction.
                int    NumBand = 1;               // This is the number of bands the raster dataset contains.
                //Create a raster dataset in TIFF format.
                IRasterDataset rasterDataset = rasterWs.CreateRasterDataset("", "MEM",
                                                                            origin, width, height, xCell, yCell, NumBand, rstPixelType.PT_UCHAR, sr,
                                                                            true);

                //If you need to set NoData for some of the pixels, you need to set it on band
                //to get the raster band.
                IRasterBandCollection rasterBands = (IRasterBandCollection)rasterDataset;
                IRasterBand           rasterBand;
                IRasterProps          rasterProps;
                rasterBand  = rasterBands.Item(0);
                rasterProps = (IRasterProps)rasterBand;
                //Set NoData if necessary. For a multiband image, a NoData value needs to be set for each band.
                //rasterProps.NoDataValue = -9999f;
                //Create a raster from the dataset.
                IRaster raster = rasterDataset.CreateDefaultRaster();

                //Create a pixel block using the weight and height of the raster dataset.
                //If the raster dataset is large, a smaller pixel block should be used.
                //Refer to the topic "How to access pixel data using a raster cursor".
                //IPnt blocksize = new PntClass();
                //blocksize.SetCoords(width, height);
                //IPixelBlock3 pixelblock = raster.CreatePixelBlock(blocksize) as IPixelBlock3;

                ////Populate some pixel values to the pixel block.
                //System.Array pixels;
                //pixels = (System.Array)pixelblock.get_PixelData(0);
                //for (int i = 0; i < width; i++)
                //{
                //    for (int j = 0; j < height; j++)
                //    {
                //        pixels.SetValue(dbData[i, j], i, j);
                //    }
                //}
                //pixelblock.set_PixelData(0, (System.Array)pixels);

                ////Define the location that the upper left corner of the pixel block is to write.
                //IPnt upperLeft = new PntClass();
                //upperLeft.SetCoords(ptLeftTop.X, ptLeftTop.Y);

                ////Write the pixel block.
                //IRasterEdit rasterEdit = (IRasterEdit)raster;
                //rasterEdit.Write(upperLeft, (IPixelBlock)pixelblock);
                //rasterEdit.Refresh();

                //Release rasterEdit explicitly.
                //System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterDataset);
                //System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterEdit);
                //System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterWs);
                //System.Runtime.InteropServices.Marshal.ReleaseComObject(sr);
                // GC.Collect();

                return(raster);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return(null);
            }

            return(null);
        }
		private Boolean CreateTemplate(NameEvents templateInfo)
		{
			//need to get everything first
			IGxDatabase pDatabase = null;
			ISchematicDiagramClassContainer pDiagramClassContainer = null;

			if (m_SelectedObject.Category == "Schematic Dataset")
			{
				pDatabase = (IGxDatabase)m_SelectedObject.Parent;
			}
			else  //on the database already
			{
				pDatabase = (IGxDatabase)m_SelectedObject;
			}
			m_pWS = pDatabase.Workspace;

			ESRI.ArcGIS.Schematic.ISchematicWorkspaceFactory pSWF = new SchematicWorkspaceFactory();
			ESRI.ArcGIS.Schematic.ISchematicWorkspace pSW = pSWF.Open(m_pWS);

			m_pSDS = pSW.get_SchematicDatasetByName(templateInfo.DatasetName);

			//check to see if the template name already exists
			pDiagramClassContainer = (ISchematicDiagramClassContainer)m_pSDS;
			m_pSDT = pDiagramClassContainer.GetSchematicDiagramClass(templateInfo.TemplateName.ToString());
			if (m_pSDT != null) return false;

			//create the schematic template
			m_pSDT = m_pSDS.CreateSchematicDiagramClass(templateInfo.TemplateName);

			if ((templateInfo.AutoCreate == true) || (templateInfo.UseVertices == true))
			{
				m_pB = (ESRI.ArcGIS.Schematic.ISchematicBuilder)m_pSDT;
				m_pSB = (ESRI.ArcGIS.Schematic.ISchematicStandardBuilder)m_pSDT.SchematicBuilder;
				m_pSB.InitializeLinksVertices = templateInfo.UseVertices;
				m_pSB.AutoCreateElementClasses = templateInfo.AutoCreate;
			}
			m_pSDS.Save(ESRI.ArcGIS.esriSystem.esriArcGISVersion.esriArcGISVersion10, false);
			return true;
		}
		private Boolean CreateDataset(NameEvents templateInfo)
		{
			try
			{
				IGxDatabase pDatabase = (IGxDatabase)m_SelectedObject;

				m_pWS = pDatabase.Workspace;

				ESRI.ArcGIS.Schematic.ISchematicWorkspaceFactory pSWF = new SchematicWorkspaceFactory();
				ESRI.ArcGIS.Schematic.ISchematicWorkspace pSW = pSWF.Open(m_pWS);
				//check to see if this dataset name is already used
				m_pSDS = pSW.get_SchematicDatasetByName(templateInfo.DatasetName.ToString());
				if (m_pSDS != null) return false;

				m_pSDS = pSW.CreateSchematicDataset(templateInfo.DatasetName, "");
				return true;
			}
			catch
			{
				//nothing
				return false;
			}
		}
Exemplo n.º 25
0
        public static bool GetAllDataSets(string strServer, string strServerName, string strDataBase, string strUser, string strPassWord, string strVersion, string strDataType, out List <string> listDatasets)
        {
            //cyf 20110609 测试数据库连接 包括SDE、PDB、gdb
            Fan.Common.Gis.SysGisDataSet pSysDt = new Fan.Common.Gis.SysGisDataSet();
            Exception pError = null;

            listDatasets = null;
            //if (this.combox_DBFormat.SelectedValue.ToString() == enumInterDBFormat.ARCGISGDB.GetHashCode().ToString())
            //{
            //    if (!Directory.Exists(txtDataBase.Text))
            //    {
            //        pError = new Exception("数据库文件路径不存在!");
            //        return false;
            //    }
            //    pSysDt.SetWorkspace(this.txtDataBase.Text, enumWSType.GDB, out pError);
            //}
            //else if (this.combox_DBFormat.SelectedValue.ToString() == enumInterDBFormat.ARCGISSDE.GetHashCode().ToString())
            //{
            pSysDt.SetWorkspace(strServer, strServerName, strDataBase, strUser, strPassWord, strVersion, out pError);

            //}
            //else if (this.combox_DBFormat.SelectedValue.ToString() == enumInterDBFormat.ARCGISPDB.GetHashCode().ToString())
            //{
            //    if (!File.Exists(txtDataBase.Text))
            //    {pError = new Exception("数据库路径不存在!");
            //        return false;
            //    }

            //    pSysDt.SetWorkspace(this.txtDataBase.Text, enumWSType.PDB, out pError);
            //}
            //if (pError != null)
            //{
            //    pError = new Exception("连接数据库失败!");
            //    return false;
            //}
            ESRI.ArcGIS.Geodatabase.IWorkspace pWs = pSysDt.WorkSpace;
            if (pWs == null)
            {
                return(false);
            }
            //连接成功后,将数据集加载到下拉列表框中
            if (strDataType.Equals("DLG"))
            {
                //框架要素库中数据集名称
                List <string> LstDtName = pSysDt.GetAllFeatureDatasetNames();
                if (LstDtName.Count == 0)
                {
                    //pError = new Exception("该数据库下不存在数据集,请检查!");
                    return(false);
                }
                //遍历数据集名称,将数据集加载在下拉列表框中
                if (listDatasets == null)
                {
                    listDatasets = new List <string>();
                }
                foreach (string item in LstDtName)
                {
                    //历史数据集,不添加
                    if (item.ToLower().EndsWith("_GOH"))
                    {
                        continue;
                    }
                    string GetDataSetName = item;//数据集名称
                    //添加
                    listDatasets.Add(GetDataSetName);
                }
            }
            else if (strDataType.Equals("DOM") || strDataType.Equals("DEM"))
            {
                IEnumDataset pEnumDataset = null;

                pEnumDataset = pWs.get_Datasets(esriDatasetType.esriDTRasterDataset);
                if (pEnumDataset == null)
                {
                    pError = new Exception("获取栅格数据名称出错!");
                    return(false);
                }
                pEnumDataset.Reset();
                IDataset pDt = pEnumDataset.Next();
                if (listDatasets == null)
                {
                    listDatasets = new List <string>();
                }
                //遍历栅格数据集
                while (pDt != null)
                {
                    string rasteName = ""; //栅格数据名称
                    rasteName = pDt.Name;
                    //添加
                    listDatasets.Add(rasteName);
                    pDt = pEnumDataset.Next();
                }


                pEnumDataset = pWs.get_Datasets(esriDatasetType.esriDTRasterCatalog);
                if (pEnumDataset == null)
                {
                    pError = new Exception("获取栅格数据名称出错!");
                    return(false);
                }
                pEnumDataset.Reset();
                pDt = pEnumDataset.Next();
                if (pDt == null)
                {
                    pError = new Exception("获取栅格数据名称出错!");
                    return(false);
                }

                //遍历栅格编目
                while (pDt != null)
                {
                    string rasteName = ""; //栅格数据名称
                    rasteName = pDt.Name;

                    //added by chulili 20110715过滤掉原本存在的历史库
                    if (!rasteName.ToLower().EndsWith("_GOH"))
                    {
                        //将栅格数据名称添加到数组中
                        listDatasets.Add(rasteName);
                    }
                    pDt = pEnumDataset.Next();
                }
            }
            return(true);
        }
        public ESRI.ArcGIS.Geodatabase.IFeatureClass GetFeatureClassFromShapefileOnDisk(System.String string_ShapefileName, out ESRI.ArcGIS.Geodatabase.IWorkspace workspace)
        {
            //We have a valid directory, proceed

            System.IO.FileInfo fileInfo_check = new System.IO.FileInfo(string_ShapefileName);
            if (fileInfo_check.Exists)
            {
                //We have a valid shapefile, proceed

                ESRI.ArcGIS.Geodatabase.IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactory();
                workspace = workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(string_ShapefileName), 0);
                ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspace; // Explict Cast
                ESRI.ArcGIS.Geodatabase.IFeatureClass     featureClass     = featureWorkspace.OpenFeatureClass(System.IO.Path.GetFileName(string_ShapefileName));
                return(featureClass);
            }
            else
            {
                workspace = null;
                //Not valid shapefile
                return(null);
            }
        }
Exemplo n.º 27
0
        private void OpenCADFile(string filePath, string outputFilePath)
        {
            try
            {
                Debug.WriteLine("Start Time: " + DateTime.Now.ToShortTimeString());
                System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;


                String nameOfPath    = System.IO.Path.GetDirectoryName(filePath);
                String nameOfCADFile = System.IO.Path.GetFileName(filePath);

                #region Open CAD Workspace from File Path
                //Set the workspace.
                ESRI.ArcGIS.Geodatabase.IWorkspaceFactory pWorkspaceFact = new
                                                                           ESRI.ArcGIS.DataSourcesFile.CadWorkspaceFactory();
                ESRI.ArcGIS.Geodatabase.IWorkspaceFactory defaultWorkspaceFact = new FileGDBWorkspaceFactory();
                //Open the workspace.
                ESRI.ArcGIS.Geodatabase.IWorkspace pWorkspace = pWorkspaceFact.OpenFromFile(nameOfPath, 0);
                //Get the CADDrawingWorkspace.
                ESRI.ArcGIS.DataSourcesFile.ICadDrawingWorkspace pCadDwgWorkspace;
                pCadDwgWorkspace = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingWorkspace)pWorkspace;
                //Open the CadDrawingDataset.
                ESRI.ArcGIS.DataSourcesFile.ICadDrawingDataset pCadDwgDataset;
                pCadDwgDataset = pCadDwgWorkspace.OpenCadDrawingDataset(nameOfCADFile);

                //Set the feature workspace.
                ESRI.ArcGIS.Geodatabase.IFeatureWorkspace pFeatureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)pWorkspace;
                //Open the Feature Class.

                #endregion


                #region Getting Polygon, polylines, and annotation from Cad file

                ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass =
                    pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile,
                                                                            ":Polygon"));

                ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass_Plyline =
                    pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile,
                                                                            ":Polyline"));

                ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass_Anno =
                    pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile,
                                                                            ":Annotation"));
                #endregion


                UID CLSID_def = new UIDClass();
                CLSID_def.Value = "esriGeoDatabase.Feature";

                #region Creating Layers from Feature Classes
                //Polygons
                ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer = new ESRI.ArcGIS.Carto.CadFeatureLayer()
                                                             as ESRI.ArcGIS.Carto.IFeatureLayer;
                pFeatLayer.FeatureClass = pFeatClass;
                pFeatLayer.Name         = "Polygons";
                ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer;

                //Annotation
                ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer_Anno = new ESRI.ArcGIS.Carto.CadFeatureLayer()
                                                                  as ESRI.ArcGIS.Carto.IFeatureLayer;
                pFeatLayer_Anno.FeatureClass = pFeatClass_Anno;
                pFeatLayer_Anno.Name         = "Annotation";
                ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers_Anno =
                    (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer_Anno;

                //Polylines
                ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer_Plyline = new ESRI.ArcGIS.Carto.CadFeatureLayer()
                                                                     as ESRI.ArcGIS.Carto.IFeatureLayer;
                pFeatLayer_Plyline.FeatureClass = pFeatClass_Plyline;
                pFeatLayer_Plyline.Name         = "Polylines";
                ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers_Plyline =
                    (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer_Plyline;
                #endregion

                #region Creating In-Memory workspace
                IWorkspaceFactory            WF    = new InMemoryWorkspaceFactory();
                ESRI.ArcGIS.esriSystem.IName name  = WF.Create("", "MyWorkspace", null, 0) as ESRI.ArcGIS.esriSystem.IName;
                IWorkspace        inMemWorkspace   = (IWorkspace)name.Open();
                IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)inMemWorkspace;
                #endregion

                #region Creating new Fields

                IObjectClassDescription objectClassDescription = new FeatureClassDescription();

                // create the fields using the required fields method
                IFields     exportFields = new Fields();
                IFieldsEdit fieldsEdit   = (IFieldsEdit)exportFields;

                //OID
                IField     field        = new Field();
                IField     oidField     = new Field();
                IFieldEdit oidFieldEdit = (IFieldEdit)oidField;
                oidFieldEdit.Name_2 = "OID";
                oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
                fieldsEdit.AddField(oidField);

                // Create a geometry definition (and spatial reference) for the feature class
                IGeometryDef     geometryDef     = new GeometryDef();
                IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
                geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
                IGeoDataset dataSet = (IGeoDataset)pFeatClass.FeatureDataset;
                ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironment();

                ISpatialReference           spatialReference           = dataSet.SpatialReference;
                ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference;
                spatialReferenceResolution.ConstructFromHorizon();
                ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference;
                spatialReferenceTolerance.SetDefaultXYTolerance();
                geometryDefEdit.SpatialReference_2 = spatialReference;


                // Add a geometry field to the fields collection. This is where the geometry definition is applied.
                IField     geometryField     = new Field();
                IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField;
                geometryFieldEdit.Name_2        = "Shape";
                geometryFieldEdit.Type_2        = esriFieldType.esriFieldTypeGeometry;
                geometryFieldEdit.GeometryDef_2 = geometryDef;
                fieldsEdit.AddField(geometryField);
                #endregion


                #region Creating New Shapefile for Final output
                UID CLSID = new UIDClass();
                CLSID.Value = "esriGeoDatabase.Feature";

                //using the In-Memory Workspace created above
                IFeatureClass output             = featureWorkspace.CreateFeatureClass("myPolygons", pFeatClass.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null);
                IFeatureClass polylines_cleaned  = featureWorkspace.CreateFeatureClass("polylines_cleaned", pFeatClass_Plyline.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null);
                IFeatureClass annotation_cleaned = featureWorkspace.CreateFeatureClass("annotation_cleaned", pFeatClass_Anno.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null);
                #endregion

                #region Appending features from CADWorkspaceFeatureClass to In-Memory FeatureClass Because Update cursor not in Cad workspace
                Geoprocessor GP = new Geoprocessor();

                //Polylines
                ESRI.ArcGIS.DataManagementTools.Append append = new Append();
                append.inputs = pFeatClass_Plyline;
                append.target = polylines_cleaned;
                GP.Execute(append, null);
                //System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass_Plyline);
                GC.Collect();

                //Annotation
                append        = new Append();
                append.inputs = pFeatClass_Anno;
                append.target = annotation_cleaned;
                GP.Execute(append, null);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass_Anno);
                GC.Collect();

                //Polygons to output
                append        = new Append();
                append.inputs = pFeatClass;
                append.target = output;
                GP.Execute(append, null);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass);
                GC.Collect();
                #endregion

                #region Query Filter to Filter Layers

                string queryString = "";
                //using the checked box list and comma seperated list to create where clause string

                //Adding Items from Check Box List
                foreach (var checkedItem in checkedListBox1.CheckedItems)
                {
                    queryString = queryString + "Layer NOT LIKE '" + checkedItem.ToString() + "' AND ";
                }
                //Adding Items from Comma separated string
                if (textBox_commaSeparated.Text.Length > 0)
                {
                    foreach (var item in textBox_commaSeparated.Text.Split(','))
                    {
                        queryString = queryString + "Layer NOT LIKE '" + item.ToString() + "' AND ";
                    }
                }

                //Removing Last 'AND' FROM queryString
                if (queryString.Length > 0) //if Atleast one item added
                {
                    queryString = queryString.Remove(queryString.Length - 4);
                }


                IQueryFilter queryFilter = new QueryFilter();
                queryFilter.SubFields = "";
                if (queryString.Length > 0)
                {
                    queryFilter.WhereClause = queryString;
                }
                else
                {
                    queryFilter.WhereClause = "1=1";
                }


                #endregion



                #region Removing Null Geometries

                string ignoreList = queryString.Replace("Layer NOT LIKE '", "").Replace("' AND ", ",").Replace("' ", "");

                Debug.WriteLine("lines Count before:" + polylines_cleaned.FeatureCount(new QueryFilter()).ToString());
                //From Polylines_cleaned
                IFeatureCursor updateCursor = polylines_cleaned.Update(new QueryFilter(), false);
                IFeature       feat         = updateCursor.NextFeature();
                while (feat != null)
                {
                    string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer")));
                    lyr = lyr.ToUpper();
                    if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l)))
                    {
                        updateCursor.DeleteFeature();
                    }
                    feat = updateCursor.NextFeature();
                }
                System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor);
                //System.Runtime.InteropServices.Marshal.ReleaseComObject(feat);
                GC.Collect();
                Debug.WriteLine("lines Count After:" + polylines_cleaned.FeatureCount(new QueryFilter()).ToString());


                //From output
                Debug.WriteLine("polygons Count before:" + output.FeatureCount(new QueryFilter()).ToString());
                updateCursor = output.Update(new QueryFilter(), false);
                feat         = updateCursor.NextFeature();
                while (feat != null)
                {
                    string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer")));
                    lyr = lyr.ToUpper();
                    if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l)))
                    {
                        updateCursor.DeleteFeature();
                    }
                    feat = updateCursor.NextFeature();
                }
                System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor);
                GC.Collect();
                Debug.WriteLine("polygons Count after:" + output.FeatureCount(new QueryFilter()).ToString());

                //From Annotation
                Debug.WriteLine("Annotation Count before:" + annotation_cleaned.FeatureCount(new QueryFilter()).ToString());
                updateCursor = annotation_cleaned.Update(new QueryFilter(), false);
                feat         = updateCursor.NextFeature();
                while (feat != null)
                {
                    string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer")));
                    lyr = lyr.ToUpper();
                    if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l)))
                    {
                        updateCursor.DeleteFeature();
                    }
                    feat = updateCursor.NextFeature();
                }
                System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor);
                GC.Collect();
                Debug.WriteLine("Annotation Count after:" + annotation_cleaned.FeatureCount(new QueryFilter()).ToString());
                #endregion


                #region Convert lines feature class to feature Cursor

                IFeatureCursor linesFCursor = polylines_cleaned.Search(new QueryFilter(), false);

                #endregion


                #region Deleting all columns of polygons to match with output

                IFields     _fieldsP     = output.Fields;
                IFieldsEdit _fieldsEditP = (IFieldsEdit)_fieldsP;
                for (int i = 0; i < output.Fields.FieldCount; i++)
                {
                    IField _field = output.Fields.get_Field(i);
                    if (_field.Name != "Shape" && _field.Name != "FID")
                    {
                        output.DeleteField(_field);
                        if (i < output.Fields.FieldCount)
                        {
                            i--;
                        }
                    }
                }

                System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsP);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsEditP);
                GC.Collect();
                #endregion

                #region Setting Envelop information
                IEnvelope   envelop    = new Envelope() as IEnvelope;
                IGeoDataset dataSetEnv = (IGeoDataset)pFeatClass_Plyline.FeatureDataset;
                envelop.SpatialReference = dataSet.SpatialReference;
                envelop.PutCoords(dataSet.Extent.XMin, dataSet.Extent.YMin, dataSet.Extent.XMax, dataSet.Extent.YMax);
                #endregion


                #region Construct Polygons from Lines Cursor (usting Feature Construct)
                IFeatureConstruction featureConstruct = new FeatureConstruction() as IFeatureConstruction;
                ISelectionSet        selectionSet     = null;
                //atureConstruct.ConstructPolygonsFromFeaturesFromCursor(null,output,envelop,false,false,linesFCursor,null,0.001,null);
                featureConstruct.AutoCompleteFromFeaturesFromCursor(output, envelop, linesFCursor, null, -1, null, out selectionSet);

                #endregion

                System.Runtime.InteropServices.Marshal.ReleaseComObject(featureConstruct);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(linesFCursor);

                GC.Collect();



                Debug.WriteLine("polygons Count after PolygonConstruct :" + output.FeatureCount(new QueryFilter()).ToString());



                #region SPATIAL JOIN
                GP = new Geoprocessor();
                ESRI.ArcGIS.AnalysisTools.SpatialJoin spatialJoin = new ESRI.ArcGIS.AnalysisTools.SpatialJoin();

                spatialJoin.join_features     = annotation_cleaned;
                spatialJoin.target_features   = output;
                spatialJoin.join_operation    = "JOIN_ONE_TO_MANY";
                spatialJoin.join_type         = "KEEP_ALL";
                spatialJoin.match_option      = "CONTAINS";
                spatialJoin.out_feature_class = outputFilePath;

                GP.Execute(spatialJoin, null);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(annotation_cleaned);
                GC.Collect();


                #endregion

                #region Remove All Fields of Annotation except Text

                ShapefileWorkspaceFactory wsf  = new ShapefileWorkspaceFactory();
                IFeatureWorkspace         work = (IFeatureWorkspace)wsf.OpenFromFile(System.IO.Path.GetDirectoryName(outputFilePath), 0);
                IFeatureClass             output_AfterJoin_FClasss = work.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(outputFilePath));

                IFields     _fields     = output_AfterJoin_FClasss.Fields;
                IFieldsEdit _fieldsEdit = (IFieldsEdit)_fields;
                for (int i = 0; i < _fields.FieldCount; i++)
                {
                    IField _field = output_AfterJoin_FClasss.Fields.get_Field(i);
                    if (_field.Name != "Text_" && _field.Name != "Text" && _field.Name != "Shape" && _field.Name != "FID")
                    {
                        output_AfterJoin_FClasss.DeleteField(_field);
                        i--;
                    }
                    else
                    {
                        if (field.Name == "Text_" || _field.Name == "Text")
                        {
                            IFieldEdit fieldEdit = (IFieldEdit)_field;
                            fieldEdit.Name_2      = "PlotNumber";
                            fieldEdit.AliasName_2 = "PlotNumber";
                        }
                    }
                }

                System.Runtime.InteropServices.Marshal.ReleaseComObject(_fields);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsEdit);
                GC.Collect();

                #endregion
                System.Windows.Forms.Cursor.Current = Cursors.Default;
                Debug.WriteLine("End Time: " + DateTime.Now.ToShortTimeString());
                MessageBox.Show("Import Complete!");
            }
            catch
            {
                MessageBox.Show("Error Importing. Something wrong with the CAD File");
            }
        }