Esempio n. 1
0
        /// <summary>
        /// 设置PDB、GDB工作区
        /// </summary>
        /// <param name="sFilePath">文件路径</param>
        /// <param name="wstype">工作区类型</param>
        /// <returns>输出错误Exception</returns>
        private IWorkspace SetWorkspace(string sFilePath, enumWSType wstype, out Exception eError)
        {
            eError = null;
            IWorkspace pWorkspace = null;

            try
            {
                IPropertySet pPropSet = new PropertySetClass();
                switch (wstype)
                {
                case enumWSType.PDB:
                    AccessWorkspaceFactory pAccessFact = new AccessWorkspaceFactoryClass();
                    pPropSet.SetProperty("DATABASE", sFilePath);
                    pWorkspace  = pAccessFact.Open(pPropSet, 0);
                    pAccessFact = null;
                    break;

                case enumWSType.GDB:
                    FileGDBWorkspaceFactoryClass pFileGDBFact = new FileGDBWorkspaceFactoryClass();
                    pPropSet.SetProperty("DATABASE", sFilePath);
                    pWorkspace   = pFileGDBFact.Open(pPropSet, 0);
                    pFileGDBFact = null;
                    break;
                }
                pPropSet = null;
                return(pWorkspace);
            }
            catch (Exception eX)
            {
                eError = eX;
                return(null);
            }
        }
Esempio n. 2
0
        public static void ExportToXml(IWorkspace sourceWorkspace, string targetPath,bool binaryGeometry,bool compressed,bool retriveMetadata)
        {
            // Open the source geodatabase and create a name object for it.
            IWorkspaceFactory workspaceFactory = new AccessWorkspaceFactoryClass();
            //IWorkspace workspace = workspaceFactory.OpenFromFile(databaseName, 0);
            IDataset workspaceDataset = (IDataset)sourceWorkspace;
            IName workspaceName = workspaceDataset.FullName;

            // Retrieve the first feature dataset from the workspace.
            IEnumDatasetName enumDatasetName = sourceWorkspace.get_DatasetNames
              (esriDatasetType.esriDTFeatureDataset);
            enumDatasetName.Reset();
            IName featureDatasetName = (IName)enumDatasetName.Next();
            if (featureDatasetName == null)
            {
                throw new Exception(
                  "No feature datasets exist in the specified geodatabase.");
            }

            // Create a new names enumerator and add the feature dataset name.
            IEnumNameEdit enumNameEdit = new NamesEnumeratorClass();
            enumNameEdit.Add(featureDatasetName);
            IEnumName enumName = (IEnumName)enumNameEdit;

            // Create a GeoDBDataTransfer object and create a name mapping.
            IGeoDBDataTransfer geoDBDataTransfer = new GeoDBDataTransferClass();
            IEnumNameMapping enumNameMapping = null;
            geoDBDataTransfer.GenerateNameMapping(enumName, workspaceName, out enumNameMapping);

            // Create an exporter and export the dataset with binary geometry, not compressed,
            // and including metadata.
            IGdbXmlExport gdbXmlExport = new GdbExporterClass();
            gdbXmlExport.ExportDatasets(enumNameMapping, targetPath, binaryGeometry, compressed, retriveMetadata);
        }
Esempio n. 3
0
        private void button2_Click(object sender, EventArgs e)
        {
            string PDBPath = mdbPath();

            if (PDBPath != "")
            {
                IWorkspaceFactory pWSFactory = new AccessWorkspaceFactoryClass();

                IWorkspace pWS = pWSFactory.OpenFromFile(PDBPath, 0);

                IEnumDataset pEDataset = pWS.get_Datasets(esriDatasetType.esriDTAny);

                IDataset pDataset = pEDataset.Next();
                comboBox1.Items.Clear();

                while (pDataset != null)
                {
                    if (pDataset.Type == esriDatasetType.esriDTFeatureClass)
                    {
                        comboBox1.Items.Add(pDataset.Name);
                    }
                    pDataset = pEDataset.Next();
                }
                comboBox1.Text = comboBox1.Items[0].ToString();
            }
        }
Esempio n. 4
0
        public IWorkspace getMDBWorkspace(string mdbfilepath)
        {
            IWorkspaceFactory pWsFac = new AccessWorkspaceFactoryClass();
            IWorkspace        pWs    = pWsFac.OpenFromFile(mdbfilepath, 0);

            return(pWs);
        }
Esempio n. 5
0
        private void Add_Tables()
        {
            IWorkspaceFactory pWorkspaceFactory = new AccessWorkspaceFactoryClass();
            IWorkspace        pWorkspace        = (IWorkspace)pWorkspaceFactory.OpenFromFile(@"C:\Users\mgh\Desktop\Data\GDB_DneshgaheAzad.mdb", 0);
            IEnumDataset      pEnumDataset      = pWorkspace.get_Datasets(esriDatasetType.esriDTTable);
            IDataset          pDataset          = pEnumDataset.Next();

            m_ArrayTables = new ArrayList();

            while (pDataset != null)
            {
                if (pDataset is ITable)
                {
                    cboLayerAttributeTable.Items.Add(pDataset.Name);
                    cboLayerGraph.Items.Add(pDataset.Name);
                    m_ArrayTables.Add(pDataset);
                }
                pDataset = pEnumDataset.Next();
            }
            if (cboLayerAttributeTable.Items.Count > 0)
            {
                cboLayerAttributeTable.SelectedIndex = 0;
            }
            if (cboLayerGraph.Items.Count > 0)
            {
                cboLayerGraph.SelectedIndex = 0;
            }
        }
Esempio n. 6
0
        public bool createMDBFile(string mdbfolderpath, string filename)
        {
            // IWorkspace workspace = null;
            IWorkspaceName workspaceName = null;

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

                if (workspaceName != null)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception eg)
            {
                return(false);
            }
        }
Esempio n. 7
0
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                IWorkspaceFactory wfactory  = new AccessWorkspaceFactoryClass();
                IWorkspace        ws        = wfactory.OpenFromFile(textBox3.Text, 0); //makan el database
                IFeatureWorkspace fws       = ws as IFeatureWorkspace;
                IFeatureClass     featclass = fws.OpenFeatureClass(comboBox3.SelectedItem.ToString());
                IFeatureLayer     featLayer = new FeatureLayerClass();
                featLayer.FeatureClass = featclass;
                featLayer.Name         = comboBox3.SelectedItem.ToString();
                mdoc.get_Map(comboBox1.SelectedIndex).AddLayer(featLayer);
                IMap map = mdoc.get_Map(comboBox1.SelectedIndex);
                axMapControl1.Map = map;
                axMapControl1.Refresh();

                checkedListBox1.Items.Clear();
                comboBox2.Items.Clear();
                IEnumLayer allLayers = map.get_Layers();
                ILayer     layer     = allLayers.Next();
                while (layer != null)
                {
                    checkedListBox1.Items.Add(layer.Name);
                    comboBox2.Items.Add(layer.Name);
                    layer = allLayers.Next();
                }
                for (int d = 0; d < checkedListBox1.Items.Count; d++)
                {
                    checkedListBox1.SetItemChecked(d, true);
                }
            }
            catch
            {
            }
        }
        public static void CreatePersonalGeodatabase(string destinationPGDBFile)
        {
            string pgdbFileName;
            string pgdbParentDirectory;
            string pgdbFile;

            destinationPGDBFile = System.IO.Path.GetFullPath(destinationPGDBFile);
            pgdbFileName        = System.IO.Path.GetFileName(destinationPGDBFile);
            pgdbParentDirectory = System.IO.Path.GetDirectoryName(destinationPGDBFile);
            pgdbFile            = System.IO.Path.Combine(pgdbParentDirectory, pgdbFileName);

            IWorkspaceFactory pgdbWSFactory = new AccessWorkspaceFactoryClass();
            IWorkspaceName    pgdbWorkspaceName;

            //Create the Access database file if it does not already exist
            if (!System.IO.File.Exists(pgdbFile))
            {
                try
                {
                    pgdbWorkspaceName = pgdbWSFactory.Create(pgdbParentDirectory, pgdbFileName, null, 0);
                }
                catch (System.Runtime.InteropServices.COMException e)
                {
                    throw new System.Runtime.InteropServices.COMException("An unexpected error occurred while trying to create a personal geodatabase.", e);
                }
            }
            else
            {
                throw new System.IO.IOException("A file with the same name already exists. Unable to create personal geodatabase.");
            }
        }
Esempio n. 9
0
        /// <summary>
        /// 创建FileGDB和PGDB Workspace
        /// @remark
        /// 1.Shp创建Workspace没有意义
        /// 2.不支持SDE创建
        /// </summary>
        /// <param name="wsType"></param>
        /// <param name="strPath"></param>
        /// <param name="strName"></param>
        /// <returns></returns>
        public static IWorkspace CreateWorkspace(enumWorkspaceType wsType, string strPath, string strName)
        {
            try
            {
                IWorkspaceFactory wsf = null;
                switch (wsType)
                {
                case enumWorkspaceType.SDE:
                    throw new Exception("CreateWorkspace方法被设计为不支持SDE方式创建");

                case enumWorkspaceType.FileGDB:
                    wsf = new ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactoryClass();
                    break;

                case enumWorkspaceType.PGDB:
                    wsf = new AccessWorkspaceFactoryClass();
                    break;

                case enumWorkspaceType.File:
                    wsf = new ShapefileWorkspaceFactoryClass();
                    break;
                }
                IWorkspaceName wsName = wsf.Create(strPath, strName, null, 0);
                return((wsName as IName).Open() as IWorkspace);
            }
            catch
            {
                return(null);
            }
        }
