Ejemplo n.º 1
0
        public static IWorkspace GetWorkspace(string datasource, DataSourceType datasourceType)
        {
            switch (datasourceType)
            {
            case DataSourceType.SdeFilePath:
            {
                SdeWorkspaceFactory sdeWf = new SdeWorkspaceFactoryClass();
                return(sdeWf.OpenFromFile(datasource, 0));
            }

            case DataSourceType.SdeTxt: throw new NotImplementedException();

            case DataSourceType.SdeJson: throw new NotImplementedException();

            case DataSourceType.GdbFilePath:
            {
                FileGDBWorkspaceFactory fileWf = new FileGDBWorkspaceFactoryClass();
                return(fileWf.OpenFromFile(datasource, 0));
            }

            case DataSourceType.ShapefilePath: throw new NotImplementedException();

            default:
                return(null);

                break;
            }
        }
Ejemplo n.º 2
0
        // Create the file geodatabase.
        public static void CreateFileGeodatabase()
        {
            string strFgdPath = @"C:\temp\";
            string strFgdName = @"AddressCrossCheck";

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

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

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

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

            workspaceFGDB = (IWorkspace)name.Open();

            // Load the data.
            ImportDataToFGDB();
        }
Ejemplo n.º 3
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);
        }
        protected override void OnClick()
        {
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
            IWorkspace        workspace        = workspaceFactory.OpenFromFile(@"C:\temp\data.gdb", 0);
            IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;
            IFeatureClass     featureClass     = featureWorkspace.OpenFeatureClass("PolygonFC");

            ISpatialReferenceFactory3 spatialFact = new SpatialReferenceEnvironmentClass();
            IQueryFilter filter = new QueryFilterClass();

            filter.WhereClause = "";
            // The Geotransformation to use while performing the projection
            IGeoTransformation pGeoTransB = spatialFact.CreateGeoTransformation(
                (int)esriSRGeoTransformationType.esriSRGeoTransformation_NAD1983_To_WGS1984_1) as IGeoTransformation;
            // The target spatial reference. WGS_1984: WKID = 4326 (EPSG)
            ISpatialReference toSpatialReference = spatialFact.CreateSpatialReference(4326);
            //create the search cursor to go through each and every feature in the featureclass
            IFeatureCursor featureCursor = featureClass.Search(filter, true);
            IFeature       feature       = featureCursor.NextFeature();
            string         areaText      = null;

            while (feature != null)
            {
                // Project the feature (geometry) from its current coordinate system into the one specified (UTMz11N_WGS84)
                ((IGeometry5)feature.Shape).ProjectEx(toSpatialReference, esriTransformDirection.esriTransformReverse, pGeoTransB, false, 0.0, 0.0);
                IPolygon polygon = (IPolygon)feature.Shape;
                // Compute the area
                IArea area = polygon as IArea;
                // Build a string to output to a message box
                areaText += "OID = " + feature.OID + " , " + "Area =" + area.Area.ToString() + " \n";
                feature   = featureCursor.NextFeature();
            }
            MessageBox.Show(areaText);
            ArcMap.Application.CurrentTool = null;
        }
Ejemplo n.º 5
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);
        }
Ejemplo n.º 6
0
        private void btnSdeRcPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();

            //folder.ShowNewFolderButton = false;
            folder.Description = "还原的gdb路径:";
            if (folder.ShowDialog() == DialogResult.OK)
            {
                string str = folder.SelectedPath;
                this.txtSdeRcPath.Text = str;
            }
            IWorkspaceFactory pGDBWf = new FileGDBWorkspaceFactoryClass();

            pGDBWs      = pGDBWf.OpenFromFile(txtSdeRcPath.Text, 0);
            this.Cursor = Cursors.WaitCursor;
            lstSdeRcDs.Items.Clear();
            if (pGDBWs == null)
            {
                lblBottom.Text = "连接失败!请检查路径。";
                this.Cursor    = Cursors.Default;
                return;
            }
            IEnumDatasetName pEDN = pGDBWs.get_DatasetNames(esriDatasetType.esriDTFeatureDataset);
            IDatasetName     pDN  = pEDN.Next();

            while (pDN != null)
            {
                lstSdeRcDs.Items.Add(pDN.Name);
                pDN = pEDN.Next();
            }
            lstSdeRcDs.Refresh();
            this.Cursor = Cursors.Default;
        }
Ejemplo n.º 7
0
        //打开工作区间
        public static IWorkspace OpenWorkspace(string strGDBName)
        {
            IWorkspaceFactory workspaceFactory;

            workspaceFactory = new FileGDBWorkspaceFactoryClass();
            return(workspaceFactory.OpenFromFile(strGDBName, 0));
        }
Ejemplo n.º 8
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);
            }
        }
Ejemplo n.º 9
0
        private void buttonX_ok_Click(object sender, EventArgs e)
        {
            CGmpPoint xml    = new CGmpPoint();
            bool      result = xml.ReadGmpXML(XMLPath);
            Regex     regNum = new Regex("^[0-9]");

            if (regNum.IsMatch(textBoxX3.Text) == true)
            {
                MessageBox.Show("数据集名称不能以数字开头命名", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (result == true)
            {
                try
                {
                    IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
                    gdbPath = textBoxX2.Text;
                    IFeatureWorkspace        pFeatureWorkspace        = workspaceFactory.OpenFromFile(gdbPath, 0) as IFeatureWorkspace;
                    ISpatialReferenceFactory pSpatialReferenceFactory = new SpatialReferenceEnvironment();

                    //ISpatialReference pSpatialReference = new UnknownCoordinateSystemClass();
                    ISpatialReference pSpatialReference = ClsGDBDataCommon.CreateProjectedCoordinateSystem();
                    pSpatialReference.SetDomain(-8000000, 8000000, -800000, 8000000);
                    IFeatureDataset pFeatureDataset = pFeatureWorkspace.CreateFeatureDataset(textBoxX3.Text, pSpatialReference);
                    IFeatureClass   pFeatureclass   = CreatePointFeatureClass(pFeatureDataset, xml);
                    IFeatureClass   pFCLine         = CreatLineFC(pFeatureDataset, pFeatureclass);
                    if (pFeatureclass == null || pFCLine == null)
                    {
                        MessageBox.Show("数据生成失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    IFeatureLayer pFPointLayer = new FeatureLayerClass();
                    pFPointLayer.FeatureClass = pFeatureclass;
                    pFPointLayer.Name         = textBoxX3.Text + "_Gmppoint";

                    IFeatureLayer pFLintLayer = new FeatureLayerClass();
                    pFLintLayer.FeatureClass = pFCLine;
                    pFLintLayer.Name         = textBoxX3.Text + "_GmpLine";

                    m_pMapCtl.AddLayer(pFLintLayer as ILayer, 0);
                    m_pMapCtl.AddLayer(pFPointLayer as ILayer, 0);
                    m_pMapCtl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);

                    if (cmbImpSymbol.Text != null && symFilePath != null)
                    {
                        ImpSymbolFromFile(symFilePath, pFPointLayer, pFLintLayer);
                    }


                    //MessageBox.Show("数据已经生成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
            }
        }
Ejemplo n.º 10
0
        private void btnOpenXML_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

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

            return(pWs);
        }
Ejemplo n.º 12
0
        public bool createGDBFile(string gdbfolderpath, string filename)
        {
            // IWorkspace workspace = null;
            IWorkspaceName workspaceName = null;

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

                if (workspaceName != null)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception eg)
            {
                return(false);
            }
        }
Ejemplo n.º 13
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);
        }
