Example #1
0
        /// <summary>
        /// 创建新的FileGeodatabase
        /// </summary>
        /// <param name="ParentDirectory">创建FGDB路径</param>
        /// <param name="strName">FGDB名称</param>
        public static bool CreateFGDB(string ParentDirectory, string strName, ref IWorkspace ws)
        {
            IWorkspace ipWks = null;

            try
            {
                IWorkspaceFactory2 workspaceFactory = (IWorkspaceFactory2) new FileGDBWorkspaceFactoryClass();
                string             strFilePath      = ParentDirectory + "\\" + strName;
                if (System.IO.Directory.Exists(strFilePath))
                {
                    System.IO.Directory.Delete(strFilePath, true);
                }

                IWorkspaceName workspacename = workspaceFactory.Create(ParentDirectory, strName, null, 0);
                ipWks = ((IName)workspacename).Open() as IWorkspace;
                ws    = ipWks;
            }
            catch (Exception exp)
            {
                Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString());

                return(false);
            }
            return(true);
        }
        public static ILocatorWorkspace GetSDELocatorWorkspace(String server, String instance, String database, String authenication, String version)
        {
            // Set up the SDE connection properties
            IPropertySet connectionProperties = new PropertySetClass();

            connectionProperties.SetProperty("SERVER", server);
            //propertySet.SetProperty("DBCLIENT", dbclient);
            connectionProperties.SetProperty("INSTANCE", instance);
            connectionProperties.SetProperty("DATABASE", database);
            connectionProperties.SetProperty("AUTHENTICATION_MODE", authenication);
            connectionProperties.SetProperty("VERSION", version);
            //connectionProperties.SetProperty("USER", username);
            //connectionProperties.SetProperty("PASSWORD", pass);

            // Get the Workspace
            System.Object      obj = Activator.CreateInstance(Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory"));
            IWorkspaceFactory2 workspaceFactory = obj as IWorkspaceFactory2;
            IWorkspace         workspace        = workspaceFactory.Open(connectionProperties, 0);

            obj = Activator.CreateInstance(Type.GetTypeFromProgID("esriLocation.LocatorManager"));
            ILocatorManager2          locatorManager           = obj as ILocatorManager2;
            ILocatorWorkspace         locatorWorkspace         = locatorManager.GetLocatorWorkspace(workspace);
            IDatabaseLocatorWorkspace databaseLocatorWorkspace = (IDatabaseLocatorWorkspace)locatorWorkspace;

            return(locatorWorkspace);
        }
Example #3
0
        private void MainWnd_Load(object sender, EventArgs e)
        {
            // Get workspace and open mdb file
            IWorkspaceFactory2 wkspcFactory = (IWorkspaceFactory2) new FileGDBWorkspaceFactoryClass();
            string             filePath     = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            filePath = System.IO.Path.Combine(filePath, @"ArcGIS\data\SanFrancisco\SanFrancisco.gdb");
            IFeatureWorkspace wkspc = wkspcFactory.OpenFromFile(filePath, Handle.ToInt32()) as IFeatureWorkspace;

            //open the Geodatabase table
            ITable foundITable = wkspc.OpenFeatureClass("Parks") as ITable;

            if (null != foundITable)
            {
                // Bind dataset to the binding source
                tableWrapper = new ArcDataBinding.TableWrapper(foundITable);
                bindingSource1.DataSource = tableWrapper;

                // Bind binding source to grid. Alternatively it is possible to bind TableWrapper
                // directly to the grid to this offers less flexibility
                dataGridView1.DataSource = bindingSource1;

                // Bind binding source to text box, we are binding the NAME
                // field.
                txtBoxBinding = new Binding("Text", bindingSource1, "NAME");
                textBox1.DataBindings.Add(txtBoxBinding);
            }
        }
        /// <summary>
        /// 打开一个SDE数据连接。
        /// </summary>
        /// <param name="propertySet">连接信息。</param>
        /// <returns>工作空间。</returns>
        public static IWorkspace OpenSdeWorkspace(IPropertySet propertySet)
        {
            Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory");
            IWorkspaceFactory2 workspaceFactory = (IWorkspaceFactory2)Activator.CreateInstance(factoryType);

            return(workspaceFactory.Open(propertySet, 0));
        }
Example #5
0
        /// <summary>
        /// 打开个人数据库工作空间
        /// </summary>
        /// <param name="ppOutWS">打开的工作空间</param>
        /// <param name="strFullPath">mdb全路径</param>
        /// <returns>打开成功与否</returns>
        public static bool OpenPGDBEx(ref IWorkspace ppOutWS, string strFullPath)
        {
            try
            {
                if (!System.IO.File.Exists(strFullPath))
                {
                    return(false);
                }

                IWorkspaceFactory2 pFactory = GetWorkspaceFactory(enumDataType.PGDB);
                ppOutWS = pFactory.OpenFromFile(strFullPath, 0);
                if (pFactory != null)
                {
                    Marshal.ReleaseComObject(pFactory);
                    pFactory = null;
                }
            }
            catch (Exception exp)
            {
                Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString());

                return(false);
            }
            return(true);
        }
