Example #1
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);
        }
Example #2
0
        public static IWorkspace OpenGDBWorkspace(this string filePath)
        {
            IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
            IWorkspace        workspace        = workspaceFactory.OpenFromFile(filePath, 0);

            return(workspace);
        }
Example #3
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;
            }
        }
Example #4
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;
        }
Example #6
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);
        }
Example #7
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);
        }
Example #8
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;
                }
            }
        }
Example #9
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;
                }
            }
        }
Example #10
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);
        }
Example #11
0
        public IWorkspace getFGDBWorkspace(string gdbfilepath)
        {
            IWorkspaceFactory pWsFac = new FileGDBWorkspaceFactoryClass();
            IWorkspace        pWs    = pWsFac.OpenFromFile(gdbfilepath, 0);

            return(pWs);
        }
Example #12
0
        //打开工作区间
        public static IWorkspace OpenWorkspace(string strGDBName)
        {
            IWorkspaceFactory workspaceFactory;

            workspaceFactory = new FileGDBWorkspaceFactoryClass();
            return(workspaceFactory.OpenFromFile(strGDBName, 0));
        }
Example #13
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;
        }
Example #14
0
        /// <summary>
        /// 获取GDB或MDB工作空间
        /// </summary>
        /// <param name="path">gdb或mdb数据库路径</param>
        /// <returns>gdb或mdb工作空间</returns>
        public static IWorkspace GetWorkspace(String path)
        {
            IWorkspaceFactory workspaceFactory;
            IWorkspace        workspace = null;

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

            return(workspace);
        }
Example #15
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);
     }
 }
Example #16
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);
        }
Example #17
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;
        }
Example #18
0
        /// <summary>
        /// 创建数据表
        /// </summary>
        /// <param name="_TablePath"></param>
        /// <param name="_TableName"></param>
        /// <returns></returns>
        public ITable CreateTable(string _TablePath, string _TableName)
        {
            IWorkspaceFactory pWks = new FileGDBWorkspaceFactoryClass();
            IFeatureWorkspace pFwk = pWks.OpenFromFile(_TablePath, 0) as IFeatureWorkspace;

            ESRI.ArcGIS.Geodatabase.IObjectClassDescription objectClassDescription = new ESRI.ArcGIS.Geodatabase.ObjectClassDescriptionClass();
            IFields     pTableFields     = objectClassDescription.RequiredFields;
            IFieldsEdit pTableFieldsEdit = pTableFields as IFieldsEdit;
            IField      pField           = null;
            IFieldEdit  pFieldEdit       = null;

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                DataColumn dc = dt.Columns[i];
                pField            = new FieldClass();
                pFieldEdit        = pField as IFieldEdit;
                pFieldEdit.Name_2 = dc.ColumnName;
                switch (dc.DataType.ToString())
                {
                case "System.Double":
                    pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
                    break;

                case "System.String":
                    pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                    break;
                }
                pTableFieldsEdit.AddField(pField);
            }

            ITable pTable = pFwk.CreateTable(_TableName, pTableFields, null, null, "");

            return(pTable);
        }
Example #19
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); }
            }
        }
Example #20
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);
        }
Example #21
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));
        }
Example #22
0
 public static IFeatureWorkspace GetIFeatureWorkspace(string gdbPath = @"D:\dmSoftwareSource\测试.gdb")
 {
     if (Workapace == null)
     {
         FileGDBWorkspaceFactoryClass fac = new FileGDBWorkspaceFactoryClass();
         Workapace = (IFeatureWorkspace)fac.OpenFromFile(gdbPath, 0);
     }
     return(Workapace);
 }