Esempio n. 10
0
        //根据连接字符串获取工作空间
        //此处连接字符串是固定格式的连接串 Server|Service|Database|User|Password|Version
        private static IWorkspace GetWorkSpacefromConninfo(string conninfostr, int type)
        {
            if (conninfostr == "")
            {
                return(null);
            }
            if (type < 0)
            {
                return(null);
            }
            int               index1 = conninfostr.IndexOf("|");
            int               index2 = conninfostr.IndexOf("|", index1 + 1);
            int               index3 = conninfostr.IndexOf("|", index2 + 1);
            int               index4 = conninfostr.IndexOf("|", index3 + 1);
            int               index5 = conninfostr.IndexOf("|", index4 + 1);
            int               index6 = conninfostr.IndexOf("|", index5 + 1);
            IPropertySet      pPropSet = new PropertySetClass();
            IWorkspaceFactory pWSFact = null;
            string            sServer = ""; string sService = ""; string sDatabase = "";
            string            sUser = ""; string sPassword = ""; string strVersion = "";

            switch (type)
            {
            case 1:    //mdb
                pWSFact   = new AccessWorkspaceFactoryClass();
                sDatabase = conninfostr.Substring(index2 + 1, index3 - index2 - 1);
                break;

            case 2:    //gdb
                pWSFact   = new FileGDBWorkspaceFactoryClass();
                sDatabase = conninfostr.Substring(index2 + 1, index3 - index2 - 1);
                break;

            case 3:    //sde
                pWSFact    = new SdeWorkspaceFactoryClass();
                sServer    = conninfostr.Substring(0, index1);
                sService   = conninfostr.Substring(index1 + 1, index2 - index1 - 1);
                sDatabase  = conninfostr.Substring(index2 + 1, index3 - index2 - 1);
                sUser      = conninfostr.Substring(index3 + 1, index4 - index3 - 1);
                sPassword  = conninfostr.Substring(index4 + 1, index5 - index4 - 1);
                strVersion = conninfostr.Substring(index5 + 1, index6 - index5 - 1);
                break;
            }

            pPropSet.SetProperty("SERVER", sServer);
            pPropSet.SetProperty("INSTANCE", sService);
            pPropSet.SetProperty("DATABASE", sDatabase);
            pPropSet.SetProperty("USER", sUser);
            pPropSet.SetProperty("PASSWORD", sPassword);
            pPropSet.SetProperty("VERSION", strVersion);
            try
            {
                IWorkspace pWorkspace = pWSFact.Open(pPropSet, 0);
                return(pWorkspace);
            }
            catch
            {
                return(null);
            }
        }
Esempio n. 11
0
        public static IWorkspaceFactory2 GetWorkspaceFactory(enumDataType databaseType)
        {
            IWorkspaceFactory2 workspacefacory = null;

            switch (databaseType)
            {
            case enumDataType.PGDB:
            {
                workspacefacory = new AccessWorkspaceFactoryClass();
                break;
            }

            case enumDataType.FileGDB:
            {
                workspacefacory = new FileGDBWorkspaceFactoryClass();
                break;
            }

            case enumDataType.SHP:
            {
                workspacefacory = new ShapefileWorkspaceFactoryClass();
                break;
            }

            default:
            {
                return(null);
            }
            }
            return(workspacefacory);
        }
Esempio n. 12
0
        /// <summary>
        /// 创建FileGDB和PGDB Workspace
        /// @remark 
        /// 1.Shp创建Workspace没有意义
        /// 2.不支持SDE创建
        /// </summary>
        /// <param name="wsType"></param>
        /// <param name="strPath"></param>
        /// <param name="strName"></param>
        /// <returns></returns>
        public static IWorkspace CreateWorkspace(enumWorkspaceType wsType, string strPath, string strName)
        {
            try
            {
                IWorkspaceFactory wsf = null;
                switch (wsType)
                {
                    case enumWorkspaceType.SDE:
                        throw new Exception("CreateWorkspace方法被设计为不支持SDE方式创建");

                    case enumWorkspaceType.FileGDB:
                        wsf = new ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactoryClass();
                        break;

                    case enumWorkspaceType.PGDB:
                        wsf = new AccessWorkspaceFactoryClass();
                        break;

                    case enumWorkspaceType.File:
                        wsf = new ShapefileWorkspaceFactoryClass();
                        break;

                }
                IWorkspaceName wsName = wsf.Create(strPath, strName, null, 0);
                return (wsName as IName).Open() as IWorkspace;
            }
            catch
            {
                return null;
            }
        }
Esempio n. 13
0
        /// <summary>
        /// 作用:打开mdb文件并获取workspace
        /// 作者:汪建龙
        /// 编写时间:2017年4月11日15:39:36
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static IWorkspace OpenAccessFileWorkSpace(this string filePath)
        {
            IWorkspaceFactory workspaceFactory = new AccessWorkspaceFactoryClass();
            IWorkspace        workspace        = workspaceFactory.OpenFromFile(filePath, 0);

            return(workspace);
        }
Esempio n. 14
0
        public object GetWorkspace(string strType, string strArgs)
        {
            IWorkspaceFactory wsf = null;
            IWorkspace m_SystemWorkspace = null;
            switch (strType)
            {
                case "PGDB":
                    wsf = new AccessWorkspaceFactoryClass();
                    m_SystemWorkspace = wsf.OpenFromFile(strArgs, 0);
                    break;

                case "FILEGDB":
                    wsf = new ShapefileWorkspaceFactoryClass();
                    m_SystemWorkspace = wsf.OpenFromFile(strArgs, 0);
                    break;

                case "SDE":
                    IPropertySet pSet = new PropertySetClass();
                    string[] argList = strArgs.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string strArg in argList)
                    {
                        string[] argPair = strArg.Split(new char[] { ':' });
                        pSet.SetProperty(argPair[0], argPair[1]);
                    }
                    wsf = new SdeWorkspaceFactoryClass();
                    m_SystemWorkspace = wsf.Open(pSet, 0);
                    break;

                default:
                    throw new Exception("系统Workspace配置了无法识别的数据库:Workspace类型应该在PGDB、FILEGDB和SDE之内");
            }

            return m_SystemWorkspace;
        }
Esempio n. 15
0
        /// <summary>
        /// 打开本地模板工作空间
        /// </summary>
        /// <returns>返回模板工作空间</returns>
        private IWorkspace OpenTempleteWorkSpace()
        {
            string            PDBPath           = Application.StartupPath + "\\..\\CacheDB\\TempleteDatabase.mdb";
            IWorkspaceFactory pWorkspaceFactory = new AccessWorkspaceFactoryClass();

            return(pWorkspaceFactory.OpenFromFile(PDBPath, 0));
        }
Esempio n. 16
0
        public void AddLayer(string LayerName)
        {
            IMap FocusedMap = axMapControl1.ActiveView.FocusMap;
            IWorkspaceFactory AccessWorkSpace    = new AccessWorkspaceFactoryClass();
            IWorkspace        MyWorkSpace        = AccessWorkSpace.OpenFromFile(DBPath, 0);
            IFeatureWorkspace FeatureOfWorkSpace = MyWorkSpace as IFeatureWorkspace;
            IFeatureClass     FeatureClassOfLayer;


            try
            {
                FeatureClassOfLayer = FeatureOfWorkSpace.OpenFeatureClass(LayerName);
                IFeatureLayer LayerToBeAdded = new FeatureLayerClass();
                LayerToBeAdded.FeatureClass = FeatureClassOfLayer;
                LayerToBeAdded.Name         = LayerName;
                LayerToBeAdded.ShowTips     = true;
                FocusedMap.AddLayer(LayerToBeAdded);
                FocusedMap.MoveLayer(LayerToBeAdded, 2);



                if (!checkedListBox1.Items.Contains(LayerName))
                {
                    checkedListBox1.Items.Add(LayerName);
                    checkedListBox1.SetItemChecked(checkedListBox1.Items.Count - 1, true);
                    comboBox3.Items.Add(LayerName);
                    comboBox2.Items.Add(LayerName);
                    comboBox8.Items.Add(LayerName);
                }
            }
            catch
            {
            }
        }