Example #6
0
        public static IRaster AbrirRasterDesdeGDB(string sDir, string sNombre)
        {
            try
            {
                IWorkspaceFactory2 pWorkspaceFactory2 = (IWorkspaceFactory2) new AccessWorkspaceFactoryClass();
                IRasterWorkspaceEx pRasterWorkspaceEx = (IRasterWorkspaceEx)pWorkspaceFactory2.OpenFromFile(sDir, 0);
                //IWorkspace pWorkspace = (IWorkspace)pRasterWorkspaceEx;
                //IEnumDataset pEnumDS = pWorkspace.get_Datasets(esriDatasetType.esriDTRasterDataset);
                //IDataset pDS = pEnumDS.Next();
                //while (pDS != null)
                //{
                //  if (pDS.Name.ToUpper().Equals(sNombre.ToUpper()))
                //  {
                //    IRasterDataset pRDS = (IRasterDataset)pDS;

                //  }
                //  pDS = pEnumDS.Next();
                //}
                IRasterDataset pRDS2 = pRasterWorkspaceEx.OpenRasterDataset(sNombre);
                return(pRDS2.CreateDefaultRaster());
                //IWorkspaceFactory wsFactory = new RasterWorkspaceFactoryClass();
                //IRasterWorkspace ws = (IRasterWorkspace)wsFactory.OpenFromFile(sDir, 0);
                //IRasterDataset rasterDataset = ws.OpenRasterDataset(sNombre);
                //return rasterDataset.CreateDefaultRaster();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return(null);
            }
        }
Example #7
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);
        }
Example #8
0
        /// <summary>
        /// 创建新的PersonalGeodatabase
        /// </summary>
        /// <param name="ParentDirectory">创建MDB路径</param>
        /// <param name="strName">MDB名称</param>
        public static bool CreatePGDB(string ParentDirectory, string strName)
        {
            IWorkspace Ws = null;

            try
            {
                IWorkspaceFactory2 workspaceFactory = (IWorkspaceFactory2) new AccessWorkspaceFactoryClass();
                string             strFilePath      = ParentDirectory + strName;
                if (System.IO.File.Exists(strFilePath))
                {
                    System.IO.File.Delete(strFilePath);
                }
                IWorkspaceName workspacename    = workspaceFactory.Create(ParentDirectory, strName, null, 0);
                string         connectionstring = "DATABASE=" + workspacename.PathName;
                Ws = workspaceFactory.OpenFromString(connectionstring, 0);
            }
            catch (Exception exp)
            {
                Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString());

                return(false);
            }
            finally
            {
                if (Ws != null)
                {
                    Marshal.ReleaseComObject(Ws);
                    Ws = null;
                }
            }
            return(true);
        }
Example #9
0
        /// <summary>
        /// open geodatabase from path filename
        /// </summary>
        /// <param name="path">path file name of file geodatabase</param>
        /// <returns>object Workspace</returns>
        public static IWorkspace OpenFGDB(string path)
        {
            Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
            IWorkspaceFactory2 workspaceFactory = (IWorkspaceFactory2)Activator.CreateInstance(factoryType);

            return(workspaceFactory.OpenFromFile(path, 0));
        }