Ejemplo n.º 14
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);
            }
        }
Ejemplo n.º 15
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);
            }
        }
Ejemplo n.º 16
0
 private void btnImpSymbol_Click(object sender, EventArgs e)
 {
     try
     {
         SaveFileDialog fbd = new SaveFileDialog();
         fbd.Title            = "Save file";
         fbd.InitialDirectory = System.IO.Path.GetDirectoryName(XMLPath);
         if (fbd.ShowDialog() == DialogResult.OK)
         {
             if (System.IO.Directory.Exists(fbd.FileName + ".shp") == true)
             {
                 MessageBox.Show("shp已存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                 return;
             }
             IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
             IWorkspaceName    workspaceName    = workspaceFactory.Create(System.IO.Path.GetDirectoryName(fbd.FileName), System.IO.Path.GetFileName(fbd.FileName), null, 0);
             gdbPath        = fbd.FileName + ".gdb";
             textBoxX2.Text = fbd.FileName + ".gdb";
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
         return;
     }
 }
Ejemplo n.º 17
0
        public IWorkspace IWorkspaceFactory_Create_Example_Access(string string_5)
        {
            IWorkspaceFactory factory = new FileGDBWorkspaceFactoryClass();
            IName             name2   = (IName)factory.Create(string_5, "MyNewFileGDB.gdb", null, 0);

            return((IWorkspace)name2.Open());
        }
Ejemplo n.º 18
0
        /// <summary>
        ///     Creates the scratch workspace.
        /// </summary>
        /// <param name="scratchConnectionFile">The scratch connection file.</param>
        /// <param name="fallbackScratchName">Name of the fallback scratch.</param>
        /// <returns>
        ///     Returns a <see cref="IWorkspace" /> representing the temporary workspace that is either local or in-memory.
        /// </returns>
        protected IWorkspace CreateScratchWorkspace(string scratchConnectionFile, string fallbackScratchName)
        {
            if (string.IsNullOrEmpty(scratchConnectionFile))
            {
                IScratchWorkspaceFactory2 factory = new ScratchWorkspaceFactoryClass();
                return(factory.DefaultScratchWorkspace);
            }

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

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

            var fgdb = new FileGDBWorkspaceFactoryClass();

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

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

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

            return(workspace);
        }
Ejemplo n.º 19
0
        private void 加载文件地理数据库数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IWorkspaceFactory pFileGDBWorkspaceFactory;

            FolderBrowserDialog dlg = new FolderBrowserDialog();

            if (dlg.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            string pFullPath = dlg.SelectedPath;

            if (pFullPath == "")
            {
                return;
            }
            pFileGDBWorkspaceFactory = new FileGDBWorkspaceFactoryClass(); //using ESRI.ArcGIS.DataSourcesGDB;

            ClearAllData();                                                //新增删除数据

            //获取工作空间
            IWorkspace pWorkspace = pFileGDBWorkspaceFactory.OpenFromFile(pFullPath, 0);

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

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

            Marshal.ReleaseComObject(wsName);
            Marshal.ReleaseComObject(wsFctry);
            return(gdbPath);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 打开数据库中FeatureClasss
        /// </summary>
        /// <param name="FileGdbName"></param>
        /// <param name="featureDataset"></param>
        /// <param name="featureclassname"></param>
        /// <returns></returns>
        public static IFeatureClass OpenFeatureClass(string FileGdbName, string featureDataset, string featureclassname)
        {
            IWorkspaceFactory pworkspF         = new FileGDBWorkspaceFactoryClass();
            IWorkspace        workspace        = pworkspF.OpenFromFile(FileGdbName, 0);
            IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;

            IFeatureClass   featureClass    = null;
            IFeatureDataset pFeatureDataset = featureWorkspace.OpenFeatureDataset(featureDataset);

            if (pFeatureDataset == null)
            {
                return(null);
            }
            IEnumDataset pEnumDataset = pFeatureDataset.Subsets;

            pEnumDataset.Reset();
            IDataset dataset = pEnumDataset.Next();

            while (dataset != null)
            {
                if (dataset.Name == featureclassname)
                {
                    featureClass = dataset as IFeatureClass;
                    break;
                }
                dataset = pEnumDataset.Next();
            }


            return(featureClass);
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Opens a dialog so the user can select an output workspace.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void outputWorkspaceButton_Click(object sender, EventArgs e)
 {
     try
     {
         IGxObjectFilter           geodatabaseFilter = new GxFilterFileGeodatabasesClass();
         IGxDialog                 dlg     = new GxDialogClass();
         IGxObjectFilterCollection filters = (IGxObjectFilterCollection)dlg;
         filters.AddFilter(geodatabaseFilter, false);
         dlg.Title         = "Select the file geodatabase for the output";
         dlg.ButtonCaption = "Select";
         IEnumGxObject objects = null;
         if (dlg.DoModalOpen(0, out objects))
         {
             IGxObject          obj = objects.Next();
             IWorkspaceFactory2 workspaceFactory = new FileGDBWorkspaceFactoryClass();
             IFeatureWorkspace  workspace        = (IFeatureWorkspace)workspaceFactory.OpenFromFile(obj.FullName, 0);
             _transform.SetWorkspace(workspace);
             outputWorkspaceTextBox.Text = obj.Name;
             EnableSave();
         }
     }
     catch (Exception ex)
     {
         ShowError(ex.Message);
     }
 }
Ejemplo n.º 23
0
        public IGeometry GetClipExtent(int extNm)
        {
            IWorkspaceFactory bouFactory   = new FileGDBWorkspaceFactoryClass();
            IFeatureWorkspace bouFeaWksp   = bouFactory.OpenFromFile(currentDir + "\\" + bouGDB, 0) as IFeatureWorkspace;
            IGeometry         clipBoundary = null;

            if (extNm == 0)
            {
                IFeatureClass wrdFC = bouFeaWksp.OpenFeatureClass("原始范围");
                clipBoundary = wrdFC.Search(null, false).NextFeature().ShapeCopy;
            }

            else if (extNm == 1)
            {
                IFeatureClass cnFC = bouFeaWksp.OpenFeatureClass("中国国界");
                clipBoundary = cnFC.Search(null, false).NextFeature().ShapeCopy;
            }

            else if (extNm == 2)
            {
                IFeatureClass prvFC = bouFeaWksp.OpenFeatureClass("省界");
                clipBoundary = prvFC.Search(null, false).NextFeature().ShapeCopy;
            }

            return(clipBoundary);
        }
Ejemplo n.º 24
0
        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);
            axToolbarControl1.AddItem("esriControls.ControlsMapZoomToolControl", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axToolbarControl1.AddItem("esriControls.ControlsMapMeasureTool", 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);

            //share the command pool
            axToolbarControl1.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 point data to the map
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
            //relative file path to the sample data from EXE location
            string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            filePath = System.IO.Path.Combine(filePath, @"ArcGIS\data\AirportsAndGolf\Golf.gdb");

            IFeatureWorkspace workspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(filePath, axMapControl1.hWnd);

            IFeatureLayer featureLayer = new FeatureLayerClass();

            featureLayer.Name         = "Golf Courses";
            featureLayer.Visible      = true;
            featureLayer.FeatureClass = workspace.OpenFeatureClass("Golf");

            axMapControl1.Map.MapUnits = esriUnits.esriMeters;
            axMapControl1.Map.AddLayer((ILayer)featureLayer);

            //set up the snapping environment
            m_engineEditor = new EngineEditorClass();
            m_engineEditor.SnapToleranceUnits = esriEngineSnapToleranceUnits.esriEngineSnapToleranceMapUnits;
            m_engineEditor.SnapTolerance      = 2000;
        }
Ejemplo n.º 25
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);
            }
        }
        // create a file geodatabase in user-specified location
        #region "Create FileGeodatabase"
        public static IWorkspace CreateFileGdbWorkspace(string strFgdPath, string strFgdName)
        {
            IWorkspaceName workspaceName = null;
            // Instantiate a file geodatabase workspace factory and create a new file geodatabase.
            // The Create method returns a workspace name object.
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass() as IWorkspaceFactory;

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

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

            return(workspace);
        }
        /// <summary>
        /// 创建工作空间工厂
        /// </summary>
        /// <returns></returns>
        private static IWorkspaceFactory CreateWksFactory(enumWorkspaceType fileWksType)
        {
            IWorkspaceFactory wksFactory = null;

            switch (fileWksType)
            {
            case enumWorkspaceType.Shapefile:
                wksFactory = new ShapefileWorkspaceFactoryClass();
                break;

            case enumWorkspaceType.Gdb:
                wksFactory = new FileGDBWorkspaceFactoryClass();
                break;

            case enumWorkspaceType.Mdb:
                wksFactory = new AccessWorkspaceFactoryClass();
                break;

            case enumWorkspaceType.Cad:
                wksFactory = new CadWorkspaceFactoryClass();
                break;

            case enumWorkspaceType.RasterFile:
                wksFactory = new RasterWorkspaceFactoryClass();
                break;

            default:
                break;
            }
            return(wksFactory);
        }