Example #23
0
        private void 现势性检查ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IWorkspaceFactory pFileGDBWorkspaceFactory;

            pFileGDBWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
            IWorkspace   pWorkspace   = pFileGDBWorkspaceFactory.OpenFromFile(Path, 0);
            IEnumDataset pEnumDataset = pWorkspace.get_Datasets(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTAny);

            pEnumDataset.Reset();
            IDataset  pDataset        = pEnumDataset.Next();
            DataTable SpatialRefTable = new DataTable();

            SpatialRefTable.Columns.Add(new DataColumn("影像名称", typeof(string)));
            SpatialRefTable.Columns.Add(new DataColumn("影像拍摄时间", typeof(string)));
            SpatialRefTable.Columns.Add(new DataColumn("时间现势性检查", typeof(string)));

            //判断数据集是否有数据
            while (pDataset != null)
            {
                if (pDataset is IRasterDataset) //栅格数据集
                {
                    IRasterWorkspaceEx pRasterWorkspace = (IRasterWorkspaceEx)pWorkspace;
                    IRasterDataset     pRasterDataset   = pRasterWorkspace.OpenRasterDataset(pDataset.Name);
                    //影像金字塔判断与创建
                    ISpatialReference pSpatialRef = (pRasterDataset as IGeoDataset).SpatialReference;
                    string            spatialref  = pSpatialRef.Name.ToString();
                    string            rastername  = pDataset.Name.ToString();
                    string[]          strArray    = rastername.Split('_');

                    DataRow dr = SpatialRefTable.NewRow();
                    dr["影像名称"]   = pDataset.Name.ToString();
                    dr["影像拍摄时间"] = strArray[1].Substring(0, 8);
                    IRasterLayer pRasterLayer = new RasterLayerClass();
                    pRasterLayer.CreateFromDataset(pRasterDataset);
                    if (int.Parse(strArray[1].Substring(0, 8)) < 20170000 && int.Parse(strArray[1].Substring(0, 8)) > 20120000)
                    {
                        dr["时间现势性检查"] = "√";
                    }
                    else
                    {
                        dr["时间现势性检查"] = "×";
                    }
                    SpatialRefTable.Rows.Add(dr);
                }
                pDataset = pEnumDataset.Next();
            }
            // ExportExcel(SpatialRefTable);
            //弹出显示框
            TimeCheck tc = new TimeCheck();

            tc.Text = "影像质量检查";
            tc.dataGridView1.DataSource       = SpatialRefTable;
            tc.dataGridView1.Columns[1].Width = 200;
            tc.dataGridView1.Columns[2].Width = 300;
            tc.Show();
        }
Example #24
0
 private void button1_Click(object sender, EventArgs e)
 {
     if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
     {
         string            path             = folderBrowserDialog1.SelectedPath;
         IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass();
         IWorkspace        workspace        = workspaceFactory.OpenFromFile(path, 0);
         featureworkspace = (IFeatureWorkspace)workspace;
     }
 }
Example #25
0
        public static IFeatureClass GetFeatureClass(string datasource, DataSourceType dataSourceType, string featureClassName)
        {
            IWorkspace workspace = null;

            switch (dataSourceType)
            {
            case DataSourceType.SdeFilePath:
            {
                SdeWorkspaceFactory sdeWorkspaceFactory = new SdeWorkspaceFactoryClass();
                workspace = sdeWorkspaceFactory.OpenFromFile(datasource, 1);
            }
            break;

            case DataSourceType.SdeTxt:
                throw new NotImplementedException();
                break;

            case DataSourceType.SdeJson:
                throw new NotImplementedException();
                break;

            case DataSourceType.GdbFilePath:
            {
                FileGDBWorkspaceFactory fileGDBWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
                workspace = fileGDBWorkspaceFactory.OpenFromFile(datasource, 1);
            }
                //throw new NotImplementedException();
                break;

            case DataSourceType.ShapefilePath:
                throw new NotImplementedException();
                break;

            default:
                break;
            }

            var featureWorkspace = (IFeatureWorkspace)workspace;


            IFeatureClass tryOpenFeatureClass;

            try
            {
                tryOpenFeatureClass = featureWorkspace.OpenFeatureClass(featureClassName);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            //((IFeatureWorkspace)workspace).CreateFeatureClass()

            return(featureWorkspace.OpenFeatureClass(featureClassName));
        }
Example #26
0
        // 从地理数据库中加载栅格数据
        private void AddRasterFromGDB(string rastername)
        {
            FileGDBWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
            IWorkspace         pWorkspace             = pWorkspaceFactory.OpenFromFile(DATADIR + "Database.gdb", 0);
            IRasterWorkspaceEx pRasterWorkspace       = pWorkspace as IRasterWorkspaceEx;
            IRasterDataset     pRasterDataset         = pRasterWorkspace.OpenRasterDataset(rastername);
            IRasterLayer       pRasterLayer           = new RasterLayerClass();

            pRasterLayer.CreateFromDataset(pRasterDataset);
            m_pMapC2.AddLayer(pRasterLayer);
        }
Example #27
0
 private IWorkspace OpenFileGDBWorkspace(string gdbPath)
 {
     try
     {
         IWorkspaceFactory wsf = new FileGDBWorkspaceFactoryClass();
         return(wsf.OpenFromFile(gdbPath, 0));
     }
     catch
     {
         return(null);
     }
 }
Example #28
0
        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);
        }