Example #10
0
        static IWorkspace OpenRasterPGDBWorkspace(string connStr)
        {
            Type t = Type.GetTypeFromProgID("esriDataSourcesGDB.AccessWorkspaceFactory");

            System.Object      obj = Activator.CreateInstance(t);
            IWorkspaceFactory2 workspaceFactory = obj as IWorkspaceFactory2;

            return(workspaceFactory.OpenFromFile(connStr, 0));
        }
        public static ILocatorWorkspace GetFileGDBLocatorWorkspace(string path)
        {
            // Open a workspace from a file geodatabase
            System.Object      obj = Activator.CreateInstance(Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"));
            IWorkspaceFactory2 workspaceFactory = obj as IWorkspaceFactory2;
            IWorkspace         workspace        = workspaceFactory.OpenFromFile(path, 0); // example of path string is... @"C:\UnitedStates.gdb"

            // Get a locator from the locator Workspace
            obj = Activator.CreateInstance(Type.GetTypeFromProgID("esriLocation.LocatorManager"));
            ILocatorManager2  locatorManager   = obj as ILocatorManager2;
            ILocatorWorkspace locatorWorkspace = locatorManager.GetLocatorWorkspace(workspace);

            return(locatorWorkspace);
        }
Example #12
0
        /// <summary>
        /// 创建shape图层
        /// </summary>
        /// <param name="strShpPath"></param>
        /// <param name="strFtName"></param>
        /// <returns></returns>
        public static IFeatureClass CreateShpFile(string strShpPath, string strFtName, string strAliasFtName, ISpatialReference pSpatial)
        {
            string             connectionstring = "DATABASE=" + strShpPath;
            IWorkspaceFactory2 pFactory         = (IWorkspaceFactory2) new ShapefileWorkspaceFactoryClass();
            IWorkspace         workspace        = pFactory.OpenFromString(connectionstring, 0);
            IFeatureWorkspace  ipFtWs           = (IFeatureWorkspace)workspace;

            //创建字段IFields
            IFields     pFields     = new FieldsClass();
            IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields;
            ///创建几何类型字段
            IField     pField     = new FieldClass();
            IFieldEdit pFieldEdit = (IFieldEdit)pField;

            ////设置FID字段
            //IFieldEdit ipFldEdit = new FieldClass(); //(__uuidof(Field));
            //ipFldEdit.Name_2 = "FID";
            //ipFldEdit.AliasName_2 = "唯一标志码";
            //ipFldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
            //pFieldsEdit.AddField(ipFldEdit);


            pFieldEdit.Name_2      = "Shape";
            pFieldEdit.AliasName_2 = "几何类型";
            pFieldEdit.Type_2      = esriFieldType.esriFieldTypeGeometry;


            IGeometryDef     pGeomDef     = new GeometryDefClass();
            IGeometryDefEdit pGeomDefEdit = (IGeometryDefEdit)pGeomDef;

            pGeomDefEdit.GeometryType_2     = esriGeometryType.esriGeometryPoint;
            pGeomDefEdit.SpatialReference_2 = pSpatial;
            pFieldEdit.GeometryDef_2        = pGeomDef;
            pFieldsEdit.AddField(pField);


            IFeatureClass _featureClass =
                ipFtWs.CreateFeatureClass(strFtName, pFields, null, null, esriFeatureType.esriFTSimple, "Shape", "");

            //更新图层别名
            //IClassSchemaEdit ipEdit = (IClassSchemaEdit)_featureClass;
            //ipEdit.AlterAliasName(strAliasFtName);

            pFactory  = null;
            workspace = null;
            ipFtWs    = null;

            return(_featureClass);
        }
Example #13
0
        public static ITable AbrirTablaDesdeGDB(string sDir, string sNombre)
        {
            try
            {
                IWorkspaceFactory2 pWorkspaceFactory2 = (IWorkspaceFactory2) new AccessWorkspaceFactoryClass();
                IFeatureWorkspace  pFWorkspace        = (IFeatureWorkspace)pWorkspaceFactory2.OpenFromFile(sDir, 0);

                return(pFWorkspace.OpenTable(sNombre));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return(null);
            }
        }
Example #14
0
        /// <summary>
        /// 打开FileGeoDatabase
        /// </summary>
        /// <param name="ppOutWS"></param>
        /// <param name="strFullPath"></param>
        /// <returns></returns>
        public static bool OpenFGDB(ref IWorkspace ppOutWS, string strFullPath)
        {
            try
            {
                string             connectionstring = "DATABASE=" + strFullPath;
                IWorkspaceFactory2 pFactory         = (IWorkspaceFactory2) new FileGDBWorkspaceFactoryClass();
                ppOutWS = pFactory.OpenFromString(connectionstring, 0);
            }
            catch (Exception exp)
            {
                Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString());

                return(false);
            }
            return(true);
        }