Ejemplo n.º 28
0
        //测试
        private void buttonXTest_Click(object sender, EventArgs e)
        {
            if (cboDataType.Text == "SDE")
            {
                try
                {//Workspace
                    IWorkspaceFactory pWorkspaceFactory;
                    pWorkspaceFactory = new SdeWorkspaceFactoryClass();

                    //PropertySet
                    IPropertySet pPropertySet;
                    pPropertySet = new PropertySetClass();
                    //pPropertySet.SetProperty("Service", comboBoxDsName.Text);
                    pPropertySet.SetProperty("Server", txtServer.Text);
                    pPropertySet.SetProperty("Database", txtDataBase.Text);
                    pPropertySet.SetProperty("Instance", "5151");//"port:" + txtService.Text
                    pPropertySet.SetProperty("user", txtUser.Text);
                    pPropertySet.SetProperty("password", txtPassWord.Text);
                    pPropertySet.SetProperty("version", "sde.DEFAULT");
                    IWorkspace pws = pWorkspaceFactory.Open(pPropertySet, 0);
                    MessageBox.Show("连接成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch { MessageBox.Show("连接失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); }
            }
            if (cboDataType.Text == "PDB")
            {
                if (txtServer.Text == "")
                {
                    MessageBox.Show("服务器名为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                try
                {
                    IWorkspaceFactory pWorkspaceFactory;
                    pWorkspaceFactory = new AccessWorkspaceFactoryClass();
                    IWorkspace pws = pWorkspaceFactory.OpenFromFile(txtServer.Text, 0);
                    MessageBox.Show("连接成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch { MessageBox.Show("连接失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); }
            }
            if (cboDataType.Text == "GDB")
            {
                if (txtServer.Text == "")
                {
                    MessageBox.Show("服务器名为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                try
                {
                    IWorkspaceFactory pWorkspaceFactory;
                    pWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
                    IWorkspace pws = pWorkspaceFactory.OpenFromFile(txtServer.Text, 0);
                    MessageBox.Show("连接成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch { MessageBox.Show("连接失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); }
            }
        }
Ejemplo n.º 29
0
        public static IFeatureClass GetFeatureClass(string gdbPath, string featureClassName)
        {
            FileGDBWorkspaceFactory fileGDBWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
            var workspace = fileGDBWorkspaceFactory.OpenFromFile(gdbPath, 0);
            var fc        = ((IFeatureWorkspace)workspace).OpenFeatureClass(featureClassName);

            return(fc);
        }
Ejemplo n.º 30
0
        public static string GetNameGDB(string gdb_Path, string file_Name)
        {
            IWorkspaceFactory wsf = new FileGDBWorkspaceFactoryClass();
            IWorkspace        ws  = wsf.OpenFromFile(gdb_Path, 0);
            IEnumDatasetName  edn = ws.get_DatasetNames(esriDatasetType.esriDTAny);

            return(Check(edn, file_Name, string.Empty));
        }
        //
        // CONSTRUCTOR
        //
        public FileGeodatabaseValidator() : base() {
            string tempPath = Path.GetTempPath();
            string name = Guid.NewGuid().ToString("N").ToUpper();

            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
            IWorkspaceName workspaceName = workspaceFactory.Create(tempPath, name, null, 0);
            IWorkspace workspace = (IWorkspace)((IName)workspaceName).Open();
            this.SetWorkspace(workspace);
        }
Ejemplo n.º 32
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;
        }
Ejemplo n.º 33
0
 public static IWorkspace GetFGDBWorkspace(string sFilePath)
 {
     if (!System.IO.Directory.Exists(sFilePath))
     {
         return null;
     }
     try
     {
         IWorkspaceFactory factory = new FileGDBWorkspaceFactoryClass();
         return factory.OpenFromFile(sFilePath, 0);
     }
     catch
     {
         return null;
     }
 }
Ejemplo n.º 34
0
        public static IFeatureClass CreateFeatureClass(fulcrumform form, string pathToGeoDB)
        {
            try
            {
                ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
                IGeographicCoordinateSystem geographicCoordinateSystem = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
                ISpatialReference sr = geographicCoordinateSystem;

                IWorkspaceFactory2 wsf = new FileGDBWorkspaceFactoryClass();
                IWorkspace2 workspace = (IWorkspace2)wsf.OpenFromFile(pathToGeoDB, 0);
                IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;

                string fcName = GetUniqueFeatureClassName(form.name, workspace);

                IFields fieldsCollection = new FieldsClass();
                IFieldEdit newField = fieldsCollection as IFieldEdit;

                IFeatureClassDescription fcDesc = new ESRI.ArcGIS.Geodatabase.FeatureClassDescriptionClass();

                IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc;
                // create required fields using the required fields method
                IFields fields = ocDesc.RequiredFields;

                //Grab the GeometryDef from the shape field, edit it and give it back
                int shapeFieldIndex = fields.FindField(fcDesc.ShapeFieldName);
                IField shapeField = fields.get_Field(shapeFieldIndex);
                IGeometryDef geomDef = shapeField.GeometryDef;
                IGeometryDefEdit geomDefEdit = (IGeometryDefEdit)geomDef;
                geomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
                geomDefEdit.GridCount_2 = 1;
                geomDefEdit.set_GridSize(0, 0);
                geomDefEdit.SpatialReference_2 = sr;

                IFields newFields = CreateNewFields(form, fields, sr);

                IFeatureClass featureClass = featureWorkspace.CreateFeatureClass
                    (fcName, newFields, ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDesc.ShapeFieldName, "");

                return featureClass;
            }
            catch (Exception e)
            {
                string errMsg = e.Message;
                return null;
            }
        }
        /*
         * A utility class to create a File Geodatabase Workspace
         */
        public static IWorkspace createFileGeodatabaseWorkspace(ref log4net.ILog log, string workspaceDirectory, string workspaceFolderName)
        {
            log.Debug("Starting the process to create a new local File Geodatabase workspace.");

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

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

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

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

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

                // return the workspace
                log.Debug("Opening the workspace and returning it to the requestor.");
                return (IWorkspace)name.Open();
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Open a feature class from a GDB
        /// </summary>
        /// <param name="conFilePath">Path to GDB workspace</param>
        /// <param name="fcName">Feature class name</param>
        /// <param name="fdsName">Optional feature dataset name</param>
        /// <returns></returns>
        public static IFeatureClass openFeatureClassFromGDB(string conFilePath, string fcName, string fdsName = "")
        {
            IFeatureClass featClass = null;
            IWorkspaceFactory factory = new FileGDBWorkspaceFactoryClass();

            IWorkspace workspace = factory.OpenFromFile(conFilePath, 0);
            IFeatureWorkspace featWorkspace = (IFeatureWorkspace)workspace;

            if (fdsName != "")
            {
                IFeatureDataset featdataset = featWorkspace.OpenFeatureDataset(fdsName);
                IFeatureWorkspace datasetWorkspace = (IFeatureWorkspace)featdataset.Workspace;
                featClass = datasetWorkspace.OpenFeatureClass(fcName);
            }
            else
            {
                featClass = featWorkspace.OpenFeatureClass(fcName);
            }
            return featClass;
        }
Ejemplo n.º 37
0
        private IFeatureClass getFeatureClass(string serviceURL, string userName, string gdbPath, string fcName)
        {
            IFeatureClass fc = null;

            //will leverage the user that is currently signed on or prompt
            string tok = "";
            int to = 60;
            IArcGISSingleSignon p = new ArcGISSingleSignonClass() as IArcGISSingleSignon;
            p.GetToken(this.Handle.ToInt32(), ref tok, serviceURL, ref to, ref userName);

            string url = String.Format(serviceURL + "&token={0}", tok);

            WebClient requestHelper = new WebClient();
            string responseString = requestHelper.DownloadString(new Uri(url));

            IWorkspaceFactory wf = new FileGDBWorkspaceFactoryClass();
            IWorkspace w = wf.OpenFromFile(gdbPath, 0);

            fc = jsonToFeatureClass(responseString, w, fcName);

            return fc;
        }
Ejemplo n.º 38
0
        /// <summary>
        /// 打开文件数据库获取要素类
        /// </summary>
        /// <param name="gdbFile"></param>
        /// <param name="featureName"></param>
        /// <returns></returns>
        public static IFeatureClass GetFileGeodatabase(string gdbFile, string featureName)
        {
            IFeatureWorkspace featureWorkspace;
            IFeatureClass featureClass;

            FileGDBWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
            featureWorkspace = workspaceFactory.OpenFromFile(gdbFile, 0) as IFeatureWorkspace;
            featureClass = featureWorkspace.OpenFeatureClass(featureName);

            return featureClass;
        }
Ejemplo n.º 39
0
        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();
        }
Ejemplo n.º 40
0
 /// <summary>
 /// 连接GDB数据源
 /// </summary>
 private IWorkspace ConnectWorkspace()
 {
     IWorkspaceFactory factory = new FileGDBWorkspaceFactoryClass();
     try
     {
         return factory.OpenFromFile(m_strFilePathName, 0);
     }
     catch (Exception ex)
     {
         //ProjectData.SetProjectError(exception1);
         Logger.WriteErrorLog(ex);
         //ProjectData.ClearProjectError();
     }
     return null;
 }
Ejemplo n.º 41
0
        private static IWorkspace GetWorkspace()
        {
            try
            {
                //Create a new AccessWorkspaceFactoryClass
                IWorkspaceFactory wsf = new FileGDBWorkspaceFactoryClass();

                ESRI.ArcGIS.esriSystem.IPropertySet ps = new PropertySetClass();  //C:\ArcFM\CAFM\Sample Data\Geodatabases
                ps.SetProperty("DATABASE", @"C:\Code\Git\GreatDivideTrail\Database\GDT.gdb");

                IWorkspace ws = wsf.Open(ps, 0);
                return ws;
            }
            catch (Exception ex)
            {
                _log.Error("ERROR - ", ex);
                //Throw the error, because we can't recover from this error!
                throw (new ApplicationException("Unable to open workspace", ex));
            }
        }
Ejemplo n.º 42
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);
        }
        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
        }
    private IFeatureClass openPlaybackData()
    {
      //set the path to the featureclass
      string path = @"..\..\..\..\..\data\Time\ProjectData.gdb";
      if (!System.IO.Directory.Exists(path))
      {
        MessageBox.Show("Cannot find hurricane data:\n" + path, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return null;
      }

      IWorkspaceFactory2 wsFactory = new FileGDBWorkspaceFactoryClass();
      IWorkspace workspace = wsFactory.OpenFromFile( path, 0 );
      IFeatureClass featureClass = ((IFeatureWorkspace)workspace).OpenFeatureClass( "atlantic_hurricanes_2000" );

      return featureClass;
    }
        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);
            axToolbarControl1.AddItem("esriControls.ControlsMapZoomToolControl", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);
            axToolbarControl1.AddItem("esriControls.ControlsMapMeasureTool", 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);
           
            //share the command pool
            axToolbarControl1.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 point data to the map
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
            //relative file path to the sample data from EXE location
            string filePath = @"..\..\..\..\data\AirportsAndGolf\Golf.gdb";
          
            IFeatureWorkspace workspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(filePath, axMapControl1.hWnd);

            IFeatureLayer featureLayer = new FeatureLayerClass();
            featureLayer.Name = "Golf Courses";
            featureLayer.Visible = true;
            featureLayer.FeatureClass = workspace.OpenFeatureClass("Golf");

            axMapControl1.Map.MapUnits = esriUnits.esriMeters;            
            axMapControl1.Map.AddLayer((ILayer)featureLayer); 
          
            //set up the snapping environment
            m_engineEditor = new EngineEditorClass();
            m_engineEditor.SnapToleranceUnits = esriEngineSnapToleranceUnits.esriEngineSnapToleranceMapUnits;
            m_engineEditor.SnapTolerance = 2000;  

        }