Esempio n. 17
0
        /// <summary>
        /// 如果是文件库则需要创建辅助库体的pdb
        /// 重载构造函数

        /// </summary>
        /// <param name="MTpath">本地辅助库存放路径</param>
        public GOFuzingTables(string MTpath)
        {
            //创建PDB工作空间
            IWorkspaceFactory pWorkspaceFactory = new AccessWorkspaceFactoryClass();

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

            if (finfo.Exists)
            {
                SysCommon.Error.frmInformation frmInfo = new SysCommon.Error.frmInformation("是", "否", "存在同名的辅助库,是否进行替代?");
                if (frmInfo.ShowDialog() == DialogResult.OK)
                {
                    finfo.Delete();
                }
                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();
        }
Esempio n. 18
0
        /// <summary>
        /// 设置PDB、GDB工作区
        /// </summary>
        /// <param name="sFilePath">文件路径</param>
        /// <param name="wstype">工作区类型</param>
        /// <returns>输出错误Exception</returns>
        public bool SetWorkspace(string sFilePath, string type, out Exception eError)
        {
            eError = null;

            try
            {
                IPropertySet pPropSet = new PropertySetClass();
                switch (type)
                {
                case "PDB":
                    AccessWorkspaceFactory pAccessFact = new AccessWorkspaceFactoryClass();
                    pPropSet.SetProperty("DATABASE", sFilePath);
                    m_Workspace = pAccessFact.Open(pPropSet, 0);
                    pAccessFact = null;
                    m_connset   = "PDB;" + sFilePath;
                    break;

                case "GDB":
                    FileGDBWorkspaceFactoryClass pFileGDBFact = new FileGDBWorkspaceFactoryClass();
                    pPropSet.SetProperty("DATABASE", sFilePath);
                    m_Workspace  = pFileGDBFact.Open(pPropSet, 0);
                    pFileGDBFact = null;
                    m_connset    = "GDB;" + sFilePath;
                    break;
                }

                pPropSet = null;
                return(true);
            }
            catch (Exception eX)
            {
                return(false);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// 添加个人地理数据库
        /// </summary>
        public void addDataSet()
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.Title       = "请选择地理数据文件";
            openFileDialog1.Filter      = "个人数据库(*.mdb)|*.mdb";//设置过滤属性
            openFileDialog1.Multiselect = false;
            if (openFileDialog1.ShowDialog() != DialogResult.OK)
            {
                return;                                             //未选择文件return
            }
            string            fileName  = openFileDialog1.FileName; //获取到文件路径
            string            pFolder   = System.IO.Path.GetDirectoryName(fileName);
            string            pFileName = System.IO.Path.GetFileName(fileName);
            IWorkspaceFactory wsf       = new AccessWorkspaceFactoryClass();//打开数据库
            IWorkspace        ws        = wsf.OpenFromFile(fileName, 0);

            if (ws != null)
            {
                MessageBox.Show("个人数据库" + pFileName + "打开成功!");
                addDataSetMap(ws);
            }
            else
            {
                MessageBox.Show("个人数据库" + pFileName + "打开失败!");
            }
        }
Esempio n. 20
0
        public void LoadDB()
        {
            try
            {
                openFileDialog1            = new OpenFileDialog();
                openFileDialog1.Title      = "Browse mdb Files";
                openFileDialog1.DefaultExt = "mdb";
                openFileDialog1.Filter     = "mdb Diles (*.mdb)|*.mdb";
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    DBPath = openFileDialog1.FileName;;
                }

                IWorkspaceFactory AccessWorkSpace = new AccessWorkspaceFactoryClass();
                IWorkspace        MyWorkSpace     = AccessWorkSpace.OpenFromFile(DBPath, 0);
                IFeatureWorkspace featWorkspace   = MyWorkSpace as IFeatureWorkspace;

                IEnumDataset AllLayerFromDB = MyWorkSpace.get_Datasets(esriDatasetType.esriDTFeatureClass);
                IDataset     SingleLayer    = AllLayerFromDB.Next();
                while (SingleLayer != null)
                {
                    string LayerText = SingleLayer.Name;
                    comboBox12.Items.Add(LayerText);
                    SingleLayer = AllLayerFromDB.Next();
                }
                comboBox12.Text = comboBox12.Items[0].ToString();
            }
            catch
            {
            }
        }
Esempio n. 21
0
        private IWorkspace GetWorkspace(string sFilePath, int wstype)
        {
            IWorkspace pWks = null;

            try
            {
                IPropertySet pPropSet = new PropertySetClass();
                switch (wstype)
                {
                case 1:
                    AccessWorkspaceFactory pAccessFact = new AccessWorkspaceFactoryClass();
                    pPropSet.SetProperty("DATABASE", sFilePath);
                    pWks        = pAccessFact.Open(pPropSet, 0);
                    pAccessFact = null;
                    break;

                case 2:
                    FileGDBWorkspaceFactoryClass pFileGDBFact = new FileGDBWorkspaceFactoryClass();
                    pPropSet.SetProperty("DATABASE", sFilePath);
                    pWks         = pFileGDBFact.Open(pPropSet, 0);
                    pFileGDBFact = null;
                    break;

                case 3:
                    break;
                }
                pPropSet = null;
                return(pWks);
            }
            catch
            {
                return(null);
            }
        }
Esempio n. 22
0
        /// <summary>
        /// 获取GDB或MDB工作空间
        /// </summary>
        /// <param name="path">gdb或mdb数据库路径</param>
        /// <returns>gdb或mdb工作空间</returns>
        public static IWorkspace GetWorkspace(String path)
        {
            IWorkspaceFactory workspaceFactory;
            IWorkspace        workspace = null;

            try
            {
                if (path.EndsWith(".gdb"))
                {
                    workspaceFactory = new FileGDBWorkspaceFactoryClass();
                    workspace        = workspaceFactory.OpenFromFile(path, 0);
                }
                else if (path.EndsWith(".mdb"))
                {
                    workspaceFactory = new AccessWorkspaceFactoryClass();
                    workspace        = workspaceFactory.OpenFromFile(path, 0);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接到地理空间数据库失败:\r\n" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            return(workspace);
        }
Esempio n. 23
0
        private void testToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //打开目标数据库
            IWorkspaceFactory pAccessWorkspaceFactory;

            pAccessWorkspaceFactory = new AccessWorkspaceFactoryClass();
            IWorkspace        fWorkspace    = pAccessWorkspaceFactory.OpenFromFile("E://2018年工作//数据验收平台测试//test.gdb", 0);
            IFeatureWorkspace fW            = fWorkspace as IFeatureWorkspace;
            IEnumDataset      penumDatasets = fWorkspace.get_Datasets(esriDatasetType.esriDTFeatureDataset);

            penumDatasets.Reset();
            IDataset pesriDataset = penumDatasets.Next();

            while (pesriDataset == null)
            {
                IFeatureClass pFeatureClass = fW.OpenFeatureClass("Ⅰ级保护林地范围");
            }
            //启动编辑
            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)fWorkspace;

            workspaceEdit.StartEditing(true);
            workspaceEdit.StartEditOperation();
            //调用创建拓朴的方法
            ITopology topology = Create_Topology(fW, "datset", "Ⅰ级保护林地范围", "Polygon_Topo");

            //停止编辑
            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);
            if (topology != null)
            {
                MessageBox.Show("创建拓朴成功!");
            }
        }