Example #15
0
        public static IWorkspace OpenWorkspace(enumDataType wsType, string strPath)
        {
            IWorkspaceFactory2 wsFactory = GetWorkspaceFactory(wsType);

            if (wsFactory == null)
            {
                throw new Exception("调用错误:打开Workspace时传入了未被支持的数据类型");
            }

            try
            {
                return(wsFactory.OpenFromFile(strPath, 0));
            }
            catch (Exception exp)
            {
                throw new Exception("打开Workspace时发生错误,可能的原因是数据路径与数据类型不一致,信息:" + exp.ToString());
            }
        }
Example #16
0
 /// <summary>
 /// 通过连接字符串,获取SDE数据库连接
 /// </summary>
 /// <param name="sConnStr"></param>
 /// <returns></returns>
 public IWorkspace OpenSDEFromString(string sConnStr)
 {
     if (string.IsNullOrEmpty(sConnStr))
     {
         return(null);
     }
     try
     {
         Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory");
         IWorkspaceFactory2 workspaceFactory2 = (IWorkspaceFactory2)Activator.CreateInstance(factoryType);
         return(workspaceFactory2.OpenFromString(sConnStr, 0));
     }
     catch (Exception ep)
     {
         ErrorMessage = "获取SDE数据库连接失败" + ep.Message;
         return(null);
     }
 }
        private IFeatureClass GetFeatureClassInsideDataset(string featureClassName)
        {
            IWorkspaceFactory2 factory = null;

            if (_serverContext != null)
            {
                factory = (IWorkspaceFactory2)_serverContext.CreateObject("esriDataSourcesGDB.SDEWorkspaceFactory");
            }
            //else
            //    factory = new ESRI.ArcGIS.DataSourcesGDB.SdeWorkspaceFactoryClass();
            //TODO COMMENTED ABOVE TO ALLOW COMPILE
            IWorkspace        ipWks            = null;
            IFeatureClass     ipFeatClass      = null;
            IFeatureDataset   ipFeatDS         = null;
            IEnumDataset      ipEnumSubDataset = null;
            IEnumDataset      ipEnumDataset    = null;
            IFeatureWorkspace fws = null;

            try
            {
                IPropertySet2 propSet = null;
                if (_serverContext != null)
                {
                    propSet = (IPropertySet2)_serverContext.CreateObject("esriSystem.PropertySet");
                }
                //else
                //    propSet =  new ESRI.ArcGIS.esriSystem.PropertySetClass();
                //TODO COMMENTED ABOVE TO ALLOW COMPILE
                propSet.SetProperty("SERVER", _sdeServerInfo.server);
                propSet.SetProperty("INSTANCE", _sdeServerInfo.instance);
                propSet.SetProperty("DATABASE", _sdeServerInfo.database);
                propSet.SetProperty("USER", _sdeServerInfo.user);
                propSet.SetProperty("PASSWORD", _sdeServerInfo.password);
                propSet.SetProperty("VERSION", _sdeServerInfo.version);

                ipWks = factory.Open(propSet, 0);
                fws   = (IFeatureWorkspace)ipWks;
                //try and open it
                if (ipWks != null)
                {
                    // Now get all the feature classes included in the datasets
                    ipEnumDataset = ipWks.get_Datasets(esriDatasetType.esriDTFeatureDataset);
                    ipEnumDataset.Reset();
                    ipFeatDS = ipEnumDataset.Next() as IFeatureDataset;
                    while (ipFeatDS != null)
                    {
                        ipEnumSubDataset = ipFeatDS.Subsets; //.get_Datasets(esriDatasetType.esriDTFeatureClass);
                        ipEnumSubDataset.Reset();
                        ipFeatClass = ipEnumSubDataset.Next() as IFeatureClass;
                        while (ipFeatClass != null)
                        {
                            if (ipFeatClass.AliasName.ToUpper().Contains(featureClassName.ToUpper()))
                            {
                                return(ipFeatClass);
                            }
                            ipFeatClass = ipEnumSubDataset.Next() as IFeatureClass;
                        }
                        ipFeatDS         = ipEnumDataset.Next() as IFeatureDataset;
                        ipEnumSubDataset = null;
                    }

                    ipEnumDataset = null;
                }
            }
            catch (System.Runtime.InteropServices.COMException edd)
            {
                ipFeatClass = null;
                throw edd;
            }
            finally
            {
                Util.ReleaseCOMObject(fws);
                Util.ReleaseCOMObject(ipEnumSubDataset);
                Util.ReleaseCOMObject(ipEnumDataset);
                Util.ReleaseCOMObject(factory);
            }

            return(null);
        }
        //search outside datasets
        protected IFeatureClass GetFeatureClass(string featureClassName)
        {
            IWorkspaceFactory2 factory = null;

            if (_serverContext != null)
            {
                factory = (IWorkspaceFactory2)_serverContext.CreateObject("esriDataSourcesGDB.SDEWorkspaceFactory");
            }

            IWorkspace        ipWks            = null;
            IFeatureClass     ipFeatClass      = null;
            IFeatureClass     ipFeatDS         = null;
            IFeatureClass     ipEnumSubDataset = null;
            IEnumDataset      ipEnumDataset    = null;
            IFeatureWorkspace fws = null;

            try
            {
                IPropertySet2 propSet = null;
                if (_serverContext != null)
                {
                    propSet = (IPropertySet2)_serverContext.CreateObject("esriSystem.PropertySet");
                }

                propSet.SetProperty("SERVER", _sdeServerInfo.server);
                propSet.SetProperty("INSTANCE", _sdeServerInfo.instance);
                propSet.SetProperty("DATABASE", _sdeServerInfo.database);
                propSet.SetProperty("USER", _sdeServerInfo.user);
                propSet.SetProperty("PASSWORD", _sdeServerInfo.password);
                propSet.SetProperty("VERSION", _sdeServerInfo.version);

                ipWks = factory.Open(propSet, 0);
                fws   = (IFeatureWorkspace)ipWks;

                //try and open it
                if (ipWks != null)
                {
                    ipEnumDataset = ipWks.get_Datasets(esriDatasetType.esriDTFeatureClass);
                    ipEnumDataset.Reset();
                    ipFeatDS = ipEnumDataset.Next() as IFeatureClass;
                    while (ipFeatDS != null)
                    {
                        ipEnumSubDataset = ipFeatDS;
                        ipFeatClass      = ipEnumSubDataset;
                        while (ipFeatClass != null)
                        {
                            if (ipFeatClass.AliasName.ToUpper().Contains(featureClassName.ToUpper()))
                            {
                                return(ipFeatClass);
                            }
                            ipFeatClass = ipEnumDataset.Next() as IFeatureClass;
                        }
                        ipFeatDS         = ipEnumDataset.Next() as IFeatureClass;
                        ipEnumSubDataset = null;
                    }

                    ipEnumDataset = null;
                }
            }
            catch (System.Runtime.InteropServices.COMException edd)
            {
                //exception is coming from Arcobjects...
                ipFeatClass = null;
                throw edd;
            }
            finally
            {
                Util.ReleaseCOMObject(fws);
                Util.ReleaseCOMObject(ipEnumSubDataset);
                Util.ReleaseCOMObject(ipEnumDataset);
                Util.ReleaseCOMObject(factory);
            }
            return(GetFeatureClassInsideDataset(featureClassName));
        }