Ejemplo n.º 46
0
        /// <summary>
        /// 转格式
        /// </summary>
        /// <param name="sourceWorkspacePath"></param>
        /// <param name="targetWorkspacePath"></param>
        /// <param name="sourceDataName"></param>
        /// <param name="targetDataName"></param>
        public static void ConvertFeatureClassToShapefile(string sourceWorkspacePath, string targetWorkspacePath, string sourceDataName, string targetDataName)
        {
            // Open the source and target workspaces.
              IWorkspaceFactory sourceWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
              IWorkspaceFactory targetWorkspaceFactory = new ShapefileWorkspaceFactoryClass();
              IWorkspace sourceWorkspace = sourceWorkspaceFactory.OpenFromFile(sourceWorkspacePath, 0);
              IWorkspace targetWorkspace = targetWorkspaceFactory.OpenFromFile(targetWorkspacePath, 0);

              // Cast the workspaces to the IDataset interface and get name objects.
              IDataset sourceWorkspaceDataset = (IDataset)sourceWorkspace;
              IDataset targetWorkspaceDataset = (IDataset)targetWorkspace;
              IName sourceWorkspaceDatasetName = sourceWorkspaceDataset.FullName;
              IName targetWorkspaceDatasetName = targetWorkspaceDataset.FullName;
              IWorkspaceName sourceWorkspaceName = (IWorkspaceName)sourceWorkspaceDatasetName;
              IWorkspaceName targetWorkspaceName = (IWorkspaceName)targetWorkspaceDatasetName;

              // Create a name object for the shapefile and cast it to the IDatasetName interface.
              IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass();
              IDatasetName sourceDatasetName = (IDatasetName)sourceFeatureClassName;
              sourceDatasetName.Name = sourceDataName;//"streets";
              sourceDatasetName.WorkspaceName = sourceWorkspaceName;

              // Create a name object for the FGDB feature class and cast it to the IDatasetName interface.
              IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
              IDatasetName targetDatasetName = (IDatasetName)targetFeatureClassName;
              targetDatasetName.Name = targetDataName;// "AtlantaStreets";
              targetDatasetName.WorkspaceName = targetWorkspaceName;

              // Open source feature class to get field definitions.
              IName sourceName = (IName)sourceFeatureClassName;
              IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open();

              // Create the objects and references necessary for field validation.
              IFieldChecker fieldChecker = new FieldCheckerClass();
              IFields sourceFields = sourceFeatureClass.Fields;
              IFields targetFields = null;
              IEnumFieldError enumFieldError = null;

              // Set the required properties for the IFieldChecker interface.
              fieldChecker.InputWorkspace = sourceWorkspace;
              fieldChecker.ValidateWorkspace = targetWorkspace;

              // Validate the fields and check for errors.
              fieldChecker.Validate(sourceFields, out enumFieldError, out targetFields);
              if (enumFieldError != null)
              {
            // Handle the errors in a way appropriate to your application.
            Console.WriteLine("Errors were encountered during field validation.");
              }

              // Find the shape field.
              String shapeFieldName = sourceFeatureClass.ShapeFieldName;
              int shapeFieldIndex = sourceFeatureClass.FindField(shapeFieldName);
              IField shapeField = sourceFields.get_Field(shapeFieldIndex);

              // Get the geometry definition from the shape field and clone it.
              IGeometryDef geometryDef = shapeField.GeometryDef;
              IClone geometryDefClone = (IClone)geometryDef;
              IClone targetGeometryDefClone = geometryDefClone.Clone();
              IGeometryDef targetGeometryDef = (IGeometryDef)targetGeometryDefClone;

              // Create a query filter to remove ramps, interstates and highways.
              IQueryFilter queryFilter = new QueryFilterClass();
              //queryFilter.WhereClause = "NAME <> 'Ramp' AND PRE_TYPE NOT IN ('I', 'Hwy')";
              queryFilter.WhereClause = "1=1";
              // Create the converter and run the conversion.
              IFeatureDataConverter featureDataConverter = new FeatureDataConverterClass();
              IEnumInvalidObject enumInvalidObject =
            featureDataConverter.ConvertFeatureClass(sourceFeatureClassName,
            queryFilter, null, targetFeatureClassName, targetGeometryDef, targetFields,
            "", 1000, 0);

              // Check for errors.
              IInvalidObjectInfo invalidObjectInfo = null;
              enumInvalidObject.Reset();
              while ((invalidObjectInfo = enumInvalidObject.Next()) != null)
              {
            // Handle the errors in a way appropriate to the application.
            Console.WriteLine("Errors occurred for the following feature: {0}",
              invalidObjectInfo.InvalidObjectID);
              }
        }