Esempio n. 24
0
        /// <summary>
        /// 新建工作空间
        /// </summary>
        /// <param name="Location">路径名</param>
        /// <param name="Name">文件名</param>
        public bool CreateWorkspace(string Location, string Name)
        {
            string strSrcdb = Application.StartupPath + @"\..\Template\DataConvertTemplate.mdb";
            //string strCopyPath = Location + @"\" + Name;
            string strCopyPath = Location + Name;

            System.IO.FileInfo fSrcFile = new System.IO.FileInfo(strSrcdb);
            System.IO.FileInfo fileCopy = new System.IO.FileInfo(strCopyPath);
            if (fSrcFile.Exists)
            {
                if (!fileCopy.Exists)
                {
                    fSrcFile.CopyTo(strCopyPath);
                }
                else
                {
                    MessageBox.Show("数据库重名!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return(false);
                }
            }
            else
            {
                IWorkspaceFactory pWorkspaceFactory = new AccessWorkspaceFactoryClass();
                pWorkspaceFactory.Create(Location, Name, null, 0);
            }

            return(true);
        }
Esempio n. 25
0
        /// <summary>
        /// Converts string to Workspace
        /// </summary>
        /// <param name="s">The connection string  for geodatabase</param>
        /// <returns>geodatabase IWorkspace </returns>
        public static IWorkspace ToWorkspace(this string s)
        {
            IWorkspace workspace = null;

            try
            {
                if (s.EndsWith("sde", StringComparison.CurrentCultureIgnoreCase))
                {
                    IWorkspaceFactory factory = new SdeWorkspaceFactoryClass();
                    workspace = factory.OpenFromFile(s, 0);
                }
                else if (s.EndsWith("gdb", StringComparison.CurrentCultureIgnoreCase))
                {
                    IWorkspaceFactory factory = new FileGDBWorkspaceFactoryClass();
                    workspace = factory.OpenFromFile(s, 0);
                }
                else if (s.EndsWith("mdb", StringComparison.CurrentCultureIgnoreCase))
                {
                    IWorkspaceFactory factory = new AccessWorkspaceFactoryClass();
                    workspace = factory.OpenFromFile(s, 0);
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine(e.StackTrace);
                Console.WriteLine(e.Message);
            }

            return(workspace);
        }
Esempio n. 26
0
        public object GetWorkspace(string strType, string strArgs)
        {
            IWorkspaceFactory wsf = null;
            IWorkspace        m_SystemWorkspace = null;

            switch (strType)
            {
            case "PGDB":
                wsf = new AccessWorkspaceFactoryClass();
                m_SystemWorkspace = wsf.OpenFromFile(strArgs, 0);
                break;

            case "FILEGDB":
                wsf = new ShapefileWorkspaceFactoryClass();
                m_SystemWorkspace = wsf.OpenFromFile(strArgs, 0);
                break;

            case "SDE":
                IPropertySet pSet    = new PropertySetClass();
                string[]     argList = strArgs.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string strArg in argList)
                {
                    string[] argPair = strArg.Split(new char[] { ':' });
                    pSet.SetProperty(argPair[0], argPair[1]);
                }
                wsf = new SdeWorkspaceFactoryClass();
                m_SystemWorkspace = wsf.Open(pSet, 0);
                break;

            default:
                throw new Exception("系统Workspace配置了无法识别的数据库:Workspace类型应该在PGDB、FILEGDB和SDE之内");
            }

            return(m_SystemWorkspace);
        }
Esempio n. 27
0
 public bool CompactPersonalGeodatabase(string sPGDBFile)
 {
     try
     {
         if (string.IsNullOrEmpty(sPGDBFile) | !File.Exists(sPGDBFile))
         {
             MessageBox.Show("数据文件 " + sPGDBFile + " 丢失。", "压缩数据错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
             return(false);
         }
         bool flag = false;
         IWorkspaceFactory factory = null;
         factory = new AccessWorkspaceFactoryClass();
         IWorkspace workspace = null;
         workspace = factory.OpenFromFile(sPGDBFile, 0);
         if ((workspace != null) && (workspace is IDatabaseCompact))
         {
             IDatabaseCompact compact = null;
             compact = workspace as IDatabaseCompact;
             if (compact.CanCompact())
             {
                 compact.Compact();
                 flag = true;
             }
         }
         workspace = null;
         factory   = null;
         return(flag);
     }
     catch (Exception exception)
     {
         this.mErrOpt.ErrorOperate(this.mSubSysName, "FunFactory.WorkspaceFun", "CompactPersonalGeodatabase", exception.GetHashCode().ToString(), exception.Source, exception.Message, "", "", "");
         return(false);
     }
 }
Esempio n. 28
0
        /// <summary>
        /// Converts  the spatialite table to a featureclass in a temporary, scratch workspace.
        /// </summary>
        /// <returns>IFeatureClass copy of the spatialite table</returns>
        public IFeatureClass ConvertToFeatureclass()
        {
            try
            {
                CreateTemporaryGeodatabase();

                IWorkspaceFactory factory   = new AccessWorkspaceFactoryClass();
                IWorkspace        workspace = factory.OpenFromFile(this.PGDBPath, 0);

                IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;

                IFields fields = CreateFields();

                // Use IFieldChecker to create a validated fields collection.
                IFieldChecker   fieldChecker    = new FieldCheckerClass();
                IEnumFieldError enumFieldError  = null;
                IFields         validatedFields = null;
                fieldChecker.ValidateWorkspace = (IWorkspace)featureWorkspace;
                fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

                IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(this.TableName, validatedFields,
                                                                                 null, null, esriFeatureType.esriFTSimple, "Shape", "");

                LoadFeatureclass(featureClass);

                return(featureClass);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.StackTrace);
                throw;
            }
        }
Esempio n. 29
0
        private void btnSetDataSourcePath_Click(object sender, EventArgs e)
        {
            string sDir = Application.StartupPath;

            System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
            openFileDialog.InitialDirectory = sDir + @"\..\Result\";
            openFileDialog.Filter           = "mdb|*.mdb";
            openFileDialog.Title            = "请选择数据库";

            if (openFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            string strFileName = openFileDialog.FileName;

            IDataLayer   pDataLayer          = (IDataLayer)m_FeaLay;
            IName        pName               = pDataLayer.DataSourceName;
            IDatasetName pDatasetName        = pName as IDatasetName;
            string       strFeatureClassName = pDatasetName.Name;

            IWorkspaceFactory pFact      = new AccessWorkspaceFactoryClass();
            IWorkspace        pWorkspace = pFact.OpenFromFile(strFileName, 0);
            IFeatureWorkspace pFeatws    = pWorkspace as IFeatureWorkspace;
            IFeatureClass     pFeatcls   = pFeatws.OpenFeatureClass(strFeatureClassName);

            m_FeaLay.FeatureClass = pFeatcls;
        }
        /// <summary>
        /// 打开工作空间
        /// </summary>
        public IWorkspace OpenWorkspace(string strMDBName)
        {
            IWorkspaceFactory workspaceFactory;

            workspaceFactory = new AccessWorkspaceFactoryClass();
            return(workspaceFactory.OpenFromFile(strMDBName, 0));
        }
Esempio n. 31
0
        /// <summary>
        /// 打开mdb
        /// </summary>
        /// <param name="pGDBName"></param>
        /// <returns></returns>
        public static ESRI.ArcGIS.Geodatabase.IWorkspace GetMDBWorkspace(String _pGDBName)
        {
            IWorkspaceFactory pWsFac = new AccessWorkspaceFactoryClass();
            IWorkspace        pWs    = pWsFac.OpenFromFile(_pGDBName, 0);

            return(pWs);
        }
        //读取mdb数据
        public List <ILayer> ReadLayerFromAccess(List <string> filePathList)
        {
            List <ILayer> layerList = new List <ILayer>();

            if (filePathList.Count == 0)
            {
                return(null);
            }
            else
            {
                foreach (string path in filePathList)
                {
                    IWorkspaceFactory pWorkspaceFactory = new AccessWorkspaceFactoryClass();
                    IWorkspace        pWorkspace        = pWorkspaceFactory.OpenFromFile(path, 0);
                    IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;

                    IEnumDataset pEnumDataset = pWorkspace.get_Datasets(esriDatasetType.esriDTFeatureClass) as IEnumDataset;
                    pEnumDataset.Reset();
                    IDataset pDataset = pEnumDataset.Next();

                    while (pDataset is IFeatureClass)
                    {
                        IFeatureLayer pFeatureLayer = new FeatureLayerClass();
                        pFeatureLayer.FeatureClass = pFeatureWorkspace.OpenFeatureClass(pDataset.Name);
                        pFeatureLayer.Name         = pDataset.Name;
                        ILayer pLayer = pFeatureLayer as ILayer;
                        layerList.Add(pFeatureLayer as ILayer);
                        pDataset = pEnumDataset.Next();
                    }
                }
                return(layerList);
            }
        }
Esempio n. 33
0
 /// <summary>
 /// 打开MDB工作空间
 /// </summary>
 /// <param name="strFilePath"></param>
 /// <returns></returns>
 public static IWorkspace OpenMdbWorspace(string strFilePath)
 {
     if (strFilePath == string.Empty)
     {
         LOG.Error("参数strFilePath不能为空");
         throw new Exception("参数strFilePath不能为空");
     }
     try
     {
         IWorkspaceFactory2 pWrksFactory = new AccessWorkspaceFactoryClass();
         //int index = strFilePath.LastIndexOf('\\');
         //string strDic = strFilePath.Substring(0, index);
         //string strName = strFilePath.Substring(index + 1, strFilePath.Length - index - 1);
         //IWorkspaceName pWrkspsName = pWrksFactory.Create(strDic, strName, null, 0);
         //IWorkspace pWrksps = ((IName)pWrkspsName).Open() as IWorkspace;
         return(pWrksFactory.OpenFromFile(strFilePath, 0));
         //return pWrksps;
     }
     catch (Exception ex)
     {
         LOG.Error("mdb工作空间打开失败,详情:" + ex.Message);
         // Console.WriteLine("创建mdb工作空间失败,详情:" + ex.Message);
         return(null);
     }
 }
        //
        // CONSTRUCTOR
        //
        public PersonalGeodatabaseValidator() : base() {
            string tempPath = Path.GetTempPath();
            string name = Guid.NewGuid().ToString("N").ToUpper();

            IWorkspaceFactory workspaceFactory = new AccessWorkspaceFactoryClass();
            IWorkspaceName workspaceName = workspaceFactory.Create(tempPath, name, null, 0);
            IWorkspace workspace = (IWorkspace)((IName)workspaceName).Open();
            this.SetWorkspace(workspace);
        }
        private void EngineEditingForm_Load(object sender, EventArgs e)
        {
           
            //Set buddy controls
            axTOCControl1.SetBuddyControl(axMapControl1);
            axEditorToolbar.SetBuddyControl(axMapControl1);
            axToolbarControl1.SetBuddyControl(axMapControl1);

            //Add items to the ToolbarControl
            axToolbarControl1.AddItem("esriControls.ControlsOpenDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axToolbarControl1.AddItem("esriControls.ControlsSaveAsDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axToolbarControl1.AddItem("esriControls.ControlsAddDataCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);            
            axToolbarControl1.AddItem("esriControls.ControlsMapZoomInTool", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axToolbarControl1.AddItem("esriControls.ControlsMapZoomOutTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axToolbarControl1.AddItem("esriControls.ControlsMapPanTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axToolbarControl1.AddItem("esriControls.ControlsMapFullExtentCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axToolbarControl1.AddItem("esriControls.ControlsMapZoomToLastExtentBackCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axToolbarControl1.AddItem("esriControls.ControlsMapZoomToLastExtentForwardCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
           
            //Add items to the custom editor toolbar          
            axEditorToolbar.AddItem("esriControls.ControlsEditingEditorMenu", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axEditorToolbar.AddItem("esriControls.ControlsEditingEditTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axEditorToolbar.AddItem("esriControls.ControlsEditingSketchTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axEditorToolbar.AddItem("esriControls.ControlsUndoCommand", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axEditorToolbar.AddItem("esriControls.ControlsRedoCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axEditorToolbar.AddItem("esriControls.ControlsEditingTargetToolControl", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axEditorToolbar.AddItem("esriControls.ControlsEditingTaskToolControl", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly);
           
            //Create a popup menu
            m_toolbarMenu = new ToolbarMenuClass();
            m_toolbarMenu.AddItem("esriControls.ControlsEditingSketchContextMenu", 0, 0, false, esriCommandStyles.esriCommandStyleTextOnly);

            //share the command pool
            axToolbarControl1.CommandPool = axEditorToolbar.CommandPool;
            m_toolbarMenu.CommandPool = axEditorToolbar.CommandPool;

            //Create an operation stack for the undo and redo commands to use
            IOperationStack operationStack = new ControlsOperationStackClass();
            axEditorToolbar.OperationStack = operationStack;

            //add some sample line data to the map
            IWorkspaceFactory workspaceFactory = new AccessWorkspaceFactoryClass();
            //relative file path to the sample data from EXE location            
            string filePath = @"..\..\..\..\data\StreamflowDateTime\Streamflow.mdb";
            
            IFeatureWorkspace workspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(filePath, axMapControl1.hWnd);

            //Add a polygon layer
            IFeatureLayer featureLayer1 = new FeatureLayerClass();
            featureLayer1.Name = "Watershed";
            featureLayer1.Visible = true;
            featureLayer1.FeatureClass = workspace.OpenFeatureClass("Watershed");
            axMapControl1.Map.AddLayer((ILayer)featureLayer1);
        }
Esempio n. 36
0
File: Home.cs Progetto: gistop/aegis
 private void AddMDB()
 {
     string filePath = "C:\\temp\\mdb.mdb";
     AccessWorkspaceFactory fac = new AccessWorkspaceFactoryClass();
     IFeatureWorkspace space = (IFeatureWorkspace)fac.OpenFromFile(filePath, 0);
     IFeatureClass featureclass = space.OpenFeatureClass("layer");
     IFeatureLayer pFLRoads = new FeatureLayer();
     pFLRoads.FeatureClass = featureclass;
     pFLRoads.Name = "点";
     ILayer pLayerRoads = pFLRoads as ILayer;
     Global.mainmap.AddLayer(pLayerRoads);
 }
Esempio n. 37
0
        /// <summary>
        /// 打开Workspace
        /// </summary>
        /// <param name="wsType"></param>
        /// <param name="objWorkspace">当为SDE时使用IPropertySet,其余情况使用路径(string)</param>
        /// <returns></returns>
        public static IWorkspace OpenWorkspace(enumWorkspaceType wsType, object objWorkspace)
        {
            IWorkspaceFactory wsf = null;
            try
            {
                switch (wsType)
                {
                    case enumWorkspaceType.FileGDB:
                        wsf = new FileGDBWorkspaceFactoryClass();

                        return wsf.OpenFromFile(objWorkspace as string, 0);

                    case enumWorkspaceType.PGDB:
                        wsf = new AccessWorkspaceFactoryClass();
                        return wsf.OpenFromFile(objWorkspace as string, 0);

                    case enumWorkspaceType.File:
                        wsf = new ShapefileWorkspaceFactoryClass();
                        return wsf.OpenFromFile(objWorkspace as string, 0);

                    case enumWorkspaceType.SDE:
                        wsf = new SdeWorkspaceFactoryClass();
                        IPropertySet pSet = objWorkspace as IPropertySet;
                        if (pSet == null)
                        {
                            string strArgs = objWorkspace as string;
                            pSet = new PropertySetClass();
                            string[] argList = strArgs.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string strArg in argList)
                            {
                                string[] argPair = strArg.Split(new char[] { '=' });
                                pSet.SetProperty(argPair[0], argPair[1]);
                            }
                        }

                        return wsf.Open(pSet, 0);
                }
            }
            catch
            {
                return null;
            }
            finally
            {
                if (wsf != null)
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wsf);
            }

            return null;
        }
 public static IWorkspace GetAccessWorkspace(string sFilePath)
 {
     if (!File.Exists(sFilePath))
     {
         return null;
     }
     try
     {
         IWorkspaceFactory factory = new AccessWorkspaceFactoryClass();
         return factory.OpenFromFile(sFilePath, 0);
     }
     catch
     {
         return null;
     }
 }
Esempio n. 39
0
 /// <summary>
 /// ����GDB����Դ
 /// </summary>
 public IWorkspace ConnectWorkspace()
 {
     IWorkspaceFactory factory = new AccessWorkspaceFactoryClass();
     try
     {
         return factory.OpenFromFile(m_strFilePathName, 0);
     }
     catch (Exception ex)
     {
         //ProjectData.SetProjectError(exception1);
         Logger.WriteErrorLog(ex);
         //ProjectData.ClearProjectError();
     }
     return null;
 }
		public static void Main(string[] args)
		{
			#region Licensing
            ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
			IAoInitialize aoInitialize = new AoInitializeClass();
			esriLicenseStatus licenseStatus = aoInitialize.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced);
			if (licenseStatus != esriLicenseStatus.esriLicenseCheckedOut)
			{
				MessageBox.Show("An Advanced License could not be checked out.");
				return;
			}
			#endregion

			try
			{
				// Open the workspace.
				IWorkspaceFactory workspaceFactory = null;
				switch (geodatabaseType)
				{
					case GeodatabaseType.ArcSDE:
						workspaceFactory = new SdeWorkspaceFactoryClass();
						break;
					case GeodatabaseType.FileGDB:
						workspaceFactory = new FileGDBWorkspaceFactoryClass();
						break;
					case GeodatabaseType.PersonalGDB:
						workspaceFactory = new AccessWorkspaceFactoryClass();
						break;
				}
				IWorkspace workspace = workspaceFactory.OpenFromFile(workspacePath, 0);
				IWorkspaceExtensionManager workspaceExtensionManager = (IWorkspaceExtensionManager)workspace;

				// Create a UID for the workspace extension.
				UID uid = new UIDClass();
				uid.Value = extensionGuid;

                // Determine whether there are any existing geodatabase-register extensions.
				// To disambiguate between GDB-register extensions and component category extensions,
				// check the extension count of a new scratch workspace.
				IScratchWorkspaceFactory scratchWorkspaceFactory = new FileGDBScratchWorkspaceFactoryClass();
				IWorkspace scratchWorkspace = scratchWorkspaceFactory.CreateNewScratchWorkspace();
				IWorkspaceExtensionManager scratchExtensionManager = (IWorkspaceExtensionManager)scratchWorkspace;
				Boolean workspaceExtensionApplied = false;
				UID gdbRegisteredUID = null;
				try
				{
					workspaceExtensionApplied = (workspaceExtensionManager.ExtensionCount > scratchExtensionManager.ExtensionCount);
				}
				catch (COMException comExc)
				{
					// This is necessary in case the existing extension could not be initiated.
					if (comExc.ErrorCode == (int)fdoError.FDO_E_WORKSPACE_EXTENSION_CREATE_FAILED)
					{
						// Parse the error message for the current extension's GUID.
						Regex regex = new Regex("(?<guid>{[^}]+})");
						MatchCollection matchCollection = regex.Matches(comExc.Message);
						if (matchCollection.Count > 0)
						{
							Match match = matchCollection[0];
							gdbRegisteredUID = new UIDClass();
							gdbRegisteredUID.Value = match.Groups["guid"].Value;
							workspaceExtensionApplied = true;
						}
						else
						{
							throw comExc;
						}
					}
					else
					{
						throw comExc;
					}
				}

				if (workspaceExtensionApplied)
				{
					if (gdbRegisteredUID == null)
					{
						// There is GDB-registered extension on the SDE workspace. Find the SDE extension that is not
						// applied to the scratch workspace. 
						for (int i = 0; i < workspaceExtensionManager.ExtensionCount; i++)
						{
							IWorkspaceExtension workspaceExtension = workspaceExtensionManager.get_Extension(i);
							IWorkspaceExtension scratchExtension = scratchExtensionManager.FindExtension(workspaceExtension.GUID);
							if (scratchExtension == null)
							{
								gdbRegisteredUID = workspaceExtension.GUID;
							}
						}
					}
				}

				// If the extension could be located, remove it.
				if (gdbRegisteredUID != null)
				{
					workspaceExtensionManager.UnRegisterExtension(gdbRegisteredUID);
				}

				// Register the extension.
				workspaceExtensionManager.RegisterExtension("RasterSyncExtension.RasterSyncWorkspaceExtension", uid);
			}
			catch (COMException comExc)
			{
				switch (comExc.ErrorCode)
				{
					case (int)fdoError.FDO_E_WORKSPACE_EXTENSION_NO_REG_PRIV:
						MessageBox.Show("The connection file's privileges are insufficient to perform this operation.",
							"Register Workspace Extension", MessageBoxButtons.OK, MessageBoxIcon.Error);
						break;
					case (int)fdoError.FDO_E_WORKSPACE_EXTENSION_CREATE_FAILED:
						String createErrorMessage = String.Concat("The workspace extension could not be created.",
							Environment.NewLine, "Ensure that it has been registered for COM Interop.");
						MessageBox.Show(createErrorMessage, "Register Workspace Extension", MessageBoxButtons.OK, MessageBoxIcon.Error);
						break;
					case (int)fdoError.FDO_E_WORKSPACE_EXTENSION_DUP_GUID:
					case (int)fdoError.FDO_E_WORKSPACE_EXTENSION_DUP_NAME:
						String dupErrorMessage = String.Concat("A duplicate name or GUID was detected. Make sure any existing GDB-registered",
							"workspaces are not component category-registered as well.");
						MessageBox.Show(dupErrorMessage, "Register Workspace Extension", MessageBoxButtons.OK, MessageBoxIcon.Error);
						break;
					default:
						String otherErrorMessage = String.Format("An unexpected error has occurred:{0}{1}{2}", Environment.NewLine, comExc.Message,
							comExc.ErrorCode);
						MessageBox.Show(otherErrorMessage);
						break;
				}
			}
			catch (Exception exc)
			{
				String errorMessage = String.Format("An unexpected error has occurred:{0}{1}", Environment.NewLine, exc.Message);
				MessageBox.Show(errorMessage);
			}

			// Shutdown the AO initializer.
			aoInitialize.Shutdown();
		}
Esempio n. 41
0
        //IFeatureClass ITnExToolsDataManager.TnOpenFeatureClassFromFileMdb(string pathNoEnd, string name)
        //{
        //    IWorkspaceFactory2 mdbWspf = new AccessWorkspaceFactoryClass();
        //    IWorkspace wsp;
        //    IFeatureWorkspace fwsp;
        //    wsp = mdbWspf.OpenFromFile(pathNoEnd, 0);
        //    fwsp = (IFeatureWorkspace)wsp;
        //    return fwsp.OpenFeatureClass(name);
        //}
        IFeatureClass IDataManager.TnOpenFeatureClassFromFileMdb(params string[] fullpathOrPathandname)
        {
            IWorkspaceFactory2 mdbWspf = new AccessWorkspaceFactoryClass();
               IWorkspace wsp;
               IFeatureWorkspace fwsp;
               int i = fullpathOrPathandname.Length;
               string pathNoEnd = "";
               string name = "";
               int j = 0;
               if (i == 2)
               {
               pathNoEnd = fullpathOrPathandname[0];
               name = fullpathOrPathandname[1];
               }
               else if(i==1)
               {
               for (j = fullpathOrPathandname[0].Length-1; j > 0; j--)
               {
                   if (fullpathOrPathandname[0][j].CompareTo(System.Char.Parse("/"))==0)
                   {
                       break;
                   }
               }
               pathNoEnd = fullpathOrPathandname[0].Substring(0, j);
               name = fullpathOrPathandname[0].Substring(j + 1, fullpathOrPathandname[0].Length - 1 - j);
               }

               wsp = mdbWspf.OpenFromFile(pathNoEnd, 0);
               fwsp = (IFeatureWorkspace)wsp;
               return fwsp.OpenFeatureClass(name);
        }
Esempio n. 42
0
        public static void ExportDatabase(IWorkspace theWorkspace)
        {
            // Try and make sure the user understands what they're doing
            MessageBox.Show("You must first browse to a previously generated, empty geodatabase.", "NCGMP Tools");

            // Browse for a file, personal or SDE geodatabase
            IWorkspaceFactory wsFact = null;
            IWorkspace openedWorkspace = null;

            IGxObjectFilter objectFilter = new GxFilterWorkspaces();
            IGxObject openedObject = commonFunctions.OpenArcFile(objectFilter, "Please select an empty database");
            if (openedObject == null) { return; }

            // Check to see if it is a File, Personal or SDE database, create appropriate workspace factory
            string pathToOpen = null;

            switch (openedObject.Category)
            {
                case "Personal Geodatabase":
                    wsFact = new AccessWorkspaceFactoryClass();
                    pathToOpen = openedObject.FullName;
                    break;
                case "File Geodatabase":
                    wsFact = new FileGDBWorkspaceFactoryClass();
                    pathToOpen = openedObject.FullName;
                    break;
                case "Spatial Database Connection":
                    wsFact = new SdeWorkspaceFactoryClass();
                    IGxRemoteDatabaseFolder remoteDatabaseFolder = (IGxRemoteDatabaseFolder)openedObject.Parent;
                    pathToOpen = remoteDatabaseFolder.Path + openedObject.Name;
                    break;
                default:
                    break;
            }
            openedWorkspace = wsFact.OpenFromFile(pathToOpen, 0);

            // Okay, now export the current database to an XML doc
            string tempFilePath = System.IO.Path.GetTempFileName();
            tempFilePath += ".xml";

            IGdbXmlExport xmlExporter = new GdbExporterClass();
            xmlExporter.ExportWorkspace(theWorkspace, tempFilePath, true, false, false);

            // Import to the new database
            // Use the temp file to perform the import
            IGdbXmlImport xmlImporter = new GdbImporterClass();
            IEnumNameMapping enumNameMapping = null;
            bool conflictsFound = xmlImporter.GenerateNameMapping(tempFilePath, openedWorkspace, out enumNameMapping);

            try
            {
                // Deal with conflicts (lifted wholesale from http://help.arcgis.com/en/sdk/10.0/arcobjects_net/conceptualhelp/index.html#/d/00010000011m000000.htm)
                if (conflictsFound)
                {
                    IName workspaceName = ((IDataset)openedWorkspace).FullName;

                    // Iterate through each name mapping.
                    INameMapping nameMapping = null;
                    enumNameMapping.Reset();
                    while ((nameMapping = enumNameMapping.Next()) != null)
                    {
                        // Resolve the mapping's conflict (if there is one).
                        if (nameMapping.NameConflicts)
                        {
                            nameMapping.TargetName = nameMapping.GetSuggestedName(workspaceName);
                        }
                        // See if the mapping's children have conflicts.
                        IEnumNameMapping childEnumNameMapping = nameMapping.Children;
                        if (childEnumNameMapping != null)
                        {
                            childEnumNameMapping.Reset();
                            // Iterate through each child mapping.
                            INameMapping childNameMapping = null;
                            while ((childNameMapping = childEnumNameMapping.Next()) != null)
                            {
                                if (childNameMapping.NameConflicts)
                                {
                                    childNameMapping.TargetName = nameMapping.GetSuggestedName
                                        (workspaceName);
                                }
                            }
                        }
                    }
                }

                // Perform the import
                xmlImporter.ImportWorkspace(tempFilePath, enumNameMapping, openedWorkspace, false);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + Environment.NewLine + "XML Workspace Doc written to: " + tempFilePath);
            }

            // Perhaps, strip the SysInfo table
        }
Esempio n. 43
0
        private void mnuSourceD_Click(object sender, EventArgs e)
        {
            int FCount;
            DirectoryInfo[] instDirs;
            IWorkspaceFactory theWSFact;
            IWorkspace theWS;
            IFeatureWorkspace theFWS;
            IFeatureClass theFClass;
            // get the directory that is to be scanned for Shapefiles or Geodatabases

            DialogResult theAns;
            FolderBrowserDialog DirBrowserDlg = new FolderBrowserDialog();
            DirBrowserDlg.RootFolder = Environment.SpecialFolder.MyComputer;

            DirBrowserDlg.Description = "Select the Parent Folder containing Geospatial Items.";

            theAns = DirBrowserDlg.ShowDialog();

            if (theAns == DialogResult.OK)
            {
                DirectoryInfo iDir = new DirectoryInfo(DirBrowserDlg.SelectedPath);

                try
                {
                    instDirs = iDir.GetDirectories();

                    foreach (DirectoryInfo theDir in instDirs)
                    {
                    }

                    foreach (FileInfo theFile in iDir.GetFiles("*.mdb"))
                    {
                        theWSFact = new AccessWorkspaceFactoryClass();

                        theWS = theWSFact.OpenFromFile(theFile.FullName, 0);

                        String[] theSrcNames = GeoDbProcs.GetFeatureClassNames(srcWrkSpc);

                        foreach (String theSrcName in theSrcNames)
                        {
                            theFWS = (IFeatureWorkspace)theWS;
                            theFClass = theFWS.OpenFeatureClass(theSrcName);
                            lbSource.Items.Add(new FeatureData(theSrcName, theFClass));
                            Application.DoEvents();
                        }
                        CheckforGeoSpatialData(iDir.FullName, "ShapeFile", lbSource);
                    }
                }
                catch (Exception ex) { }
            }
        }
Esempio n. 44
0
        private void txtfolder_Click(object sender, EventArgs e)
        {
            bool cancel = true;
            switch (m_DataType)
            {
                case enumDataType.VCT:
                    dlgSourceFile.Filter = "VCT�ļ�|*.VCT";
                    dlgSourceFile.FileName = txtDatasource.Text;
                    if (dlgSourceFile.ShowDialog() == DialogResult.OK)
                    {
                        txtDatasource.Text = dlgSourceFile.FileName;
                        cancel = false;
                    }
                    break;

                case enumDataType.FileGDB:
                case enumDataType.SHP:
                    dlgSourceFolder.SelectedPath = txtDatasource.Text;
                    if (dlgSourceFolder.ShowDialog() == DialogResult.OK)
                    {
                        txtDatasource.Text = dlgSourceFolder.SelectedPath;
                        cancel = false;
                    }
                    break;

                case enumDataType.PGDB:
                    dlgSourceFile.Filter = "PGDB(MDB)�ļ�|*.MDB";
                    dlgSourceFile.FileName = txtDatasource.Text;
                    if (dlgSourceFile.ShowDialog() == DialogResult.OK)
                    {
                        txtDatasource.Text = dlgSourceFile.FileName;
                        cancel = false;
                    }
                    break;

                default:
                    break;
            }
            if (string.IsNullOrEmpty(txtDatasource.Text))
            {
                dxErrorProvider.SetError(txtDatasource, "����Դ·������Ϊ��");
            }
            else
            {
                dxErrorProvider.SetError(txtDatasource, null);
            }

            if (cancel)
                return;

            if (m_DataType != enumDataType.VCT)
            {
                try
                {
                    // �ռ�ο��б�
                    m_DicSpatialReference = new Dictionary<string, ISpatialReference>();
                    cmbSpatialRefLayer.Properties.Items.Clear();
                    IWorkspaceFactory wsFactory = null;
                    switch (m_DataType)
                    {
                        case enumDataType.FileGDB:
                            wsFactory = new FileGDBWorkspaceFactoryClass();
                            break;
                        case enumDataType.SHP:
                            wsFactory = new ShapefileWorkspaceFactoryClass();
                            break;

                        case enumDataType.PGDB:
                            wsFactory = new AccessWorkspaceFactoryClass();
                            break;
                        default:
                            break;
                    }
                    IWorkspace wsSource = wsFactory.OpenFromFile(txtDatasource.Text, 0);
                    IEnumDataset enDataset = wsSource.get_Datasets(esriDatasetType.esriDTAny);
                    IDataset ds = enDataset.Next();

                    while (ds != null)
                    {
                        IGeoDataset geoDs = ds as IGeoDataset;
                        if (geoDs != null)
                        {
                            cmbSpatialRefLayer.Properties.Items.Add(ds.Name);
                            m_DicSpatialReference.Add(ds.Name, geoDs.SpatialReference);
                        }
                        ds = enDataset.Next();
                    }

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wsSource);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wsFactory);
                    wsSource = null;
                    wsFactory = null;
                    GC.Collect();

                }
                catch
                {
                    MessageBoxApi.ShowErrorMessageBox("ѡ�������Դ����ȷ��������Դ��û�пռ����ݣ�");
                    txtDatasource.Text = "";
                }

                if (cmbSpatialRefLayer.Properties.Items.Count == 0)
                {
                    MessageBoxApi.ShowErrorMessageBox("ѡ�������Դ����ȷ��������Դ��û�пռ����ݣ�");
                    //dxErrorProvider.SetError(txtDatasource, "��ǰ����Դ��û�пռ�����", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning);
                    txtDatasource.Text = "";
                }
                else
                {
                    dxErrorProvider.SetError(txtDatasource, null);
                    cmbSpatialRefLayer.SelectedIndex = 0;
                }
            }
        }
Esempio n. 45
0
 //
 //
 //
 public static IFeatureWorkspace openPDB(string filePath)
 {
     try
     {
         IWorkspaceFactory pWSF = new AccessWorkspaceFactoryClass();
         IFeatureWorkspace pFWS;
         IPropertySet pPropset = new PropertySetClass();
         pPropset.SetProperty("DATABASE", filePath);
         pFWS = pWSF.Open(pPropset, 0) as IFeatureWorkspace;
         return pFWS;
     }
     catch (Exception e)
     {
         MessageBox.Show(e.Message);
         return null;
     }
 }
Esempio n. 46
0
        /// <summary>
        /// Create a workspace for a FGDB or PGDB
        /// </summary>
        /// <param name="path"></param>
        /// <param name="gdbType"></param>
        /// <returns></returns>
        private IWorkspace createGDBWorkspace(string path, string gdbType)
        {
            _log.Debug("Misc createGDBWorkspace");
              string fullPath = "";
              string[] connectionProperties = tokenizeConnectionProperties(path);

              if (connectionProperties == null)
              throw new ArgumentNullException("The connection properties are null.");

              if (connectionProperties.Length > 0)
              {
              fullPath = connectionProperties[0];
              try
              {
                  string[] pathArray = fullPath.Split('=');

                  // Get the path to the locator
                  if (pathArray.Length == 2)
                  {
                      fullPath = pathArray[1].TrimEnd(')');
                      fullPath = fullPath.Trim();
                  }
              }
              catch (Exception e)
              {
                  throw new Exception("Error parsing LocatorWorkspaceString.", e);
              }
              }

              IWorkspaceFactory workspaceFactory;

              if (gdbType.ToLower() == "mdb")
              workspaceFactory = new AccessWorkspaceFactoryClass();
              else if (gdbType.ToLower() == "gdb")
              workspaceFactory = new FileGDBWorkspaceFactoryClass();
              else
              throw new ArgumentException("Expected GDB Type equal to 'mdb' or 'gdb'.");

              return workspaceFactory.OpenFromFile(fullPath, 0);
        }
Esempio n. 47
0
        public void CheckforGeoSpatialData(String strPath, String geoType, ListBox lstBox)
        {
            IWorkspaceFactory owrkspaceFact = null;
            IFeatureWorkspace theFWS;
            IFeatureClass theFClass;
            int FCount;

            try
            {
                switch (geoType)
                {
                    case "ShapeFile":
                        owrkspaceFact = new ShapefileWorkspaceFactory();
                        break;
                    default:
                        owrkspaceFact = new AccessWorkspaceFactoryClass();
                        break;
                }

                PropertySet pPropSet = new PropertySetClass();
                pPropSet.SetProperty("DATABASE", strPath);

                IWorkspace theWS = owrkspaceFact.Open(pPropSet, 0);
                theFWS = (IFeatureWorkspace)theWS;

                if (theWS != null)
                {
                    String[] theSrcNames = GeoDbProcs.GetFeatureClassNames(theWS);

                    foreach (String theSrcName in theSrcNames)
                    {
                        theFClass = theFWS.OpenFeatureClass(theSrcName);
                        lbSource.Items.Add(new FeatureData(theSrcName, theFClass));
                        Application.DoEvents();
                    }
                }
            }
            catch { }
        }
Esempio n. 48
0
 public void ExportToMDB(string name, string outputPath)
 {
     IWorkspaceFactory wsFct = new AccessWorkspaceFactoryClass();
     IWorkspace pWorkspace = (IWorkspace)wsFct.OpenFromFile(outputPath, 0);
     ConvertFeatureClassToGDB(this.m_workSpace, pWorkspace, name, name, null);
 }
Esempio n. 49
0
        private void FillSubDirectory(DirectoryInfo di)
        {
            IWorkspaceFactory theWSFact;
            IWorkspace theWS;
            IFeatureWorkspace theFWS;
            IFeatureClass theFClass;
            int FCount;

            try
            {
                foreach (DirectoryInfo iDir in di.GetDirectories())
                {
                    FillSubDirectory(iDir);
                }

                foreach (FileInfo theFile in di.GetFiles("*.mdb"))
                {
                    theWSFact = new AccessWorkspaceFactoryClass();

                    theWS = theWSFact.OpenFromFile(theFile.FullName, 0);
                    theFWS = (IFeatureWorkspace)theWS;

                    String[] theSrcNames = GeoDbProcs.GetFeatureClassNames(srcWrkSpc);

                    foreach (String theSrcName in theSrcNames)
                    {
                        theFClass = theFWS.OpenFeatureClass(theSrcName);
                        lbSource.Items.Add(new FeatureData(theSrcName, theFClass));
                        Application.DoEvents();
                    }
                }
            }
            catch { }
        }
        private void EngineEditingForm_Load(object sender, EventArgs e)
        {
            m_editor = new EngineEditorClass();
           
            //Set buddy controls
            axTOCControl1.SetBuddyControl(axMapControl1);
            axEditorToolbar.SetBuddyControl(axMapControl1);
            axToolbarControl1.SetBuddyControl(axMapControl1);

            //Add items to the ToolbarControl
            axToolbarControl1.AddItem("esriControls.ControlsOpenDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axToolbarControl1.AddItem("esriControls.ControlsSaveAsDocCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axToolbarControl1.AddItem("esriControls.ControlsAddDataCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);            
            axToolbarControl1.AddItem("esriControls.ControlsMapZoomInTool", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axToolbarControl1.AddItem("esriControls.ControlsMapZoomOutTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axToolbarControl1.AddItem("esriControls.ControlsMapPanTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axToolbarControl1.AddItem("esriControls.ControlsMapFullExtentCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axToolbarControl1.AddItem("esriControls.ControlsMapZoomToLastExtentBackCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axToolbarControl1.AddItem("esriControls.ControlsMapZoomToLastExtentForwardCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
           
            //Add items to the custom editor toolbar          
            axEditorToolbar.AddItem("esriControls.ControlsEditingEditorMenu", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axEditorToolbar.AddItem("esriControls.ControlsEditingEditTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axEditorToolbar.AddItem("esriControls.ControlsEditingSketchTool", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axEditorToolbar.AddItem("esriControls.ControlsUndoCommand", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axEditorToolbar.AddItem("esriControls.ControlsRedoCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axEditorToolbar.AddItem("esriControls.ControlsEditingTargetToolControl", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axEditorToolbar.AddItem("esriControls.ControlsEditingTaskToolControl", 0, -1, true, 0, esriCommandStyles.esriCommandStyleIconOnly);
                       
            //Create a popup menu
            m_toolbarMenu = new ToolbarMenuClass();
            m_toolbarMenu.AddItem("esriControls.ControlsEditingSketchContextMenu", 0, 0, false, esriCommandStyles.esriCommandStyleTextOnly);

            //share the command pool          
            axToolbarControl1.CommandPool = axEditorToolbar.CommandPool;
            m_toolbarMenu.CommandPool = axEditorToolbar.CommandPool;

            //Create an operation stack for the undo and redo commands to use
            IOperationStack operationStack = new ControlsOperationStackClass();
            axEditorToolbar.OperationStack = operationStack;

            // Fill the Check List of Events for Selection
            TabControl tabControl = eventTabControl as TabControl;
            System.Collections.IEnumerator enumTabs = tabControl.TabPages.GetEnumerator();
            enumTabs.MoveNext();
            m_listenTab = enumTabs.Current as TabPage;
            enumTabs.MoveNext();
            m_selectTab = enumTabs.Current as TabPage;

            CheckedListBox editEventList = m_selectTab.GetNextControl(m_selectTab, true) as CheckedListBox;
            editEventList.ItemCheck += new ItemCheckEventHandler(editEventList_ItemCheck);

            ListBox listEvent = m_listenTab.GetNextControl(m_listenTab, true) as ListBox;
            listEvent.MouseDown += new MouseEventHandler(listEvent_MouseDown);

            eventListener = new Events.EventListener(m_editor);

            eventListener.Changed += new Events.ChangedEventHandler(eventListener_Changed);

            //populate the editor events            
            editEventList.Items.AddRange(Enum.GetNames(typeof(Events.EventListener.EditorEvent)));

            //add some sample line data to the map
            IWorkspaceFactory workspaceFactory = new AccessWorkspaceFactoryClass();
            //relative file path to the sample data from EXE location
            string filePath = @"..\..\..\data\StreamflowDateTime\Streamflow.mdb";
            
            IFeatureWorkspace workspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(filePath, axMapControl1.hWnd);

            //Add the various layers
            IFeatureLayer featureLayer1 = new FeatureLayerClass();
            featureLayer1.Name = "Watershed";
            featureLayer1.Visible = true;
            featureLayer1.FeatureClass = workspace.OpenFeatureClass("Watershed");
            axMapControl1.Map.AddLayer((ILayer)featureLayer1);

            IFeatureLayer featureLayer2 = new FeatureLayerClass();
            featureLayer2.Name = "TimSerTool";
            featureLayer2.Visible = true;
            featureLayer2.FeatureClass = workspace.OpenFeatureClass("TimSerTool");
            axMapControl1.Map.AddLayer((ILayer)featureLayer2);

        }
Esempio n. 51
0
 public static IWorkspaceFactory2 GetWorkspaceFactory(enumDataType databaseType)
 {
     IWorkspaceFactory2 workspacefacory = null;
     switch (databaseType)
     {
         case enumDataType.PGDB:
             {
                 workspacefacory = new AccessWorkspaceFactoryClass();
                 break;
             }
         case enumDataType.FileGDB:
             {
                 workspacefacory = new FileGDBWorkspaceFactoryClass();
                 break;
             }
         case enumDataType.SHP:
             {
                 workspacefacory = new ShapefileWorkspaceFactoryClass();
                 break;
             }
         default:
             {
                 return null;
             }
     }
     return workspacefacory;
 }
Esempio n. 52
0
        /// <summary>
        /// ����PGDB����Դ
        /// </summary>
        private IWorkspace CreateWorkspace()
        {
            IWorkspaceFactory workspaceFactory = new AccessWorkspaceFactoryClass();
            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;
        }
Esempio n. 53
0
        /// <summary>
        /// 获取工作空间SDE,文件型数据库,MDB,以及shapefile文件所在工作空间,这里可以用一个枚举
        /// </summary>
        /// <param name="_pDatabase"></param>
        /// <returns></returns>
        public IWorkspace GetWorkspace(String _pDatabase, GDBType pGDBType = GDBType.FGDB)
        {
            ESRI.ArcGIS.Geodatabase.IWorkspaceFactory pWsFactory = null;

            IWorkspace pWkspace = null;

            if (pGDBType == GDBType.SHP)
            {

                pWsFactory = new ShapefileWorkspaceFactory();

            }
            else if (pGDBType == GDBType.RWS)
            {

                pWsFactory = new RasterWorkspaceFactoryClass();

            }
            else if (pGDBType == GDBType.MDB)
            {
                pWsFactory = new AccessWorkspaceFactoryClass();
            }
            else if (pGDBType == GDBType.FGDB)
            {

                pWsFactory = new ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactoryClass();
            }
            else if (pGDBType == GDBType.SDE)
            {

                pWsFactory = new ESRI.ArcGIS.DataSourcesGDB.SdeWorkspaceFactoryClass();
            }

            try
            {

                pWkspace = pWsFactory.OpenFromFile(_pDatabase, 0);

            }
            catch (Exception EX)
            {
                //MessageBox.Show(EX.ToString());

            }

            return pWkspace;
        }
        private void tlsbtnShowCopyPanel_Click(object sender, EventArgs e)
        {
            #region "Open the Database to Copy From"

            findDatabase:
            // Check the registry
            string regValue = commonFunctions.ReadReg("Software\\NCGMPTools", "getSqlDatabase");

            // Find a Database
            IWorkspaceFactory wsFact = null;
            IWorkspace openedWorkspace = null;

            // Browse for a file, personal or SDE geodatabase
            IGxObjectFilter objectFilter = new GxFilterWorkspaces();
            IGxObject openedObject = commonFunctions.OpenArcFile(objectFilter, "Please select an NCGMP database");
            if (openedObject == null) { return; }

            // Check to see if it is a File, Personal or SDE database, create appropriate workspace factory
            string pathToOpen = null;

            switch (openedObject.Category)
            {
                case "Personal Geodatabase":
                    wsFact = new AccessWorkspaceFactoryClass();
                    pathToOpen = openedObject.FullName;
                    break;
                case "File Geodatabase":
                    wsFact = new FileGDBWorkspaceFactoryClass();
                    pathToOpen = openedObject.FullName;
                    break;
                case "Spatial Database Connection":
                case "Database Connection":
                    wsFact = new SdeWorkspaceFactoryClass();
                    IGxRemoteDatabaseFolder remoteDatabaseFolder = (IGxRemoteDatabaseFolder)openedObject.Parent;
                    pathToOpen = remoteDatabaseFolder.Path + openedObject.Name;
                    break;
                default:
                    break;
            }
            openedWorkspace = wsFact.OpenFromFile(pathToOpen, 0);

            // Check to see if the database is valid NCGMP
            bool isValid = ncgmpChecks.IsWorkspaceMinNCGMPCompliant(openedWorkspace);
            if (isValid == false)
            {
                MessageBox.Show("The selected database is not a valid NCGMP database.", "NCGMP Toolbar");
                goto findDatabase;
            }
            //else
            //{
            //    isValid = ncgmpChecks.IsSysInfoPresent(openedWorkspace);
            //    if (isValid == false)
            //    {
            //        MessageBox.Show("In order to use these tools, the NCGMP database must contain a SysInfo table.", "NCGMP Toolbar");
            //        goto findDatabase;
            //    }
            //}
            #endregion

            // Show the copy form
            sourceLegendItemSelection sourceForm = new sourceLegendItemSelection(openedWorkspace);
            sourceForm.ShowDialog();

            // Bail if they canceled
            if (sourceForm.Canceled == true) { return; }

            // Get the Ids from the form, then close it
            if (sourceForm.idsToCopy.Count == 0) { sourceForm.Close(); return; }
            List<string> idsToCopy = sourceForm.idsToCopy;
            sourceForm.Close();

            // Build the Query to get the records to copy
            string sqlWhereClause = "DescriptionOfMapUnits_ID = '";
            foreach (string idValue in idsToCopy) { sqlWhereClause += idValue + "' OR DescriptionOfMapUnits_ID = '"; }

            // Get the records
            if (sqlWhereClause == "DescriptionOfMapUnits_ID = '") { return; }
            DescriptionOfMapUnitsAccess sourceDmu = new DescriptionOfMapUnitsAccess(openedWorkspace);
            sourceDmu.AddDescriptionOfMapUnits(sqlWhereClause.Remove(sqlWhereClause.Length - 32));

            // Get the next new Hierarchy Key
            string newHierarchy = GetNewHierarchyKey();
            int newValue = int.Parse(newHierarchy.Substring(newHierarchy.Length - 4));

            // Loop through the source records, add them to the target legend after adjusting the Hierarchy
            DescriptionOfMapUnitsAccess targetDmu = new DescriptionOfMapUnitsAccess(m_theWorkspace);
            foreach (KeyValuePair<string, DescriptionOfMapUnitsAccess.DescriptionOfMapUnit> sourceEntry in sourceDmu.DescriptionOfMapUnitsDictionary)
            {
                DescriptionOfMapUnitsAccess.DescriptionOfMapUnit sourceDmuEntry = sourceEntry.Value;
                string thisHierachyKey = newValue.ToString().PadLeft(4, '0');

                targetDmu.NewDescriptionOfMapUnit(sourceDmuEntry.MapUnit, sourceDmuEntry.Name, sourceDmuEntry.FullName, sourceDmuEntry.Label,
                    sourceDmuEntry.Age, sourceDmuEntry.Description, thisHierachyKey,
                    sourceDmuEntry.ParagraphStyle, sourceDmuEntry.AreaFillRGB, sourceDmuEntry.AreaFillPatternDescription,
                    commonFunctions.GetCurrentDataSourceID(), sourceDmuEntry.GeneralLithology, sourceDmuEntry.GeneralLithologyConfidence);

                newValue++;
            }

            // Save the target Dmu
            targetDmu.SaveDescriptionOfMapUnits();

            // Refresh the tree
            ClearMapUnitInput();
            PopulateMainLegendTree();
        }
Esempio n. 55
0
 public IWorkspace CreateWorkspaceGdbFile(string path, string name, string type)
 {
     try
     {
         IWorkspace wp;
         IWorkspaceName wpn;
         IName nwp;
         IWorkspaceFactory2 wspf;
         Directory.CreateDirectory(path);
         path = path + "\\";
         switch (type)
         {
             case "mdb":
                 wspf = new AccessWorkspaceFactoryClass();
                 name = name + ".mdb";
                 break;
             case "shp":
                 wspf = new ShapefileWorkspaceFactoryClass();
                 break;
             default:
                 wspf = new ShapefileWorkspaceFactoryClass();
                 break;
         }
         wpn = wspf.Create(path, name, null, 0);
         nwp = (IName)wpn;
         wp = (IWorkspace)nwp.Open();
         return wp;
     }
     catch { return null; }
 }
        protected override void OnClick()
        {
            //          string getSqlDatabase = "False";
            findDatabase:
            // Check the registry
            // Find a Database
            IWorkspaceFactory wsFact = null;
            IWorkspace openedWorkspace = null;

            // Browse for a file, personal or SDE geodatabase
            IGxObjectFilter objectFilter = new GxFilterWorkspaces();
            IGxObject openedObject = commonFunctions.OpenArcFile(objectFilter, "Please select an NCGMP database");
            if (openedObject == null) { return;  }

            // Check to see if it is a File, Personal or SDE database, create appropriate workspace factory
            string pathToOpen = null;

            switch (openedObject.Category)
            {
                case "Personal Geodatabase":
                    wsFact = new AccessWorkspaceFactoryClass();
                    pathToOpen = openedObject.FullName;
                    break;
                case "File Geodatabase":
                    wsFact = new FileGDBWorkspaceFactoryClass();
                    pathToOpen = openedObject.FullName;
                    break;
                case "Spatial Database Connection":
                    wsFact = new SdeWorkspaceFactoryClass();
                    IGxRemoteDatabaseFolder remoteDatabaseFolder = (IGxRemoteDatabaseFolder)openedObject.Parent;
                    pathToOpen = remoteDatabaseFolder.Path + "\\" + openedObject.Name;
                    break;
                default:
                    break;
            }

            try
            {
                openedWorkspace = wsFact.OpenFromFile(pathToOpen, 0);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            // Check to see if the database is valid NCGMP
            bool isValid = ncgmpChecks.IsWorkspaceMinNCGMPCompliant(openedWorkspace);
            if (isValid == false)
            {
                MessageBox.Show("The selected database is not a valid NCGMP database.", "NCGMP Toolbar");
                goto findDatabase;
            }
            else
            {
                isValid = ncgmpChecks.IsSysInfoPresent(openedWorkspace);
                if (isValid == false)
                {
                    MessageBox.Show("In order to use these tools, the NCGMP database must contain a SysInfo table.", "NCGMP Toolbar");
                    goto findDatabase;
                }
            }

            bool isTopologyUsed = ncgmpChecks.IsTopologyUsed(openedWorkspace);
            bool hasStationTables = ncgmpChecks.IsAzgsStationAddinPresent(openedWorkspace);
            bool hasStandardLithtables = ncgmpChecks.IsStandardLithAddinPresent(openedWorkspace);
            bool hasRepresentations = ncgmpChecks.AreRepresentationsUsed(openedWorkspace);

            // Add FeatureClasses and tables to the ArcMap Project
            AddLayersToMap(openedWorkspace, isTopologyUsed, hasStationTables, hasRepresentations);

            // Populate the Data Sources combobox
        }
Esempio n. 57
0
 //++++++++GeoDatabase Part++++++
 public IFeatureClass openFeatureClass(string mdbName, string featName)
 {
     //Open the AccessWorkSpace by the given name which including extention(.mdb)
     IWorkspace ws = null;
     IWorkspaceFactory wsf = new AccessWorkspaceFactoryClass();
     ws = wsf.OpenFromFile(mdbName, 0);
     IFeatureWorkspace pFeatWorkspace = ws as IFeatureWorkspace;
     IFeatureClass pFeatCls = pFeatWorkspace.OpenFeatureClass(featName);
     return pFeatCls;
 }
Esempio n. 58
0
        //Open Personal Geodatabase RasterCatalog
        //   ESRI.ArcGIS.Geodatabase, ESRI.ArcGIS.DataSourcesGDB
        public IRasterCatalog OpenPGDBRasterCatalog(string pathName, string rasterCatalogName)
        {
            // Open personal geodatabase raster catalog with the given name
            // pathName is the PGDB path (location of the personal geodatabase)
            // rasterCatalogName is the name of the raster catalog to be opened

            //Open the Access workspace
            IWorkspaceFactory2 workspaceFactory = new AccessWorkspaceFactoryClass();

            IRasterWorkspaceEx rasterWorkspaceEx = workspaceFactory.OpenFromFile(pathName, 0) as IRasterWorkspaceEx;

            //Open the PGDB raster Catalog
            IRasterCatalog rasterCatalog = null;
            rasterCatalog = rasterWorkspaceEx.OpenRasterCatalog(rasterCatalogName);

            return rasterCatalog;
        }
Esempio n. 59
0
        public IFeatureClass OpenFeatureClassFromFileMdb(string path, string name)
        {
            IWorkspaceFactory2 mdbWspf = new AccessWorkspaceFactoryClass();
            IWorkspace wsp;
            IFeatureWorkspace fwsp;

            wsp = mdbWspf.OpenFromFile(path, 0);
            fwsp = (IFeatureWorkspace)wsp;
            return fwsp.OpenFeatureClass(name);
        }
Esempio n. 60
0
 //��������openAccessWorkspace
 //�������ܣ��򿪸������ݿ�ռ�
 public IWorkspace openAccessWorkspace(string connString)
 {
     //Open the AccessWorkSpace by the given name which including extention(.mdb)
     IWorkspace ws = null;
     IWorkspaceFactory wsf = new AccessWorkspaceFactoryClass();
     ws = wsf.OpenFromFile(connString, 0);
     return ws;
 }