Example #19
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 #20
0
        } // ConnectToGDB

        private static void UpdateDatalayerInfo(ITable table, Boolean verbose)
        {
            String       server       = "";
            String       dbclient     = "";
            String       instanceOrig = "";
            String       instanceNew  = "";
            IDataLayer   dataLayer    = null;
            IRasterLayer rasterLayer  = null;

            if (table is IRasterLayer)
            {
                rasterLayer = (IRasterLayer)table;
                dataLayer   = (IDataLayer)rasterLayer;
            }
            else
            {
                dataLayer = (IDataLayer)table;
            }

            IName           n   = dataLayer.DataSourceName;
            IDatasetName    dsn = (IDatasetName)n;
            IWorkspaceName2 wsn = (IWorkspaceName2)dsn.WorkspaceName;

            IWorkspaceFactory2 wsFact    = (IWorkspaceFactory2)wsn.WorkspaceFactory;
            IWorkspace2        workspace = (IWorkspace2)wsFact.OpenFromString(wsn.ConnectionString.ToString(), 0);

            // Access connection properties, update, and re-apply
            IPropertySet propertySet = wsn.ConnectionProperties;

            // Confirm original
            server       = propertySet.GetProperty("SERVER").ToString();
            instanceOrig = propertySet.GetProperty("INSTANCE").ToString();

            if (verbose)
            {
                Console.WriteLine("Original: {0}, {1}", server, instanceOrig);
            }

            // Only need to set if currently app server, check if "instance" string has a colon in it
            // Is there a way to check this based on the list by source so that we don't have to check every layer?
            if (instanceOrig.Contains(":") == false)
            {
                // Determine what kind of DBMS we are working with (Oracle, SqlServer, etc.)
                IDatabaseConnectionInfo3 dbmsConnInfo = (IDatabaseConnectionInfo3)workspace;

                // Set the DBCLIENT to the appropriate dbms
                switch (dbmsConnInfo.ConnectionDBMS)
                {
                case esriConnectionDBMS.esriDBMS_Oracle:
                    dbclient    = "Oracle";
                    instanceNew = String.Format("{0}/{1}", dbmsConnInfo.ConnectionServer, dbmsConnInfo.ConnectedDatabaseEx);
                    break;

                case esriConnectionDBMS.esriDBMS_SQLServer:
                    dbclient    = "SQLServer";
                    instanceNew = dbmsConnInfo.ConnectionServer;
                    break;

                case esriConnectionDBMS.esriDBMS_PostgreSQL:
                    dbclient    = "PostgreSQL";
                    instanceNew = dbmsConnInfo.ConnectionServer;
                    break;

                default:
                    dbclient = "";
                    break;
                }

                // Set to new target
                propertySet.SetProperty("DBCLIENT", dbclient);
                propertySet.SetProperty("DB_CONNECTION_PROPERTIES", instanceNew);

                // INSTANCE needs to be cleared out for Raster layers
                if (table is IRasterLayer)
                {
                    propertySet.SetProperty("INSTANCE", "");//propertySet.SetProperty("INSTANCE", String.Format("sde:{0}",dbclient.ToLower()));
                }
                wsn.ConnectionProperties = propertySet;

                // Confirm target was set
                propertySet = null;
                propertySet = wsn.ConnectionProperties;

                if (verbose)
                {
                    Console.WriteLine("NEW: {0}, {1}", propertySet.GetProperty("DBCLIENT"), propertySet.GetProperty("DB_CONNECTION_PROPERTIES"));
                    Console.WriteLine("----------------");
                }
            } // End if
        }     // UpdateDatalayerInfo