Ejemplo n.º 47
0
        public bool CreateMxd(string sMxdTemplate,
                              string sPathToMXD,
                              string ArcGISServer,
                              string sMxdFile,
                              string sDBConn,
                              string sDataSet,
                              bool bSde)
        {
            if (sMxdTemplate.Length > 0) _sMxdTemplate = sMxdTemplate;

            _sPathToMXD = sPathToMXD;
            _ArcGISServer = ArcGISServer;
            ESRI.ArcGIS.Carto.IMap pMap = null;
            IFeatureClass pOldFC = null;
            string fcName = String.Empty;
            string sSuffix = String.Empty;

            IWorkspaceFactory2 wsf = null;
            IWorkspace2 ws2 = null;
            IFeatureWorkspace fws = null;
            IWorkspace ws = null;

            try
            {
                if (bSde)
                {
                    // Get WS for SDE
                    ws = ArcSdeWorkspaceFromFile(sDBConn);
                }
                else
                {
                    // Get WS from file GDB.   
                    wsf = new FileGDBWorkspaceFactoryClass() as IWorkspaceFactory2;
                    //if locks on gdb only path is passed in 
                    string fileGdb = sDBConn.Contains(".gdb") ? sDBConn : sDBConn;

                    if (wsf.IsWorkspace(fileGdb))
                    {
                        ws = wsf.OpenFromFile(fileGdb, 0);
                    }
                }

                if (ws == null)
                {
                    return false;
                }

                // Check if Mxd already exists
                if (File.Exists(sMxdFile))
                {
                    return false;
                }

                // Create a Mxd from Overlays Template
                pMap = PrivateCreateMxd(sMxdFile);

                ws2 = (IWorkspace2)ws;
                fws = (IFeatureWorkspace)ws;

                // Loop through all layers in MXD and repoint data source to OverlayGDB Features
                IEnumLayer pEnumLayer = pMap.get_Layers(null, true);
                pEnumLayer.Reset();
                ILayer pLayer = pEnumLayer.Next();
                while (pLayer != null)
                {
                    if (!(pLayer is IFeatureLayer))
                    {

                        pLayer = pEnumLayer.Next();
                        continue;
                    }

                    // Cast pLayer to featurelayer
                    IFeatureLayer pMapFeatureLayer = (IFeatureLayer)pLayer;
                    pOldFC = pMapFeatureLayer.FeatureClass;

                    if (pOldFC == null)
                    {
                        pLayer = pEnumLayer.Next();
                        continue;
                    }

                    // Get FC name
                    IDataset pDS = (IDataset)pOldFC;
                    fcName = pDS.Name;
                    
                    // Feature Class: <Dataset>_osm_pt, <Dataset>_osm_ln, <Dataset>_osm_ply
                    sSuffix = fcName.Substring(fcName.IndexOf("_osm_"));

                    if (String.IsNullOrEmpty(sSuffix)) continue;

                    // Check if feature class exists in GDB
                    if (ws2.get_NameExists(esriDatasetType.esriDTFeatureClass, sDataSet + sSuffix))
                    {
                        // Get feature class
                        IFeatureClass ipFC = fws.OpenFeatureClass(sDataSet + sSuffix);
                        IFeatureLayer ipFL = (IFeatureLayer)pLayer;

                        // Create IMapAdmin2 from pMap
                        IMapAdmin2 pMapAdmin2 = (IMapAdmin2)pMap;

                        // Change FeatureClass of layer to FC in FGDB
                        ipFL.FeatureClass = ipFC;
                        pMapAdmin2.FireChangeFeatureClass(pOldFC, ipFC);

                        COMUtil.ReleaseObject(ipFC);
                        ipFC = null;

                        COMUtil.ReleaseObject(ipFL);
                        ipFL = null;
                    }
                    else
                    {
                        // Remove layer from map
                        pMap.DeleteLayer(pLayer);
                    }

                    pLayer = pEnumLayer.Next();
                }

                SaveMXD(sMxdFile, pMap);

                return true;
            }
            catch (System.Runtime.InteropServices.COMException cx)
            {
                throw cx;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                COMUtil.ReleaseObject(pOldFC);
                COMUtil.ReleaseObject(fws);
                COMUtil.ReleaseObject(ws2);
                COMUtil.ReleaseObject(ws);
                COMUtil.ReleaseObject(pMap);
                COMUtil.ReleaseObject(wsf);
                pOldFC = null;
                fws = null;
                ws2 = null;
                ws = null;
                wsf = null;
                pMap = null;
                _pMapDocument = null;

                //Do not make any call to ArcObjects after ShutDownApplication()
                if (m_AOLicenseInitializer != null) m_AOLicenseInitializer.ShutdownApplication();
                m_AOLicenseInitializer = null;

            }
        }