Example #29
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);
        }
Example #30
0
        /// <summary>
        /// 打开实体表
        /// </summary>
        /// <param name="name">实体表名称</param>
        /// <param name="path">实体表路径</param>
        /// <returns></returns>
        private ITable OpenEntityTable(string name, string path)
        {
            ITable             result            = null;
            IWorkspaceFactory2 pWorkspaceFactory = new FileGDBWorkspaceFactoryClass() as IWorkspaceFactory2;
            IWorkspace2        pWorkspace        = pWorkspaceFactory.OpenFromFile(path, 0) as IWorkspace2;
            IFeatureWorkspace  featureWorkspace  = pWorkspace as IFeatureWorkspace;

            if (pWorkspace.get_NameExists(esriDatasetType.esriDTTable, name))
            {
                result = featureWorkspace.OpenTable(name);
            }
            return(result);
        }
Example #31
0
        /// <summary>
        /// 打开Workspace
        /// </summary>
        /// <param name="wsType"></param>
        /// <param name="objWorkspace">当为SDE时使用IPropertySet,其余情况使用路径(string)</param>
        /// <returns></returns>
        public static IWorkspace OpenWorkspace(enumWorkspaceType wsType, object objWorkspace)
        {
            IWorkspaceFactory wsf = null;
            try
            {
                switch (wsType)
                {
                    case enumWorkspaceType.FileGDB:
                        wsf = new FileGDBWorkspaceFactoryClass();

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

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

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

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

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

            return null;
        }
 public static IWorkspace GetFGDBWorkspace(string sFilePath)
 {
     if (!System.IO.Directory.Exists(sFilePath))
     {
         return null;
     }
     try
     {
         IWorkspaceFactory factory = new FileGDBWorkspaceFactoryClass();
         return factory.OpenFromFile(sFilePath, 0);
     }
     catch
     {
         return null;
     }
 }
        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;
            }
        }
        /// <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;
        }
Example #35
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;
        }
Example #36
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);
        }
Example #37
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;
 }
        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;
        }