Example #21
0
        private static bool CreateShpFile(string shpPath, ISpatialReference spatialReference)
        {
            bool result = true;
            IWorkspaceFactory2 workspaceFactory = null;
            IWorkspace         workspace        = null;
            IFeatureClass      featureClass     = null;

            try
            {
                FileInfo info      = new FileInfo(shpPath);
                string   directory = info.DirectoryName;
                string   name      = info.Name.Substring(0, info.Name.Length - info.Extension.Length);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                workspaceFactory = new ShapefileWorkspaceFactoryClass();
                workspace        = workspaceFactory.OpenFromFile(directory, 0);

                if (workspace == null)
                {
                    result = false;
                }
                else
                {
                    if (EngineAPI.IsNameExist(workspace, name, esriDatasetType.esriDTFeatureClass))
                    {
                        EngineAPI.DeleteDataset(workspace, name, esriDatasetType.esriDTFeatureClass);
                    }
                    IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass();
                    IFields requiredFields = objectClassDescription.RequiredFields;
                    if (requiredFields == null)
                    {
                        result = false;
                    }
                    featureClass = CreateFeatureClass(workspace, name, requiredFields, spatialReference);
                    if (featureClass == null)
                    {
                        result = false;
                    }
                }

                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (featureClass != null)
                {
                    Marshal.ReleaseComObject(featureClass);
                }
                if (workspace != null)
                {
                    Marshal.ReleaseComObject(workspace);
                }
                if (workspaceFactory != null)
                {
                    Marshal.ReleaseComObject(workspaceFactory);
                }
            }
        }