Ejemplo n.º 48
0
        private void ImportXMLToGDB(string xmlFileName, string gdbName)
        {
            this.textBox3.Text += "xmlFileName:" + System.IO.Path.GetFileName( xmlFileName)+"\n";
            this.textBox3.SelectionStart = this.textBox3.Text.Length;
            this.textBox3.ScrollToCaret();
            IWorkspaceFactory pWSF = new FileGDBWorkspaceFactoryClass();
            IWorkspace pWS = pWSF.OpenFromFile(gdbName,0);

            IGdbXmlImport pImport = new GdbImporterClass();

            IEnumNameMapping pEnumNM = null;
            bool bHasConflicts = pImport.GenerateNameMapping(xmlFileName, pWS, out pEnumNM);
            pImport.ImportWorkspace(xmlFileName, pEnumNM, pWS, false);
        }
Ejemplo n.º 49
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;
 }
Ejemplo n.º 50
0
 public static void AddData_GDB(AxMapControl axMapControl1)
 {
     IWorkspaceFactory pWorkspaceFactory;
     IFeatureWorkspace pFeatureWorkspace;
     IFeatureLayer pFeatureLayer;
     IFeatureDataset pFeatureDataset;
     //获取当前路径和文件名
     OpenFileDialog dlg = new OpenFileDialog();
     dlg.Title = "选择图层";
     dlg.Filter = "gdb文件|*.gdb";
     if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         string strFullPath = dlg.FileName;
         if (strFullPath == "") return;
         //打开personGeodatabase,并添加图层
         pWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
         //IWorkspaceFactory pAccessWorkspaceFactory = new AccessWorkspaceFactoryClass();
         //打开工作空间并遍历数据集
         IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(strFullPath, 0);
         IEnumDataset pEnumDataset = pWorkspace.get_Datasets(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTAny);
         pEnumDataset.Reset();
         IDataset pDataset = pEnumDataset.Next();
         //如果数据集是IFeatureDataset,则遍历它下面的子类
         if (pDataset is IFeatureDataset)
         {
             pFeatureWorkspace = (IFeatureWorkspace)pWorkspaceFactory.OpenFromFile(strFullPath, 0);
             pFeatureDataset = pFeatureWorkspace.OpenFeatureDataset(pDataset.Name);
             IEnumDataset pEnumDataset1 = pFeatureDataset.Subsets;
             pEnumDataset1.Reset();
             IDataset pDataset1 = pEnumDataset1.Next();
             //如果子类是FeatureClass,则添加到axMapControl1中
             if (pDataset1 is IFeatureClass)
             {
                 pFeatureLayer = new FeatureLayerClass();
                 pFeatureLayer.FeatureClass = pFeatureWorkspace.OpenFeatureClass(pDataset1.Name);
                 pFeatureLayer.Name = pFeatureLayer.FeatureClass.AliasName;
                 axMapControl1.Map.AddLayer(pFeatureLayer);
                 axMapControl1.ActiveView.Refresh();
                 ILayer layer = axMapControl1.get_Layer(0);
                 axMapControl1.Extent = layer.AreaOfInterest;
             }
         }
     }
 }
Ejemplo n.º 51
0
 private IWorkspace OpenWorkspace(string strMDBName)
 {
     IWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
     return pWorkspaceFactory.OpenFromFile(strMDBName, 0);
 }
Ejemplo n.º 52
0
        public QAErrorStorage(string templatePgdbPath, string savePgdbPath, string errorFCName)
        {
            if (templatePgdbPath == null || templatePgdbPath.Length == 0)
                throw new ArgumentNullException("templatePgdbPath", "Cannot pass null personal geodatabase name to QAErrorStorage");

            if (savePgdbPath == null || savePgdbPath.Length == 0)
                throw new ArgumentNullException("savePgdbPath", "Cannot pass null personal geodatabase name to QAErrorStorage");

            if (errorFCName == null || errorFCName.Length == 0)
                throw new ArgumentNullException("errorFCName", "Cannot pass null featureclass name to QAErrorStorage");

            // Copy the template pgdb to the save pgdb
            if (File.Exists(templatePgdbPath) == false)
                throw new ArgumentException(templatePgdbPath + " does not exist", "templatePgdbPath");

            bool bFileExists = false;
            if (File.Exists(savePgdbPath) == true)
                bFileExists = true;
            else
                File.Copy(templatePgdbPath, savePgdbPath, false);

            // Open the new pgdb
            IWorkspaceFactory2 theFactory = new FileGDBWorkspaceFactoryClass();
            IWorkspace theWorkspace = theFactory.OpenFromFile(savePgdbPath, 0);
            if (theWorkspace == null)
                throw new ArgumentException("Could not open a copy of '" + templatePgdbPath + "' as a Personal Geodatabase", "templatePgdbPath");

            // Locate the DATA_ERRORS featureclass in the template workspace
            IFeatureClass theFC = ((IFeatureWorkspace)theWorkspace).OpenFeatureClass(errorFCName);

            if (theFC == null)
                throw new ArgumentException("The template Personal Geodatabase does not contain a featureclass named '" + errorFCName + "'", "errorFCName");

            // Check the featureclass definition
            string theMessage = this.FeatureClassSchemaCheck(theFC);
            if (theMessage != null && theMessage.Length > 0)
            {
                throw new ArgumentException(theMessage, "errorFCName");
            }

            // If we're re-using the FC, clean it out
            if (bFileExists)
                ((ITable)theFC).DeleteSearchedRows(null);

            // Clean out everything except the destination featureclass
            theMessage = this.WorkspaceCleanout(theWorkspace, errorFCName);
            if (theMessage != null && theMessage.Length > 0)
            {
                throw new ArgumentException(theMessage, "errorFCName");
            }

            this._errorFC = theFC;
        }