Example #39
0
        private void btnChangeY_Click(object sender, EventArgs e)
        {
            maploaded = true;
            System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;
            if ((cboBotYear.Text != "") && (cboTopYear.Text != ""))
            {
                label3.Text = cboTopYear.Text;
                label4.Text = cboBotYear.Text;
                if (!(topPublicMosaicLayer == null))
                {
                    //Delete old top layer, ??check still the same top to save time?
                    m_MapControl.ActiveView.FocusMap.DeleteLayer((ILayer)topPublicMosaicLayer);
                    m_MapControltop.ActiveView.FocusMap.DeleteLayer((ILayer)topPublicMosaicLayer);
                }
                if (!(botPublicMosaicLayer == null))
                {
                    //Delete old bot layer, ??check still the same bot to save time?
                    m_MapControl.ActiveView.FocusMap.DeleteLayer((ILayer)botPublicMosaicLayer);
                    m_MapControlbase.ActiveView.FocusMap.DeleteLayer((ILayer)botPublicMosaicLayer);
                }
                //This version, we will use mosaicdataset========================
                IMosaicWorkspaceExtensionHelper MosaicWsHelper = new MosaicWorkspaceExtensionHelperClass();
                IWorkspaceFactory2 workspaceFactory = new FileGDBWorkspaceFactoryClass();
                string mosaicdatabase = ConfigurationManager.AppSettings["MosaicDatabase"];
                IWorkspace ws = workspaceFactory.OpenFromFile(mosaicdatabase, 0);
                IMosaicWorkspaceExtension mosaicWsExtension = MosaicWsHelper.FindExtension(ws);

                //BOT
                strBaseYr = "AmherstOrthoMosaic" + cboBotYear.Text;
                IMosaicDataset pMosaicDatasetBot = mosaicWsExtension.OpenMosaicDataset(strBaseYr);
                botPublicMosaicLayer = new MosaicLayerClass();
                botPublicMosaicLayer.CreateFromMosaicDataset(pMosaicDatasetBot);
                if (!(botPublicMosaicLayer == null))
                {
                    IFeatureLayer footprint = (IFeatureLayer)botPublicMosaicLayer.FootprintLayer;
                    ((ILayer)footprint).Visible = false;
                    ILayer botLayer = (ILayer)botPublicMosaicLayer;
                    botLayer.MinimumScale = 6000;
                    m_MapControl.ActiveView.FocusMap.AddLayer(botLayer);
                    m_MapControlbase.ActiveView.FocusMap.AddLayer(botLayer);
                }
                //TOP
                strTopYr = "AmherstOrthoMosaic" + cboTopYear.Text;
                IMosaicDataset pMosaicDatasetTop = mosaicWsExtension.OpenMosaicDataset(strTopYr);
                topPublicMosaicLayer = new MosaicLayerClass();
                topPublicMosaicLayer.CreateFromMosaicDataset(pMosaicDatasetTop);
                if (!(topPublicMosaicLayer == null))
                {
                    IFeatureLayer footprint = (IFeatureLayer)topPublicMosaicLayer.FootprintLayer;
                    ((ILayer)footprint).Visible = false;
                    ILayer topLayer = (ILayer)topPublicMosaicLayer;
                    topLayer.MinimumScale = 6000;
                    m_MapControl.ActiveView.FocusMap.AddLayer(topLayer);
                    m_MapControltop.ActiveView.FocusMap.AddLayer(topLayer);
                    ILayerEffectProperties lepSwip = m_CommandsEnvironment as ILayerEffectProperties;
                    lepSwip.SwipeLayer = topLayer;
                    //===possible problem toplayer is not public variable any more
                }

                IFeatureLayer featurelayerParcel = new FeatureLayerClass();
                featurelayerParcel.FeatureClass = featureClassParcels;
                featurelayerParcel.Name = "parcels";
                featurelayerParcel.MinimumScale = 6000;
                featurelayerParcel.Visible = false;
                IRgbColor pLColor = new RgbColorClass();
                pLColor.Red = 255;
                pLColor.Green = 255;
                pLColor.Blue = 255;

                ISimpleFillSymbol pSFS = new SimpleFillSymbolClass();
                ICartographicLineSymbol pCLineS = new CartographicLineSymbolClass();
                pCLineS.Color = pLColor;
                ILineProperties lineProperties = pCLineS as ILineProperties;
                lineProperties.Offset = 0;
                System.Double[] hpe = new System.Double[4];
                hpe[0] = 7;
                hpe[1] = 2;
                hpe[2] = 1;
                hpe[3] = 2;

                ITemplate template = new TemplateClass();
                template.Interval = 3;
                for (int i = 0; i < hpe.Length; i = i + 2)
                {
                    template.AddPatternElement(hpe[i], hpe[i + 1]);
                }
                lineProperties.Template = template;
                pCLineS.Width = 1;
                pCLineS.Cap = esriLineCapStyle.esriLCSButt;
                pCLineS.Join = esriLineJoinStyle.esriLJSBevel;
                pCLineS.Color = pLColor;
                pSFS.Outline = pCLineS;
                pSFS.Style = esriSimpleFillStyle.esriSFSHollow;

                IGeoFeatureLayer pGFL = (IGeoFeatureLayer)featurelayerParcel;
                ISimpleRenderer pRend = pGFL.Renderer as ISimpleRenderer;
                pRend.Symbol = pSFS as ISymbol;

                if ((Helper.FindMyFeatureLayer(m_MapControl.ActiveView.FocusMap, "parcels") == null))
                {
                    if (!(featurelayerParcel == null))
                    {
                        m_MapControl.ActiveView.FocusMap.AddLayer(featurelayerParcel);
                        m_MapControltop.ActiveView.FocusMap.AddLayer(featurelayerParcel);
                        m_MapControlbase.ActiveView.FocusMap.AddLayer(featurelayerParcel);
                    }
                }
                else
                {
                    //is this temp necessary???????
                    IFeatureLayer parcellayertemp = Helper.FindMyFeatureLayer(m_MapControl.ActiveView.FocusMap, "parcels");
                    m_MapControl.ActiveView.FocusMap.MoveLayer(parcellayertemp, 0);
                    m_MapControltop.ActiveView.FocusMap.MoveLayer(parcellayertemp, 0);
                    m_MapControlbase.ActiveView.FocusMap.MoveLayer(parcellayertemp, 0);
                }
                //MessageBox.Show("Top aerophoto is taken on: " + cboTopYear.Text + ".\r\nBottom areophoto is taken on: " + cboBotYear.Text + ".");
            }
            else
            {
                MessageBox.Show("Please select two years to compare");

            }
            GeneratePageLayout();
            System.Windows.Forms.Cursor.Current = Cursors.Default;
        }
        /// <summary>
        /// 按Code值进行拆分
        /// </summary>
        /// <param name="path">源数据路径</param>
        /// <param name="outPath">输出路径</param>
        /// <param name="FiledName">字段名称</param>
        public void Select(string path, string outPath, string FiledName)
        {
            //创建工作空间
            IWorkspaceFactory pwokspace = new FileGDBWorkspaceFactoryClass();
            IWorkspace workspace = pwokspace.OpenFromFile(path, 0);
            IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)workspace;
            //新建GP
            gp.SetEnvironmentValue("workspace", path);
            //获取工作空间下要素类
            IGpEnumList featureClasses = gp.ListFeatureClasses("", "", "");//直接搜索featureClass;
            string featureClass = featureClasses.Next();
            while (featureClass != "")
            {
                IFeatureClass pFeatureClass = pFeatureWorkspace.OpenFeatureClass(featureClass);
                int f = pFeatureClass.FindField(FiledName);
                if (f == -1)//判断字段是否存在
                {
                    featureClass = featureClasses.Next();
                    continue;
                }
                Export2Shp(gp, pFeatureClass, FiledName, outPath);//转换函数

                featureClass = featureClasses.Next();
            }
            //RasterCatalog rasterCatalog = ;

            //IGpEnumList rasterCatalog = gp.ListDatasets("", "");
            //string rasterCalog = rasterCatalog.Next();
            //while (rasterCalog != "")
            //{
            //    MessageBox.Show(rasterCalog);
            //    rasterCalog = rasterCatalog.Next();
            //}
            IGpEnumList dataSets = gp.ListDatasets("", "");//搜寻dataset;
            string dataSet = dataSets.Next();
            while (dataSet != "")
            {
                try
                {
                    IFeatureDataset pFeatureDataset = pFeatureWorkspace.OpenFeatureDataset(dataSet);
                    IFeatureClassContainer pFCC = (IFeatureClassContainer)pFeatureDataset;
                    IEnumFeatureClass pEnumFeatureClass = pFCC.Classes;
                    IFeatureClass m_FeatureClass = pEnumFeatureClass.Next();
                
                if(dataSet=="SchemeRasterData")//提取栅格数据集
                {/*说明:每个方案中对应的需要提取出来的数据有:
                  * 1)到达时间2)淹没水深3)淹没历时4)淹没图。
                  * 四种数据在不同方案中对应不同的数据
                  * 要求:方案1_“四种数据名称”;
                  * 在方案1中:OBJECTID=9(到达时间)
                  */

                }
                else if (dataSet == "RiskDataUnk")//专题图数据提取
                {
                    string ztdtFolder=importTool.createFolder(outPath_Mid + "\\ztdt");
                    string bxzyFolder = importTool.createFolder(outPath_Mid + "\\bhzy");
                    while (m_FeatureClass != null)
                    {
                        if (m_FeatureClass.AliasName == "进水口" || m_FeatureClass.AliasName == "进水口线" || m_FeatureClass.AliasName == "洪水流速" || m_FeatureClass.AliasName == "等时线")
                        {
                            ExtractShpData(gp, m_FeatureClass, ztdtFolder);
                            m_FeatureClass = pEnumFeatureClass.Next();
                        }
                        else
                        {
                            if (m_FeatureClass.AliasName.Substring(0, 3) == "等时线")
                                m_FeatureClass = pEnumFeatureClass.Next();
                            else
                            {
                                ExtractShpData(gp, m_FeatureClass, bxzyFolder);
                                m_FeatureClass = pEnumFeatureClass.Next();
                            }
                        }
                        
                    }
                    dataSet = dataSets.Next();
                }
                else if (dataSet == "HydroBaseDataUnk")//定量的寻找该数据集
                {
                    try
                    {
                        //对dataset中的fetureclass的一个循环获取
                        while (m_FeatureClass != null)
                        {
                            string na = m_FeatureClass.AliasName.Substring(m_FeatureClass.AliasName.Length - 2);
                            if (na == "A3")
                            {
                                m_FeatureClass = pEnumFeatureClass.Next();
                            }
                            else
                            {
                                int f = m_FeatureClass.FindField(FiledName);//判断code字段是否存在
                                try
                                {
                                    if (f != -1)//判断是否有code字段
                                    {
                                        Export2Shp(gp, m_FeatureClass, FiledName, outPath);
                                        m_FeatureClass = pEnumFeatureClass.Next();
                                    }
                                    else
                                        m_FeatureClass = pEnumFeatureClass.Next();
                                }
                                catch(Exception ex)
                                {
                                    MessageBox.Show(ex.Message + "1号监视");
                                    m_FeatureClass = pEnumFeatureClass.Next();
                                }
                            }
                        }
                        dataSet = dataSets.Next();
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show(ex.Message + "2号监视");
                        dataSet = dataSets.Next();
                    }
                }
                else
                    dataSet = dataSets.Next();
                }
                catch
                {
                    dataSet = dataSets.Next();
                }
            }
        }