Example #22
0
        /// <summary>
        /// 创建shp文件
        /// </summary>
        /// <param name="shpPath">入样总体文件</param>
        /// <param name="SampleTable">抽样样本表</param>
        /// <param name="sampleFile">生成样本shp</param>
        /// <returns>是否创建成功</returns>
        public bool CreateShpFile(string shpPath, DataTable SampleTable, string sampleFile)
        {
            bool result = true;
            IWorkspaceFactory2 workspaceFactory = null;
            IWorkspace         workspace        = null;
            IFeatureClass      allVillage       = null;
            ISpatialReference  spatialReference = null;
            IFeatureClass      sampleClass      = null;

            try
            {
                //获取入样总体的坐标信息
                allVillage       = EngineAPI.OpenFeatureClass(shpPath);
                spatialReference = (allVillage as IGeoDataset).SpatialReference;

                //ISpatialReference spatialReference = pGeoDataset.SpatialReference;

                FileInfo info      = new FileInfo(sampleFile);
                string   directory = info.DirectoryName;
                string   name      = info.Name.Substring(0, info.Name.Length - info.Extension.Length);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                workspaceFactory = new ShapefileWorkspaceFactoryClass();
                workspace        = workspaceFactory.OpenFromFile(directory, 0);

                if (workspace == null)
                {
                    result = false;
                }
                else
                {
                    if (EngineAPI.IsNameExist(workspace, name, esriDatasetType.esriDTFeatureClass))
                    {
                        EngineAPI.DeleteDataset(workspace, name, esriDatasetType.esriDTFeatureClass);
                    }

                    IFields requiredFields = allVillage.Fields;
                    if (requiredFields == null)
                    {
                        result = false;
                    }
                    sampleClass = CreateFeatureClass(workspace, name, requiredFields, spatialReference);
                    //添加字段
                    AddFields(sampleClass, _expand);
                    if (sampleClass == null)
                    {
                        result = false;
                    }

                    //添加要素
                    IFeatureCursor pFeaCur  = sampleClass.Insert(true);
                    IFeatureBuffer pFeaBuf  = null;
                    IFeature       pFeature = null;
                    for (int i = 0; i < SampleTable.Rows.Count; i++)
                    {
                        pFeature      = allVillage.GetFeature(Convert.ToInt32(SampleTable.Rows[i][0]));
                        pFeaBuf       = sampleClass.CreateFeatureBuffer();
                        pFeaBuf.Shape = pFeature.ShapeCopy;

                        //添加字段值
                        for (int j = 2; j < requiredFields.FieldCount; j++)
                        {
                            pFeaBuf.set_Value(j, SampleTable.Rows[i][j]);
                            //IField pField = requiredFields.get_Field(j);
                            //int iIndex = pFeaBuf.Fields.FindField(pField.Name);
                            //if (iIndex != -1)
                            //{
                            //    pFeaBuf.set_Value(iIndex, SampleTable.Rows [i][j]);
                            //}
                        }
                        int fIndex = pFeaBuf.Fields.FindField(_expand);
                        if (fIndex > 0 && SampleTable.Columns.Contains(_expand))
                        {
                            pFeaBuf.set_Value(fIndex, SampleTable.Rows[i][_expand]);
                        }

                        pFeaCur.InsertFeature(pFeaBuf);
                    }

                    //保存要素
                    pFeaCur.Flush();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeaCur);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeaBuf);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeature);
                }
                ////删除添加的字段
                //IFields fields = allVillage.Fields;
                //IField field = fields.get_Field(fields.FindField(_expand));
                //allVillage.DeleteField(field);
                return(result);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                Log.WriteLog(typeof(SampleSimulation), ex);
                return(result);
            }
            finally
            {
                if (sampleClass != null)
                {
                    Marshal.ReleaseComObject(sampleClass);
                }
                if (spatialReference != null)
                {
                    Marshal.ReleaseComObject(spatialReference);
                }
                if (allVillage != null)
                {
                    Marshal.ReleaseComObject(allVillage);
                }
                if (workspace != null)
                {
                    Marshal.ReleaseComObject(workspace);
                }
                if (workspaceFactory != null)
                {
                    Marshal.ReleaseComObject(workspaceFactory);
                }
            }
        }