Ejemplo n.º 53
0
        public bool OpenErrorFeatureClass()
        {
            // Open stored errors
            try
            {
                tm.TransactionManager theTM = this.Extension.TransactionManager;
                string theFCName = this.Extension.get_SystemValue("tm.template.dataerrors.table");

                if (theTM.Current() == null)
                {
                    // This isn't tied to any transaction, so prompt the user to open a pgdb
                    OpenFileDialog theOpenDialog = new OpenFileDialog();

                    theOpenDialog.Filter = "Personal Geodatabase files (*.mdb)|*.mdb";
                    theOpenDialog.FilterIndex = 1;
                    theOpenDialog.RestoreDirectory = true;
                    theOpenDialog.Title = "Open Test Results";

                    if(theOpenDialog.ShowDialog() == DialogResult.OK)
                    {
                        IWorkspaceFactory2 theFactory = new FileGDBWorkspaceFactoryClass();
                        IWorkspace thePersonalGDB = theFactory.OpenFromFile(theOpenDialog.FileName, 0);
                        this._errors = new QAErrorStorage(thePersonalGDB, theFCName);
                        this._errors.FetchErrors();
                    }
                    else
                        return false;
                }
                else
                {
                    if (this._errors == null || this._errors.StorageWorkspace != theTM.Current().PGDBConnection)
                    {
                        this._errors = new QAErrorStorage(theTM.Current().PGDBConnection, theFCName);
                        this._errors.FetchErrors();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error raised when opening error storage:" + Environment.NewLine
                    + ex.Message,
                    "Error Storage Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                util.Logger.Write("Error raised when opening error storage:" + Environment.NewLine
                    + ex.Message + Environment.NewLine + ex.StackTrace);
                return false;
            }
            return true;
        }
Ejemplo n.º 54
0
 /// <summary>
 /// check exists file geodatabase
 /// </summary>
 /// <param name="pathFileName">path and name of geodatabase</param>
 /// <returns>true if exists</returns>
 internal static bool ExistsFileGdb(string pathFileName)
 {
     IWorkspaceFactory2 wsf = new FileGDBWorkspaceFactoryClass() as IWorkspaceFactory2;
     return wsf.IsWorkspace(pathFileName);
 }
Ejemplo n.º 55
0
        private IFeatureClass loadFeatureClassFromGDB(string name)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            //dlg.Filter="GDB |*.gdb";
            //dlg.InitialDirectory=@"E:\";
            //dlg.Title="Locating in GDB";
            IFeatureClass feacls = null;

            if (DialogResult.OK == dlg.ShowDialog())
            {
                IWorkspace workspace;
                IWorkspaceFactory wsFact = new FileGDBWorkspaceFactoryClass();
                workspace = wsFact.OpenFromFile(dlg.SelectedPath, 0);
                IEnumDataset enumDataset = workspace.get_Datasets(esriDatasetType.esriDTFeatureClass);
                enumDataset.Reset();
                IDataset dataset = enumDataset.Next();
                while (dataset != null)
                {
                    if (string.Equals(dataset.Name, name))
                    {
                        feacls = dataset as IFeatureClass;
                        break;
                    }
                    dataset = enumDataset.Next();

                }
            }

            return feacls;
        }
Ejemplo n.º 56
0
        static void Main(string[] args)
        {
            ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Server);
            IAoInitialize aoInit = new AoInitializeClass();
            aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcServer);

            IWorkspaceFactory2 workspaceFactory = new FileGDBWorkspaceFactoryClass();
            string workspacePath = "C:\\Users\\Administrator\\Documents\\ArcGIS\\Default.gdb";
            IWorkspace ws = workspaceFactory.OpenFromFile(workspacePath, 0);
            IFeatureWorkspace workspace = ws as IFeatureWorkspace;

            IFeatureClass inFC = workspace.OpenFeatureClass("test");

            CopyAndLabel(inFC, workspace, "labeled_0");
        }
Ejemplo n.º 57
0
        /// <summary>
        /// Open a table class from a GDB
        /// </summary>
        /// <param name="conFilePath">Path to GDB workspace</param>
        /// <param name="tabName">Table name</param>
        /// <param name="fdsName">Optional feature dataset name</param>
        /// <returns></returns>
        public static ITable openTableFromGDB(string conFilePath, string tabName, string fdsName = "")
        {
            ITable table = null;
            IWorkspaceFactory factory = new FileGDBWorkspaceFactoryClass();

            IWorkspace workspace = factory.OpenFromFile(conFilePath, 0);
            IFeatureWorkspace featWorkspace = (IFeatureWorkspace)workspace;

            if (fdsName != "")
            {
                IFeatureDataset featdataset = featWorkspace.OpenFeatureDataset(fdsName);
                IFeatureWorkspace datasetWorkspace = (IFeatureWorkspace)featdataset.Workspace;
                table = datasetWorkspace.OpenTable(tabName);
            }
            else
            {
                table = featWorkspace.OpenTable(tabName);
            }
            return table;
        }
Ejemplo n.º 58
0
        /// <summary>
        /// 创建PGDB数据源
        /// </summary>
        private IWorkspace CreateWorkspace()
        {
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
            int nIndex = m_strFilePathName.LastIndexOf("\\");
            string sPath = m_strFilePathName.Remove(nIndex);
            string sName = m_strFilePathName.Substring(nIndex + 1) ;
            IWorkspaceName workspaceName = workspaceFactory.Create(sPath,
                sName, null, 0);

            // Cast the workspace name object to the IName interface and open the workspace.
            IName name = (IName)workspaceName;
            IWorkspace workspace = (IWorkspace)name.Open();
            return workspace;
        }