Example #41
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");
        }
Example #42
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;
        }
Example #43
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);
              }
        }
Example #44
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;
        }
        /// <summary>
        /// 打开文件数据库
        /// </summary>
        /// <param name="_pGDBName"></param>
        /// <returns></returns>
        public IWorkspace GetFGDBWorkspace(String _pGDBName)
        {
            IWorkspaceFactory pWsFac = new FileGDBWorkspaceFactoryClass();

            IWorkspace pWs = pWsFac.OpenFromFile(_pGDBName, 0);

            return pWs;
        }
Example #46
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");
        }
Example #47
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;
             }
         }
     }
 }
Example #48
0
 private IWorkspace OpenWorkspace(string strMDBName)
 {
     IWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
     return pWorkspaceFactory.OpenFromFile(strMDBName, 0);
 }
    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;
    }
        /// <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;
        }
Example #51
0
        /// <summary>
        /// 连接GDB的Workspace
        /// </summary>
        /// <param name="Path">GDB路径</param>
        public IWorkspace Workspace_GDB(string Path)
        {
            IWorkspaceFactory GDBWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
            IWorkspace WS = null;

            try
            {
                WS = GDBWorkspaceFactory.OpenFromFile(Path, 0);
            }
            catch
            {
                MessageBox.Show("请检查GDB路径是否正确");
            }

            return WS;
        }
Example #52
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;
        }
        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;  

        }
Example #54
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;

            }
        }
Example #55
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;
        }
        IMosaicDataset GetMosaicDataset(string pFGDBPath,string pMDame)
        {
            IWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
                  IWorkspace pFgdbWorkspace = pWorkspaceFactory.OpenFromFile(pFGDBPath, 0);

                  IMosaicWorkspaceExtensionHelper pMosaicExentionHelper = new
                      MosaicWorkspaceExtensionHelperClass();

                  IMosaicWorkspaceExtension pMosaicExtention = pMosaicExentionHelper.FindExtension(pFgdbWorkspace);

                  return pMosaicExtention.OpenMosaicDataset(pMDame);
        }