Ejemplo n.º 59
0
        public bool CommitTransaction(string comment)
        {
            bool result = false;

            // get the path
            string pgdbDirectory = "";
            string pgdbFile = "";
            string mxdFile = "";
            // get the see ID
            string seeID = "";

            try
            {
                Logger.Write("Testing valid tranasaction state...");

                if (BaseTransactionManager.Current() == null)
                {
                    throw new Exception("The current transaction manager has timed out. Please reload ArcMap. Transaction is no longer valid.");
                }

                if (BaseTransactionManager.Current().PGDB == null)
                {
                    throw new Exception("The current transaction manager has timed out. Please reload ArcMap. FGDB reference is no longer valid.");
                }

                bool usePgdbDirectory = false;
                if (BaseTransactionManager.Current().MXD == null)
                {
                    // check the PGDB directory
                    if (Directory.Exists(BaseTransactionManager.Current().PGDB.DirectoryName) && !File.Exists(BaseTransactionManager.Current().PGDB.DirectoryName + "\\" + BaseTransactionManager.Current().PGDB.Name.Replace(".gdb", ".mxd")))
                    {
                        usePgdbDirectory = true;
                        BaseTransactionManager.Current().MXD = new FileInfo(BaseTransactionManager.Current().PGDB.DirectoryName + "\\" + BaseTransactionManager.Current().PGDB.Name.Replace(".gdb", ".mxd"));
                    }
                    else throw new Exception("The current transaction manager has timed out. Please reload ArcMap. MXD reference is no longer valid.");
                }

                if (string.IsNullOrEmpty(BaseTransactionManager.Current().TxId))
                {
                    throw new Exception("The current transaction manager has timed out. Please reload ArcMap. SEE ID reference is no longer valid.");
                }

                BaseTransactionManager.startHourGlass("Creating Temproary Directory...");

                try
                {
                    pgdbDirectory = BaseTransactionManager.Current().PGDB.DirectoryName;
                    pgdbFile = BaseTransactionManager.Current().PGDB.Name;
                    mxdFile = usePgdbDirectory ? BaseTransactionManager.Current().PGDB.DirectoryName + "\\" + BaseTransactionManager.Current().PGDB.Name.Replace(".gdb", ".mxd") : BaseTransactionManager.Current().MXD.DirectoryName + "\\" + BaseTransactionManager.Current().MXD.Name;
                    // get the see ID
                    seeID = BaseTransactionManager.Current().TxId;
                    Logger.Write("Located transaction documents at " + pgdbDirectory);
                }
                catch (Exception parseEx)
                {
                    Logger.Write("Could not locate FGDB directory. " + parseEx.Message);
                    throw new Exception(parseEx.Message + ". An error occured reading the transaction directories from Metadata. Please ensure you're FGDB and MXD exist in the correct metadata location.");
                }

                if (!Directory.Exists(pgdbDirectory + "\\temp\\"))
                {
                    Logger.Write("Creating temporary directory...");
                    Directory.CreateDirectory(pgdbDirectory + "\\temp\\");
                }
                else
                {
                    Logger.Write("Deleting old temporary directory...");
                    Directory.Delete(pgdbDirectory + "\\temp\\", true);
                    Logger.Write("Creating temporary directory...");
                    Directory.CreateDirectory(pgdbDirectory + "\\temp\\");
                }

                BaseTransactionManager.Close();

                //Marshal.ReleaseComObject(BaseTransactionManager.Current().PGDBConnection);
                //BaseTransactionManager.Current().PGDB = null;

                // close the PGDB, maintain the file state
                SystemDefaults defaults = new SystemDefaults();

                BaseTransactionManager.app.SaveDocument(null);
                BaseTransactionManager.app.NewDocument(false, defaults.get_Default("tm.temp"));

                GC.Collect();

                BaseTransactionManager.startHourGlass("Creating transaction FGDB Backup...");
                Logger.Write("Creating transaction backup");

                // create temp file of PGDB
                IWorkspaceName sourceWS = (IWorkspaceName)new WorkspaceName();
                sourceWS.WorkspaceFactoryProgID = "esriDataSourcesGDB.FileGDBWorkspaceFactory";
                sourceWS.PathName = pgdbDirectory + "\\" + pgdbFile;

                IWorkspaceFactory2 wf2 = new FileGDBWorkspaceFactoryClass();
                IWorkspaceName wsResult = null;
                wf2.Copy(sourceWS, pgdbDirectory + "\\temp\\", out wsResult);

                string tempFileLocation = "";

                if (wsResult != null) tempFileLocation = pgdbDirectory + "\\temp\\" + pgdbFile;
                else throw new Exception("Commit failed. Could not create temporary transaction file.");

                Marshal.ReleaseComObject(wf2);
                Marshal.ReleaseComObject(wsResult);
                wf2 = null;
                wsResult = null;

                Logger.Write("Renaming transaction backup to see ID: " + seeID.Replace("-", "").ToUpper());

                string newTempFolder = pgdbDirectory + "\\temp\\" + seeID.Replace("-", "").ToUpper() + ".gdb";

                Directory.Move(pgdbDirectory + "\\temp\\" + pgdbFile, newTempFolder);

                BaseTransactionManager.startHourGlass("Creating ZIP file...");
                Logger.Write("Creating Zip File...");

                // zip the temp folder.
                ZipFile zip = new ZipFile();
                zip.AddDirectory(pgdbDirectory + "\\temp\\");
                zip.Save(newTempFolder + ".zip");
                zip = null;

                // flag the transaction as checked in. Once complete, we'll set the flag back to checked out on an error, or complete on success
                //SetTransactionStatus("CHECKED_IN", "The Transaction has been checked in", seeID);

                BaseTransactionManager.startHourGlass("Waiting for SUITT FME Server. This may take a while...");
                Logger.Write("Subitting transaction...");

                RestRequest checkinRequest = ClientRequest("sees/" + seeID + "/features", Method.POST, true);
                checkinRequest.RequestFormat = DataFormat.Json;
                checkinRequest.AddFile("file", File.ReadAllBytes(newTempFolder + ".zip"), seeID.Replace("-", "").ToUpper() + ".gdb.zip");

                var checkinResponse = ApplicationClient.Execute(checkinRequest);
                if (checkinResponse.StatusCode == System.Net.HttpStatusCode.Accepted)
                {
                    Logger.Write("Submission successful, completeing transaction...");
                    result = CompleteCheckin(seeID, comment);
                }
                else
                {
                    string[] status = GetTransactionStatus(seeID);

                    MessageBox.Show("An error has occured commiting the transaction, and could not be completed at this time. Please verify your transaction is valid, with no spatial errors, and your transaction does not conflict with other transactions.");
                    SetTransactionStatus("CHECKED_OUT", "The Transaction has been checked out", seeID);
                }
            }
            catch (Exception e)
            {
                result = false;
                MessageBox.Show("An error has occured while committing your transaction: " + e.Message + Environment.NewLine + e.StackTrace);
                Logger.Write("#### COMMIT TRANSACTION ENDED: " + e + Environment.NewLine + e.StackTrace);
                SetTransactionStatus("CHECKED_OUT", "The Transaction has been checked out", seeID);
            }

            if (result)
            {
                MessageBox.Show("Transaction check-in completed successfully. No check-in errors were reported. Click 'OK' to clean up your ArcMap session and close the completed transaction.");

                BaseTransactionManager.Close();

                SystemDefaults defaults = new SystemDefaults();
                BaseTransactionManager.app.NewDocument(false, defaults.get_Default("tm.temp"));
            }
            else
            {
                if(!string.IsNullOrEmpty(mxdFile)) BaseTransactionManager.app.OpenDocument(mxdFile);
                MessageBox.Show("Transaction check-in did not complete successfully. Please review the log for errors");
            }

            return result;
        }
Ejemplo n.º 60
0
        static void Main(string[] args)
        {
            TileInfo tiles = new TileInfo() {
                dpi = 96,
                width = 256,
                height = 256,
                originX = -20037508.342787,
                originY = 20037508.342787,
                lods = new LOD[] {
                    new LOD() {
                        level = 0,
                        resolution = 156543.033928,
                        scale = 591657527.591555
                    },
                    new LOD() {
                        level = 1,
                        resolution = 78271.5169639999,
                        scale = 295828763.795777
                    },
                    new LOD() {
                        level = 2,
                        resolution = 39135.7584820001,
                        scale = 147914381.897889
                    },
                    new LOD() {
                        level = 3,
                        resolution = 19567.8792409999,
                        scale = 73957190.948944
                    }
                },
                spatialReference = 102100
            };

            ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Server);
            IAoInitialize aoInit = new AoInitializeClass();
            aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcServer);

            IWorkspaceFactory2 workspaceFactory = new FileGDBWorkspaceFactoryClass();
            string workspacePath = "C:\\Users\\Administrator\\Documents\\ArcGIS\\Default.gdb";
            IWorkspace ws = workspaceFactory.OpenFromFile(workspacePath, 0);
            IFeatureWorkspace workspace = ws as IFeatureWorkspace;

            CreateGrid(tiles, 0, workspace, "Tiles_0");
            CreateGrid(tiles, 1, workspace, "Tiles_1");
            CreateGrid(tiles, 2, workspace, "Tiles_2");
            CreateGrid(tiles, 3, workspace, "Tiles_3");
        }